There is only Miku

Result of work on FSGL library with OpenGL ES and code:

Next I will describe how all this was programmed, and how various interesting problems were solved.

First we initialize the OpenGL ES context, as I wrote in the previous note. Further we will consider only rendering, a brief description of the code.

The Matrix is ​​watching you

This Miku figure in the video is made up of triangles. To draw a triangle in OpenGL, you need to specify three points with x, y, z coordinates in the 2D coordinates of the OpenGL context.
Since we need to draw a figure containing 3D coordinates, we need to use the projection matrix. We also need to rotate, zoom, or do anything with the model – for this, the model matrix is used. There is no concept of a camera in OpenGL, in fact, objects rotate around a static camera. For this, the view matrix is used.

To simplify the implementation of OpenGL ES – it does not have matrix data. You can use libraries that add missing functionality, such as GLM.

Shaders

In order to allow the developer to draw whatever and however he wants, it is necessary to implement vertex and fragment shaders in OpenGL ES. A vertex shader must receive rendering coordinates as input, perform transformations using matrices, and pass the coordinates to gl_Position. A fragment or pixel shader – already draws the color/texture, applies overlay, etc.

I wrote the shaders in GLSL. In my current implementation, the shaders are embedded directly into the main application code as C strings.

Buffers

The vertex buffer contains the coordinates of the vertices (vertices), this buffer also receives coordinates for texturing and other data necessary for shaders. After generating the vertex buffer, you need to bind a pointer to the data for the vertex shader. This is done with the glVertexAttribPointer command, where you need to specify the number of elements, a pointer to the beginning of the data and the step size that will be used to walk through the buffer. In my implementation, the binding of vertex coordinates and texture coordinates for the pixel shader is done. However, it is worth mentioning that the transfer of data (texture coordinates) to the fragment shader is carried out through the vertex shader. For this, the coordinates are declared using varying.

In order for OpenGL to know in what order to draw the points for triangles – you need an index buffer (index). The index buffer contains the number of the vertex in the array, with three such indices you get a triangle.

Textures

First, you need to load/generate a texture for OpenGL. For this, I used SDL_LoadBMP, the texture is loaded from a bmp file. However, it is worth noting that only 24-bit BMPs are suitable, and the colors in them are not stored in the usual RGB order, but in BGR. That is, after loading, you need to replace the red channel with blue.
Texture coordinates are specified in the UV format, i.e. it is necessary to transmit only two coordinates. The texture is output in the fragment shader. To do this, it is necessary to bind the texture to the fragment shader.

Nothing extra

Since, according to our instructions, OpenGL draws 3D via 2D – then to implement depth and sampling of invisible triangles – we need to use sampling (culling) and a depth buffer (Z-Buffer). In my implementation, I managed to avoid manual generation of the depth buffer using two commands glEnable(GL_DEPTH_TEST); and sampling glEnable(GL_CULL_FACE);
Also, be sure to check that the near plane for the projection matrix is ​​greater than zero, since depth checking with a zero near plane will not work.

Rendering

To fill the vertex buffer, index buffer with something conscious, for example the Miku model, you need to load this model. For this, I used the assimp library. Miku was placed in a Wavefront OBJ file, loaded using assimp, and data conversion from assimp to vertex, index buffers was implemented.

Rendering takes place in several stages:

  1. Rotate Miku using the model matrix rotation
  2. Clearing the screen and depth buffer
  3. Drawing triangles using the glDrawElements command.

The next step is to implement WebGL rendering using Emscripten.

Source code:
https://github.com/demensdeum/OpenGLES3-Experiments/tree/master/8-sdl-gles-obj-textured-assimp-miku
Model:
https://sketchfab.com/models/7310aaeb8370428e966bdcff414273e7

 

Project it

Having drawn a red teapot in 3D, I consider it my duty to briefly describe how it is done.

Modern OpenGL does not draw 3D, it only draws triangles, points, etc. in 2D screen coordinates.
To output anything with OpenGL, you need to provide a vertex buffer, write a vertex shader, add all the necessary matrices (projection, model, view) to the vertex shader, link all the input data to the shader, call the rendering method in OpenGL. Seems simple?


Ok, what is a vertex buffer? A list of coordinates to draw (x, y, z)
The vertex shader tells the GPU what coordinates to draw.
A pixel shader tells what to draw (color, texture, blending, etc.)
Matrices translate 3D coordinates into 2D coordinates OpenGL can render

In the following articles I will provide code examples and the result.

SDL2 – OpenGL ES

I love Panda3D game engine. But right now this engine is very hard to compile and debug on Microsoft Windows operation system. So as I said some time ago, I begin to develop my own graphics library. Right now it’s based on OpenGL ES and SDL2.
In this article I am going to tell how to initialize OpenGL ES context and how SDL2 helps in this task. We are going to show nothing.

King Nothing

