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

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/

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

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