First of all you need to install OpenGL ES3 – GLES 3 libraries. This operation is platform dependant, for Ubuntu Linux you can just type sudo apt-get install libgles2-mesa-dev. To work with OpenGL you need to initialize OpenGL context. There is many ways to do that, by using one of libraries – SDL2, GLFW, GLFM etc. Actually there is no one right way to initialize OpenGL context, but I chose SDL2 because it’s cross-platform solution, code will look same for Windows/*nix/HTML5/iOS/Android/etc.

To install sdl2 on Ubuntu use this command sudo apt-get install libsdl2-dev

So here is OpenGL context initialization code with SDL2:

    SDL_Window *window = SDL_CreateWindow(
            "SDL2 - OGLES",
            SDL_WINDOWPOS_UNDEFINED,
            SDL_WINDOWPOS_UNDEFINED,
            640,
            480,
            SDL_WINDOW_OPENGL
            );
	    

    SDL_GLContext glContext = SDL_GL_CreateContext(window);

After that, you can use any OpenGL calls in that context.

Here is example code for this article:
https://github.com/demensdeum/OpenGLES3-Experiments/tree/master/3sdl-gles
https://github.com/demensdeum/OpenGLES3-Experiments/blob/master/3sdl-gles/sdlgles.cpp

You can build and test it with command cmake . && make && ./SDLGles

Flame Steel Core

Screenshot from the latest version of Death Mask:

Looks like a million dollars huh?

< /blockquote>

Renaming, splitting

The Flame Steel Engine library has been renamed to Flame Steel Core, Game Toolkit has been split into SDL, Panda3D (Desktop) and Web (ThreeJS) libraries. If you have steel balls to build with Flame Steel libraries, you should first select and build the ones you need.

Github:

https://github.com/demensdeum/Death-Mask
https://github.com/demensdeum/FlameSteelCore
https://github.com/demensdeum/FlameSteelEngineGameToolkit
https://github.com/demensdeum/FlameSteelEngineGameToolkitDesktop

Deprecated:

https://github.com/demensdeum/FlameSteelEngineGameToolkitSDL
https://github.com/demensdeum/FlameSteelEngineGameToolkitWeb

Quantum hacking of RSA

The other day I wrote my implementation of the RSA public key encryption algorithm. I also did a simple hack of this algorithm, so I wanted to write a short note on this topic. RSA’s resistance to hacking is based on the factorization problem. Factorization… What a scary word.

It’s not all that bad

In fact, at the first stage of creating keys, we take two random numbers, but the numbers should only be divisible by themselves and one – prime numbers.
Let’s call them p and q. Next, we should get the number n = p *q. It will be used for further key generation, the keys in turn will be used for encryption, decryption of messages. In the final version of the private and public key, the number n will be transmitted unchanged.
Let’s say we have one of the RSA keys and an encrypted message. We extract the number n from the key and start hacking it.

Factorize n

Factorization – decomposition of a number into prime factors. First, we extract the number n from the key (on real keys, this can be done using openssl), let’s say n = 35. Then we decompose into prime factors n = 35 = 5 * 7, this is our p and q. Now we can regenerate keys using the obtained p, q, decrypt the message and encrypt, ensuring the visibility of the original author.

Qubits are not that simple

Is it really possible to break any RSA so easily? Actually, no, the numbers p, q are taken deliberately large so that the factorization task on classical computers would take a very long time (10 years to some degree)
However, using Shor’s quantum algorithm, it is possible to factor a number in a very short time. At the moment, articles on this topic state the time of multiplication of this number, i.e., practically instantly. For Shor’s algorithm to work, it is necessary to implement quantum computers with a large number of qubits. In 2001, IBM factored the number 15 into prime factors using 7 qubits. So we will have to wait a long time for this moment, by which time we will have switched to post-quantum encryption algorithms.

Touch Shor

Peter Shor talks about his factorization algorithm

To try out Shor’s algorithm on a quantum simulator, you can install ProjectQ, whose examples include an implementation of shor.py that allows you to factorize a number entered by the user. On the simulator, the execution time is depressing, but it seems to simulate the work of a quantum computer in a fun and playful way.

Articles:
http://www.pagedon.com/rsa-explained-simply/my_programming/
http://southernpacificreview.com/2014/01/06/rsa-key-generation-example/
https://0day.work/how-i-recovered-your-private-key-or-why-small-keys-are-bad/

RSA implementation in Python:
https://github.com/demensdeum/RSA-Python

Russian Quantum Hack and Number Generator

[Translation may be, some day]

Эта заметка увеличит длину вашего резюме на 5 см!

Без лишних слов о крутости квантовых компьютеров и всего такого, сегодня я покажу как сделать генератор чисел на реальном квантовом процессоре IBM.
Для этого мы будем использовать всего один кубит, фреймворк для разработки квантового ПО для python – ProjectQ, и 16 кубитовый процессор от IBM, онлайн доступ к которому открыт любому желающему по программе IBM Quantum Experience.

Установка ProjectQ

Для начала у вас должен быть Linux, Python и pip. Какие либо инструкции по установке этих базовых вещей приводить бесполезно, т.к. в любом случае инструкции устареют через неделю, поэтому просто найдите гайд по установке на официальном сайте. Далее устанавливаем ProjectQ, гайд по установке приведен в документации. На данный момент все свелось к установке пакета ProjectQ через pip, одной командой: python -m pip install –user projectq

Ставим кубит в суперпозицию

Создаем файл quantumNumberGenerator.py и берем пример генератора бинарного числа из документации ProjectQ, просто добавляем в него цикл на 32 шага, собираем бинарную строку и переводим в 32-битное число:

import projectq.setups.ibm
from projectq.ops import H, Measure
from projectq import MainEngine
from projectq.backends import IBMBackend

binaryString = ""

eng = MainEngine()

for i in range(1, 33):

 qubit = eng.allocate_qubit()

 H | qubit

 Measure | qubit

 eng.flush()

 binaryString = binaryString + str(int(qubit))

 print("Step " + str(i))

number = int(binaryString, 2)

print("\n--- Quantum 32-Bit Number Generator by demensdeum@gmail.com (2017) ---\n")
print("Binary: " + binaryString)
print("Number: " + str(number))
print("\n---")

Запускаем и получаем число из квантового симулятора с помощью команды python quantumNumberGenerator.py

Незнаю как вы, но я получил вывод и число 3974719468:

--- Quantum 32-Bit Number Generator by demensdeum@gmail.com (2017) ---

Binary: 11101100111010010110011111101100
Number: 3974719468

---

Хорошо, теперь мы запустим наш генератор на реальном квантовом процессоре IBM.

Хакаем IBM

Проходим регистрацию на сайте IBM Quantum Experience, подтверждаем email, в итоге должен остаться email и пароль для доступа.
Далее включаем айбиэмовский движок, меняем строку eng = MainEngine() -> eng = MainEngine(IBMBackend())
В теории после этого вы запускаете код снова и теперь он работает на реальном квантовом процессоре, используя один кубит. Однако после запуска вам придется 32 раза набрать свой email и пароль при каждой аллокации реального кубита. Обойти это можно прописав свой email и пароль прямо в библиотеки ProjectQ.

Заходим в папку где лежит фреймворк ProjectQ, ищем файл с помощью grep по строке IBM QE user (e-mail).
В итоге я исправил строки в файле projectq/backends/_ibm/_ibm_http_client.py:

email = input_fun('IBM QE user (e-mail) > ') -> email = "quantumPsycho@aport.ru"

password = getpass.getpass(prompt='IBM QE password > ') -> password = "ilovequbitsandicannotlie"

Напишите свой email и password со-но.

После этого IBM будет отправлять результаты работы с кубитом онлайн прямо в ваш скрипт, процесс генерации занимает около 20 секунд.

Возможно в дальнейшем я доберусь до работы квантового регистра, и возможно будет туториал, но это не обязательно.
Да прибудет с вами запутанность.

Статья на похожую тему:
Introducing the world’s first game for a quantum computer

Death Mask

From today I start developing a roguelike game in a cyberpunk setting – Death Mask.
In fact, this was supposed to be the first game on the new Flame Steel Engine toolchain, but the engine had to be improved before full 3D appeared.
The original title was “Flame Steel: Call Of The Death Mask”, then I decided to simplify the task and release only part of the game “Flame Steel: Zombie Night”
However, the idea of ​​creating a normal full-fledged project did not give me peace, and the name was also overloaded with the name of the Flame Steel universe.
For visual inspiration, I take the manga Biomega and Blame! as the Flame Steel universe itself is very similar to Shadowrun in space.
So don’t be surprised if in this game you meet an alien mage shooting a werewolf with magic bullets from a revolver, with precise aim from a cyber implant in his eye.

The game is being developed under an MIT open source license on GitHub, using the Flame Steel Engine toolchain and free frameworks.

GitHub:
https://github.com/demensdeum/Death-Mask

Bad Robots on WebGL based on ThreeJS

Today, a version of the Bad Robots game is released on an experimental WebGL renderer based on the library ThreeJS.
This is the first OpenGL (WebGL) game on the Flame Steel Engine.
You can play it at the link:
http://demensdeum.com/games/BadRobotsGL/

The source code for IOSystem based on ThreeJS is available here:
https://github.com/demensdeum/FlameSteelEngineGameToolkitWeb

Porting SDL C++ Game to HTML5 (Emscripten)

[Translation may be some day]

За последний год я написал простейший движок Flame Steel Engine и набор классов для игровой разработки Flame Steel Engine Game Toolkit. В данной статье я опишу как производил портирование движка и SDL игры Bad Robots на HTML 5, с использованием компилятора Emscripten.

Установка Hello World – Emscripten

Для начала нужно установить Emscripten. Простейшим вариантом оказалось использование скрипта emsdk для Linux. На официальном сайте данный тип установки называется как “Portable Emscripten SDK for Linux and OS X“. Внутри архива есть инструкция по установке с использованием скрипта. Я производил установку в директорию ~/emsdk/emsdk_portable.

После установки emscripten нужно проверить корректность работы компилятора, для этого создаем простейший hello_world.cpp и собираем его в hello_world.html с помощью команд:

source ~/emsdk/emsdk_portable/emsdk_env.sh
emcc hello_world.cpp -o hello_world.html

После компиляции в папке появится hello_world.html и вспомогательные файлы, откройте его в лучшем браузере Firefox, проверьте что все работает корректно.

Портирование кода игры

В javascript нежелательно вызывать бесконечный цикл – это приводит к зависанию браузера. На данный момент корректная стратегия – запрашивать один шаг цикла у браузера с помощью вызова window.requestAnimationFrame(callback)

В Emscripten данное обстоятельство решено с помощью вызова:

emscripten_set_main_loop(em_callback_func func, int fps, int simulate_infinite_loop);

Таким образом, нужно изменить код игры для корректного вызова метода emscripten. Для этого я сделал глобальный метод GLOBAL_fsegt_emscripten_gameLoop, в котором вызываю шаг цикла игрового контроллера. Главный игровой контроллер также вынесен в глобальную видимость:

#ifdef __EMSCRIPTEN__

void GLOBAL_fsegt_emscripten_gameLoop() {

GLOBAL_fsegt_emscripten_gameController->gameLoop();

}
#endif

Также для обработки специфических для Emscripten моментов, нужно использовать макрос __EMSCRIPTEN__.

Ресурсы и оптимизация

Emscripten поддерживает ресурсы и сборку с оптимизацией.

Для добавления изображений, музыки и прочего, положите все файлы в одну папку, например data. Далее в скрипт сборки добавьте:

emcc <файлы для сборки> –use-preload-plugins –preload-file data

Флаг –use-preload-plugins включает красивый прелоадер в углу экрана, –preload-file добавляет указанный ресурс в файл <имя проекта>.data
Код постоянно останавливался с ошибками доступа к ресурсам, пока я не включил оба этих флага. Также стоит заметить что для корректного доступа к ресурсам, желательно запускать игру на https (возможно и http) сервере, или отключить защиту локального доступа к файлам в вашем браузере.

Для включения оптимизации добавьте флаги:

-s TOTAL_MEMORY=67108864 -O3 -ffast-math

TOTAL_MEMORY – оперативная память в байтах(?) необходимая для корректной работы игры. Вы можете использовать флаг для динамического выделения памяти, но тогда часть оптимизаций работать не будет.

Производительность

Код javascript из C++ работает гораздо медленнее, даже со включенными оптимизациями. Поэтому если ваша цель это разработка для HTML5, то приготовьтесь к ручной оптимизации алгоритмов игры, паралелльному тестированию, также к написанию javascript кода вручную в особо узких местах. Для написания javascript кода используется макрос EM_ASM. Во время реализации рейкастера на emscripten, мне удалось добиться повышения fps с 2-4 до 30 с помощью прямого использования методов canvas.drawImage, в обход обертки SDL->Canvas, что почти приравнялось к написанию всего на javascript.

Поддержка SDL

На данный момент почти не работает SDL_TTF, поэтому отрисовка шрифта для Game Score в BadRobots очень проста. SDL_Image, SDL_Mixer работают корректно, в mixer я проверил только проигрывание музыки.

Исходный код Flame Steel Engine, Flame Steel Engine Game Toolkit, игры Bad Robots:

https://github.com/demensdeum/BadRobots
https://github.com/demensdeum/FlameSteelEngine
https://github.com/demensdeum/FlameSteelEngineGameToolkit

Статья на эту тему:

https://hacks.mozilla.org/2012/04/porting-me-my-shadow-to-the-web-c-to-javascriptcanvas-via-emscripten/

Bad Robots – HTML 5 Game

The first game on the Flame Steel Engine.

http://demensdeum.com/games/BadRobots/BadRobots.html

Shoot all the robots on the screen!

Authors:

Robot animation – http://opengameart.org/content/xeon-ultimate-smash-friends
Music – Killers Kevin MacLeod (incompetech.com)

Source code:

https://github.com/demensdeum/BadRobots
https://github.com/demensdeum/FlameSteelEngine
https://github.com/demensdeum/FlameSteelEngineGameToolkit

Beautiful and empty

You get up in the morning, your mom cooks you something to eat, your dad gives you money for Snickers and takes you to school. You go to a good, strict school without bullies. You study excellently – you have several tutors in subjects that you are not predisposed to. There is an honor roll in your school, on which you, along with your grades, should be, ideally, at the very top. Your future is cloudless – every day you are given gifts, candy, cool fashionable clothes. Everything seems fine, but you understand how boring such a life really is. There is no sense of struggle, every step is predetermined, scheduled for several years in advance.

That’s how I feel when I play any Blizzard game. I see a lot of people who can’t play old school games, can’t play something really original, not formulaic (Deadly Premonition or Papers Please) but everyone loves Blizzard games.

I started my acquaintance with their games on PC with Starcraft. After the wild and arcade Command & Conquer, the gameplay seemed very measured, calming to me. The limitation on the number of units, digging into micro-nano operations personally put me to sleep. Then there was a beautiful, but empty clicker game – Diablo 2. Good graphics, generated levels, and zero gameplay, an absolutely meditative and empty pastime. However, my friends were firmly entrenched in Starcraft and Diablo. In the early 2000s, the mind-blowing Warcraft 3 was released. I really liked the single-player company then. However, the multiplayer is very similar to Starcraft and therefore very dull. Then there was no less beautiful, empty Starcraft 2. I played f2p Hearthstone for a while – this game is like a slot machine, at first you win, you start believing in yourself, but then developers come to you with an offer to buy several decks for 500 ₽. Your skill doesn’t decide anything, only the amount of money spent on virtual decks decides.

I recently bought Overwatch, a shooter from Blizzard. I liked the heroine Mei, whose art and cosplay are all over social networks, and as a result, the general wave of advertising in geek communities threw me onto the shore of Overwatch players.

My fears were justified – excellent graphics, different heroes with their own voices, abilities. Not a single crash during the game, everything is at the level of Blizzard. And now, I want to say that the game is again so polished even in the gameplay that it is simply not interesting to play. It really lacks interesting – unexpected moments, risky ideas, the company, as always, took only the best from past years and, having polished it, sent it to conquer the market, not skimping on good promotion.

The only Blizzard game that I really liked is Rock’n’Roll Racing. It does have gameplay, but I suspect that the credit for this goes not to the developer, but to the publisher – Interplay, most likely Interplay helped Blizzard make something truly playable out of the game.

Games Vision #2

Variable heading Games Vision.
I write short reviews of games that I have played recently

wsunhd
SIM
aka Sara is Missing (Android, Monsoon Lab) – ты находишь телефон девушки по имени Сара. Внутри телефона есть встроенный помощник IRIS, она хочет найти свою хозяйку и просит тебя ей в этом помочь. Задача понять что творилось в голове Сары из ее переписки, фоточек и видео, найти где она находится. Игра очень оригинальная и достаточно пугающая. Минус в том что нет локализации на русский и другие языки, нет версии для iOS, хотя очевидно что интерфейс игры копирует продукцию Apple (IRIS – SIRI) Также игра очень короткая.
Rating 7/10

unnamed
The End of The World
(Android, Sean Wenham) – игра про расставание – парня бросила девушка, теперь он бродит в поисках вина и спит под мостом, вспоминая моменты когда они были вместе. Умилительные моменты воспоминаний, грустная музыка, переход в белое, в принципе отличная игра для женской аудитории и некоторых пацанов. Мне не понравилась бюджетная графика с претензией на оригинальность (напоминает Another World Эрика Шайи), нулевой геймплей, попытки выбить из игрока слезки, предсказуемость, десять минут прохождения. Любителям ванили рекомендую.
Rating: 5/10

unnamed

Werewolf Tycoon (Android, Joe Williamson) – a game about a werewolf who eats people in a city park. The graphics and gameplay here are cheerful – childish, the colors are light without gloomy tones, no blood and people look like round cupcakes with funny animations. The rounds are short and simple, the only enemies are journalists with cameras. It sounds, looks and plays very fun. Of the minuses – low difficulty, watching ads for canceling Game Over, the mechanism for withdrawing points to social networks does not work.
Rating: 6/10

Games Vision #1

Variable heading Games Vision.
In this article I will write short reviews of the games I have played recently.

jansen

Don’t even think that this guy has emotions, he just pretends that he does sometimes.

Deus Ex Mankind Divided (PC, Square Enix) – a game about half-human Adam Jensen who is vacationing in Prague and saving the world along the way.
Good graphics, high system requirements, predictable plot, non-standard work of artists – it’s all here. The game offers many options for passing, for example, I managed to get the achievement “pacifist”, for the fact that I did not kill anyone during the entire passage, including bosses.
I liked the pop culture references “The Void Which Binds“, “IRON MADE in China” and others. I didn’t like the huge amount of text – fluff, all sorts of emails storing passwords for doors and characters’ correspondence, the text is absolutely empty and uninteresting. At the time of passing, the game constantly crashed in DirectX 12 mode, autosaves broke, patches seem to be still being released. I decided not to play the DLC because I had already been playing the main game for about 2 weeks, having gotten out of my usual empty life.
Rating 8/10

slayin

Slayin (Android, FDG) – an extraordinary arcade game in pixel style for mobile phones. You need to run and kill monsters, buying equipment in the store. In this game I liked the art, I really liked the chiptune music, it looks like arcades for NES, convenient controls. The game itself was upset by the fact that the gameplay does not take place beyond one scene on the screen, the inability to move around a large level.
Rating 5/10

swordxolan

Sword of Xolan (Android, Alper Sarıkaya) – an arcade platformer in pixel style for mobile phones. A knight or samurai runs around the level and saves people from iron cages. Quite interesting gameplay, convenient controls, large levels. The overall budget of the game is disappointing, cheap art, cheap sound, looped music.
Rating 6/10

bardstale

The Bard’s Tale (Android, inXile entertainment) – a remastered action RPG for mobile phones. An unusual RPG with funny scenes and dialogues. On the disc with the game it was written “turn the disc over to see something terrible”, on the back there was a mirror side of the disc. At one time, I missed this game on PC because of Neverwinter Nights, but now I can play it on my mobile on the bus. For a modern gamer, there are clearly not enough points of where to go and what to do, but that’s why I love old school games, you really need to play them. There is also no ability to save at any point, which is critical for a mobile game. Music, art, I like everything, but I find the current controls on the phone screen inconvenient. And of course, this is not a new game, but simply a re-release for mobile platforms, which I personally consider a big minus.
Rating 7/10

Diluting ECS


Commission: Mad Scientist by Culpeo-Fox on DeviantArt

In this article I will roughly describe the ECS pattern and my implementation in the Flame Steel Engine Game Toolkit. The Entity Component System pattern is used in games, including the Unity engine. Each object in the game is an Entity, which is filled with Components. Why is this necessary if there is OOP?
Then to change the properties, behavior, display of objects directly during the game execution. Such things are not found in real-world applications, the dynamics of changing parameters, properties of objects, display, sound, are more inherent in games than in accounting software.


We didn’t go through bananas

Let’s say we have a banana class in our game. And the game designer wanted bananas to be used as weapons. Let’s say in the current architecture bananas are not related to weapons. Make a banana a weapon? Make all objects weapons?
ECS offers a solution to this pressing problem – all objects in the game must consist of components. Previously, a banana was a Banana class, now we will make it, and all other objects, an Entity class, and add components to them. Let’s say a banana now consists of components:

  1. Position component (coordinates in the game world – x, y, z)
  2. Rotation component (x, y, z coordinates)
  3. The calorie content of a banana (the main character can’t get too fat)
  4. Banana picture component

We are now adding a new component to all bananas, which is a flag that it can be used as a weapon – Weapon Component. Now when the game system sees that a player has approached a banana, it checks whether the banana has a weapon component, and if it does, it arms the player with a banana.
In my game Flame Steel Call Of The Death Mask, the ECS pattern is used everywhere. Objects consist of components, components themselves can contain components. In general, the separation of object < – > component is absent in my implementation, but this is even a plus.

screenshot_2016-09-24_14-33-43

The shotgun in this screenshot is a player component, while the second shotgun is just hanging on the game map like a normal object.
In this screenshot, there are two Systems running – the scene renderer and the interface renderer. The scene renderer is working with the shotgun image component on the map, the interface renderer is working with the shotgun image component in the player’s hands.

Related links:
https://habrahabr.ru/post/197920/
https://www.youtube.com/watch?v=NTWSeQtHZ9M

Flame Steel Engine Game Toolkit Architecture

Today I will talk about the architecture of the game development toolkit Flame Steel Engine Game Toolkit.
Flame Steel Engine Game Toolkit allows you to create games based on the Flame Steel Engine:
flamesteelgametoolkitschematics

All classes of the Flame Steel Engine engine start with the FSE prefix (Flame Steel Engine), and FSEGT (Flame Steel Engine Game Toolkit) for the toolkit.
Game scene, objects, buttons, all these are subclasses of FSEObject and must be inside the FSEGTGameData class. Each FSEObject must implement the FSESerialize interface, this will allow saving/loading game data, providing a saving mechanism.
FSEController class works with objects of the FSEObject class. The toolkit has a base game scene controller class – FSEGTGameSceneController, you can inherit this class to implement your game logic.
IOSystem is an object of FSEGTIOSystem interface, this interface contains FSEGTRenderer, FSEGTInputController, FSEGTUIRenderer.
FSEGTIOSystem must implement a renderer, receive data from the keyboard, joysticks (input devices) and provide rendering of interface elements for the input-output system of this platform.
At the moment, a renderer and keyboard controller based on the SDL library have been implemented, it is available in the FSEGTIOSDLSystem class.

Flame Steel Engine Raycaster Demo
Flame Steel Engine Raycaster Demo

Future plans to create an IOSystem based on OpenGL, the class will be called FSEGTIOGLSystem. If you want to create an IOSystem based on any platform, then you need to use the FSEGTIOSystem interface and implement the FSEGTRenderer renderer, FSEGTInputController input controller for this platform.

Source code of Flame Steel Engine, toolkit, game:
https://github.com/demensdeum/FlameSteelCallOfTheDeathMask

Unity, why doesn’t Wasteland 2 work on my Ubuntu?

I am proud to be a Wasteland 2 backer. Today I wanted to run it on Ubuntu, but I couldn’t. However, after an hour of googling, everything worked out. It turns out that Unity has serious problems with Linux, but by using certain hacks, the game can be launched:

ulimit -Sn 65536~/.local/share/Steam/steamapps/common/Wasteland\ 2\ Director\'s\ Cut/Linux/WL2

Recipe from here:
https://forums.inxile-entertainment.com/viewtopic.php?t=15505

Flame Steel: Courier Nimble Eyes

His name was Revil, and his nickname was Nimble Eyes. His friends called him Nimble. A street-bred, nimble kid, he always knows what’s interesting and who to get it from. For this, he earned the respect of the criminal world of Alterra – 14.
Now he was inside the warehouse of Native Pharm-United. There were huge containers around, the smell of pharmaceuticals.
– Why did you get up? Take it and go.
The clerk said snapping, he looked nervous, shifting from foot to foot, it was clear that he was very afraid. His shirt was wet with sweat.
– I’m from the security service.
The clerk’s face turned pale and he staggered even more.
– So what now?
– On the floor – hands behind your head!
The clerk frowned, took a deep breath, and pulled his hand down. Quick Eyes sensed something was wrong – it looked like he was reaching for a gun. Revil stunned him with a blow to the impudent face, the little body fell in front of him with a pop.
–I asked nicely…
After searching the clerk, Revil found a regular inhaler, the kind used by asthmatics, in place of the gun. He also found an access card to the company’s laboratory sectors. It was a very lucky find.
The Toxic Brothers gang sent him to pick up a batch of the banned substance – endofomil. But Revil didn’t care about the Brothers and their toxicity, he was here for another reason – he intended to draw his lucky ticket.
The elevator doors swung open, Shustryak chose the floor indicated on the map – forty-second. The elevator slowly moved. Revil was thinking about what he would do in the laboratory sector. He was aware of sophisticated security systems, intelligent identity verification systems, brain wave analysis and the like.

Revil by Inc
Revil by Inc

He wasn’t alone here, an employee of the Lorian company agreed to help him cause a system failure, as a result of which Revil would have ten minutes to carry out his plan.
On the thirty-third floor, the elevator stopped, and a loud bang was heard above Revil’s head – something landed with a crash on the roof of the elevator.
Shustryak reached for his pistol, but at that moment metal tentacles broke through the roof of the elevator. They entangled him, there was a grinding sound and the roof of the elevator was turned inside out. A girl’s face looked at him through the hole – cold empty eyes, a metal plate with blinking red indicators on half of her face, deliberately not hidden under the skin.
– Before you die, answer me, why did you come here?
Shustryak couldn’t move, the steel tentacles were squeezing him tighter and tighter, soon he wouldn’t even be able to breathe.
– I have come for what is rightfully mine!
A satisfied grin appeared on the girl’s face. The indicators flashed alternately green and red…

Flame Steel: Call of the Death Mask

Today I’m announcing three projects at once! Wow!
The first project is a base platform for cross-platform application development Flame Steel Engine. The second project is a set of libraries for the base platform Flame Steel Game Toolkit, designed for game development. And the third project is a game with generated levels in a cyber fantasy setting Flame Steel: Call of The Death Mask.
The original is available under the MIT license, game assets will be available under different licenses (check each file separately)

Github link (C++, Eclipse):
https://github.com/demensdeum/FlameSteelCallOfTheDeathMask

Losing yourself

“You can’t be a master of everything” – I’ve always found phrases like these funny. Everyone, users, programmers, bosses, and customers, falls into this trap of specialization. “I want it like Microsoft/Apple/Google”, “Why can’t we just make a Russian iPhone?”, “Why isn’t it like Word/Uber/Photoshop?” – Anyone who is even slightly involved in IT has heard these phrases. These phrases, repeated by different people, sound even funnier.

I’ll ask you, reader – why do you need another Word? Why do you need another Uber? Why do you need another Photoshop? Why do you need it to be like an iPhone?
Why do you tie yourself to only one company’s interfaces and approach? Why do you label yourself as an Apple/Google/Microsoft lover? Why can’t you open your mind to alternative approaches to solving problems, why don’t you want to be more productive?

A lot of Microsoft users didn’t like how the company decided that everyone needed to upgrade to Windows 10. People complain about the iPhone’s inconvenient interfaces, system crashes during updates, design changes that they don’t need, but they still continue to use them because they’re used to it, and having an “iPhone” is a status symbol in modern society.

Sometimes it seems that if Microsoft/Apple/Google were asked to give up their own children in exchange for continuing to work with their products, then due to the high attachment to these products, people would easily give up their children.

Don’t be like them, don’t get attached to one product, look at alternative options. Once I was offered to develop a system for realtors, with an interface on Microsoft Excel, there were also offers to develop an “interactive whiteboard” system on Microsoft PowerPoint. When I asked why Microsoft, they answered that “we’re so used to it”, when I asked if there is licensed software from Microsoft in these companies, they answered evasively, saying that if it is necessary, they will buy it.

Reader, I urge you to study the edges of the IT world, at least in general. If you have been using only Microsoft Windows all your life, try Apple OS X, or Linux. If you only use the iPhone, try using the latest version of Android for at least a week. The moment you switch to the side of only one company, closing yourself off from the products of others, at that moment you lose yourself. Yourself, as a person who can decide for himself what he wants, as a person who can choose the most convenient and productive tool for solving a specific problem.

Programmers of only one platform – another headache for me personally, as I believe, for the IT industry as a whole. Developers who make applications with export only to *.doc or only to *.pdf, developers who are tied to only one outdated commercial database (for example, IBM Informix, or God forbid Firebird), only to one type of hardware (all these non-working programs for x86 on Android), of course, I understand that you are “used to”, but guys, it’s time to change.

In my work I often use unpopular, but very convenient tools. One example – it was necessary to reduce the resolution and compress about 100 photos for fast loading over 3G and output to iPad. That day I heard one of the most typical phrases – “We will have to manually convert all the photos in *Photoshop* to the desired format.” It seemed funny to me because I imagined a person who would manually, like a servant of God, redo all these 100 photos in Photoshop, or try to automate through the built-in mechanism. The point here is that the person is so attached to Photoshop that he did not even suspect the existence of a free, open set of tools like ImageMagick. ImageMagick allows you to do a lot of things with vector and raster images, including being ideal for solving a problem with 100 pictures in 5 minutes.

Be a master of everything, study, try, don’t become a slave to a specific corporation.

16-bit Santa’s Helpers

I received a message in my email:
“Hey, we’re opening a retro game jam here – bibitjam3!!! You should make a game for the 8-16 bit retro platform!!!”
Bah! This is my childhood dream – to make a game for Sega Mega Drive Two.
Well, I tried to make a toy, and I even got something:
rqr
I called the game “Red Queen’s Mess”. The story is this – “The Red Queen was thrown into a deadly labyrinth, now she will kill everyone on her way to freedom.”
You can walk, you can attack the green thing with red eyes, open treasure chests, and move from scene to scene.
This is of course a level “to try” to do at least something for Sega and for the competition.
I use SGDK toolkit – compiler for Motorola 68k based on GCC, libraries for working with Sega Mega hardware.
Now I understand that it was really difficult – to make games 20-30 years ago. For example, each tile – should be divided into pieces of 8×8 pixels and drawn in pieces in turn. Also, the palette for each tile should not exceed 16 colors! Now, of course, it is much easier.
Of course, we need to create a game, sound, and graphics engine for the game, just like now.
You can play Red Queen using Sega Genesis emulator and game ROM:
http://demensdeum.com/games/redQueenRampageSegaGenesis/RedQueenRampage.zip
If you want to see the source code:
http://demensdeum.com/games/redQueenRampageSegaGenesis/RedQueenRampageSource.zip

Tutorial: Making a Game for Android. Spinning the Earth. Rajawali

In the beginning God created the heaven and the earth.

This is the second video in which we make a game for Android. Let’s spin the earth!
Please write to me if you have any questions or if you would like to add something to this course.
Video based on the article Rajawali Basic Setup & Sphere (Maven):
http://www.clintonmedbery.com/basic-rajawali3d-tutorial-for-android/

Rajawali Engine: https://github.com/Rajawali/Rajawali

Plan, commands, links:
1. Install VirtualBox Guest Additions

sudo apt-get install dkmssudo apt-get install linux-headers-$(uname -r)

2. Add Rajawali library to the project
Filebuild.gradle (Project: Demon’s Cave)
Add mavenCentral() < /span>to the buildscript/repositories
sectionAdd
maven { url< /span> “https://oss.sonatype.org/content/repositories/snapshots/” } to the allprojects/repositories section

File build.gradle (Module: app)
Add compile ‘org.rajawali3d:rajawali:1.0.306-SNAPSHOT@aar& #8217; to the dependencies
section

3. Create a Renderer class, initialize the scene, add a sphere and spin!
Source code of class Renderer.java:
https://github.com/clintonmedbery/RajawaliBasicProject/blob/master/app/src/main/java/com/clintonmedbery/rajawalibasicproject/Renderer.java

4. Add Renderer class to MainActivity
Source code of MainActivity.java:
https://github.com/clintonmedbery/RajawaliBasicProject/blob/master/app/src/main/java/com/clintonmedbery/rajawalibasicproject/MainActivity.java

Ground texture:
http://www.clintonmedbery.com/wp-content/uploads/2015/04/earthtruecolor_nasa_big.jpg