Fixing the mobile menu in WordPress


document.addEventListener('DOMContentLoaded', function() {
    new navMenu('primary');
    new navMenu('woo');
});

If you too have not had the iOS/Android blog menu open in your WordPress blog for several years, when using the Seedlet theme, then simply add:
In the closure function of the wp-content/themes/seedlet/assets/js/primary-navigation.js file, next to the default window addEventListener ‘load’ subscription.

Number 2

Comrades, I take pride in projects that were created on the basis of Flame Steel Framework 1 and specifically on Flame Steel Engine 1, namely Death-Mask, Cube Art Project, since all this was conceived as a big experiment, creating a multimedia framework alone that can work on the most platforms. I think the experiment ended successfully immediately after the release of the Cube Art Project.

Now about the decisions that I came to during the development of new projects on FSFramework 1

During the development of Space Jaguar and the Space Jaguar Galaxy Bastards shooter, it became clear that the Flame Steel Framework tools were already outdated, not even having time to become at least somewhat convenient.

Therefore, I decided to develop a completely new Flame Steel Framework 2. The main decision will be to switch to my Rise 2 transpiler language, and the Component System (ECS) will no longer be used architecturally, because. it turned out to be needed only within the framework of game logic with great dynamics. For this reason, in Flame Steel Framework 2, the component system will only be possible while using the scripting languages ​​that are planned to be implemented (at least Lua and JavaScript), an interesting feature is that these languages ​​​​are dynamic in nature, so additional creation of the component system is redundant.

You can follow the development of new projects on the blog and on Gitlab:

https://gitlab.com/demensdeum/rise2

https://gitlab.com/demensdeum/flamesteelengine2

https://gitlab.com/demensdeum/flame-steel-engine-2-demo-projects

https://gitlab.com/demensdeum/space-jaguar-action-rpg

https://gitlab.com/demensdeum/space-jaguar-galaxy-bastards

Characteristics in Space Jaguar Action RPG

The first article about the game in development Space Jaguar Action RPG. In this article I will describe the gameplay feature of the Jaguar – Characteristics.

Many RPGs use a static system of character stats, such as those from DnD (Strength, Constitution, Dexterity, Intelligence, Wisdom, Charisma), or Fallout’s S.P.E.C.I.A.L (Strength, Perception, Endurance, Charisma, Intelligence, Dexterity, Luck).

In Space Jaguar, I plan to implement a dynamic system of characteristics, for example, the main character of the game, Jag, at the start has only three characteristics – Blade mastery (half-sabre), shadow operations (making deals in the criminal world), rogue abilities (picking locks, stealing). During the game, characters will be given and deprived of dynamic characteristics within the game module, all checks will be made based on the level of certain characteristics necessary for a given game situation. For example, Jag will not be able to win a game of chess if he does not have the chess game characteristic, or does not have a sufficient level to pass the check.

To simplify the logic of checks, each characteristic is given a 6-digit code in English letters, a name, a description. For example, for blade ownership:

bladeFightingAbility.name = "BLADFG"; 
bladeFightingAbility.description = "Blade fighting ability"; 
bladeFightingAbility.points = 3;

Перед стартом игрового модуля можно будет просмотреть список публичных проверок необходимых для прохождения, также создатель может скрыть часть проверок для создания интересных игровых ситуаций.

Ноу-хау? Будет ли интересно? Лично я нахожу такую систему интересной, позволяющей одновременно обеспечить свободу творчества создателям игровых модулей, и возможность переноса персонажей из разных, но похожих по характеристикам, модулей для игроков.

Skeletal Animation (Part 2 – Node Hierarchy, Interpolation)

I continue to describe the skeletal animation algorithm as it is implemented in the Flame Steel Engine.

Since this is the most complex algorithm I’ve ever implemented, there may be errors in the development notes. In the previous article about this algorithm, I made a mistake: the bone array is passed to the shader for each mesh separately, not for the entire model.

Hierarchy of nodes

For the algorithm to work correctly, the model must contain a connection between the bones (graph). Let’s imagine a situation in which two animations are played simultaneously – a jump and raising the right hand. The jump animation must raise the model along the Y axis, while the animation of raising the hand must take this into account and rise together with the model in the jump, otherwise the hand will remain in place on its own.

Let’s describe the node connection for this case – the body contains a hand. When the algorithm is processed, the bone graph will be read, all animations will be taken into account with correct connections. In the model’s memory, the graph is stored separately from all animations, only to reflect the connectivity of the model’s bones.

Interpolation on CPU

In the previous article I described the principle of rendering skeletal animation – “transformation matrices are passed from the CPU to the shader at each rendering frame.”

Each rendering frame is processed on the CPU, for each bone of the mesh the engine gets the final transformation matrix using interpolation of position, rotation, magnification. During the interpolation of the final bone matrix, the node tree is traversed for all active node animations, the final matrix is ​​multiplied with the parents, then sent to the vertex shader for rendering.

Vectors are used for position interpolation and magnification, quaternions are used for rotation, since they are very easy to interpolate (SLERP) unlike Euler angles, and they are also very easy to represent as a transformation matrix.

How to Simplify Implementation

To simplify debugging of vertex shader operation, I added simulation of vertex shader operation on CPU using macro FSGLOGLNEWAGERENDERER_CPU_BASED_VERTEX_MODS_ENABLED. Video card manufacturer NVIDIA has a utility for debugging shader code Nsight, perhaps it can also simplify development of complex algorithms of vertex/pixel shaders, however I never had a chance to check its functionality, simulation on CPU was enough.

In the next article I plan to describe mixing several animations, fill in the remaining gaps.

Sources

https://www.youtube.com/watch?v= f3Cr8Yx3GGA

Space Jaguar 3D Action RPG

I haven’t announced new projects for a long time) The next project I’m starting to work on is a 3D action RPG called Space Jaguar. The story is in a sci-fi setting about a cool guy named Jag and his difficult adventure in search of his missing father. There will be 3D graphics on the Flame Steel Engine (or perhaps any other popular one), using the developments of past projects (Death Mask, Cube Art Project), a comedy plot with many references, arcade battles and bosses. I’m not ready to talk about the release dates of the full version, I plan to release the game in parts.

Project repository:
https://gitlab.com/demensdeum/space-jaguar-action-rpg

ZX Spectrum Game Development in C

This is a silly post about developing a game for an old ZX Spectrum computer in C. Let’s take a look at the beauty:

It began production in 1982 and was produced until 1992. Technical characteristics of the machine: 8-bit Z80 processor, 16-128 KB of memory and other extensions, such as the AY-3-8910 sound chip.

As part of the Yandex Retro Games Battle 2019 competition, I wrote a game called Interceptor 2020 for this machine. Since I didn’t have time to learn assembler for the Z80, I decided to develop it in C. As a toolchain, I chose the ready-made set – z88dk, which contains C compilers and many auxiliary libraries to speed up the implementation of applications for the Spectrum. It also supports many other Z80 machines, such as MSX, Texas Instruments calculators.

Next I will describe my superficial flight over the computer architecture, the z88dk toolchain, and show how I managed to implement the OOP approach and use design patterns.

Installation Features

Installation of z88dk should be carried out according to the manual from the repository, however for Ubuntu users I would like to note a feature – if you already have compilers for Z80 installed from deb packages, then you should remove them, since z88dk will access them from the bin folder by default, due to incompatibility of the toolchain compiler versions you most likely will not be able to build anything.

Hello World

Writing Hello World is very simple:

#include 

void main()
{
    printf("Hello World");
}

It’s even easier to assemble a tap file:

zcc +zx -lndos -create-app -o helloworld helloworld.c

To run, use any ZX Spectrum emulator with tap file support, for example online:
http://jsspeccy.zxdemo.org/

Draw on the picture on the whole screen

tl;dr Pictures are drawn in tiles, tiles of size 8×8 pixels, the tiles themselves are embedded in the spectrum font, then the picture is printed in a line of indices.

The sprite and tile output library sp1 outputs tiles using UDG. The image is translated into a set of individual UDGs (tiles), then assembled on the screen using indices. It should be remembered that UDG is used to output text, and if your image contains a very large set of tiles (for example, more than 128 tiles), then you will have to go beyond the set boundaries and erase the default Spectrum font. To get around this limitation, I used a base of 128 – 255 by simplifying the images, leaving the original font in place. About simplifying the images below.

To draw full-screen images, you need to arm yourself with three utilities:
Gimp
img2spec
png2c-z88dk

There is a way for real ZX men, real retro warriors: open a graphic editor using the spectrum palette, knowing the features of image output, prepare it manually and upload it using png2c-z88dk or png2scr.

The simpler way is to take a 32-bit image, switch the number of colors to 3-4 in Gimp, edit it a little, then import it into img2spec so as not to work with color restrictions manually, export png and convert it to a C array using png2c-z88dk.

Please remember that for successful export each tile cannot contain more than two colors.

As a result, you will receive an h file that contains the number of unique tiles. If there are more than ~128, then simplify the image in Gimp (increase the repeatability) and perform the export procedure again.

After exporting, you literally load the “font” from the tiles and print the “text” from the tile indices on the screen. Here is an example from the render “class”:

// грузим шрифт в память
    unsigned char *pt = fullscreenImage->tiles;

    for (i = 0; i < fullscreenImage->tilesLength; i++, pt += 8) {
            sp1_TileEntry(fullscreenImage->tilesBase + i, pt);
    }

    // ставим курсор в 0,0
    sp1_SetPrintPos(&ps0, 0, 0);

    // печатаем строку
    sp1_PrintString(&ps0, fullscreenImage->ptiles);

Drawing sprites on the screen

Next I will describe the method of drawing 16-16 pixel sprites on the screen. I did not get to animation and color changes, because at this stage, as I suppose, I simply ran out of memory. Therefore, the game contains only transparent monochrome sprites.

Draw a monochrome png image 16×16 in Gimp, then use png2sp1sprite to translate it into an asm assembler file, declare arrays from the assembler file in C code, and add the file at the build stage.

After the stage of declaring the sprite resource, it must be added to the screen in the desired position, here is an example of the code for the “class” of the game object:

    struct sp1_ss *bubble_sprite = sp1_CreateSpr(SP1_DRAW_MASK2LB, SP1_TYPE_2BYTE, 3, 0, 0);
    sp1_AddColSpr(bubble_sprite, SP1_DRAW_MASK2,    SP1_TYPE_2BYTE, col2-col1, 0);
    sp1_AddColSpr(bubble_sprite, SP1_DRAW_MASK2RB,  SP1_TYPE_2BYTE, 0, 0);
    sp1_IterateSprChar(bubble_sprite, initialiseColour);

From the names of the functions you can roughly understand the meaning – we allocate memory for the sprite, add two columns 8-8, add color for the sprite.

In each frame the position of the sprite is set:

sp1_MoveSprPix(gameObject->gameObjectSprite, Renderer_fullScreenRect, gameObject->sprite_col, gameObject->x, gameObject->y);

Emulating OOP

There is no syntax for OOP in C, what to do if you still really want it? You need to connect your mind and be enlightened by the thought that such a thing as OOP equipment does not exist, everything ultimately comes to one of the machine architectures, in which there is simply no concept of an object and other related abstractions.

This fact for a long time prevented me from understanding why OOP is needed at all, why it should be used if in the end everything comes to machine code.

However, having worked in product development, I discovered the charms of this programming paradigm, mainly, of course, the flexibility of development, protective mechanisms of the code, with the right approach, reducing entropy, simplifying work in a team. All the listed advantages follow from the three pillars – polymorphism, encapsulation, inheritance.

It is also worth noting the simplification of solving issues related to application architecture, because 80% of architectural problems were solved by computer scientists in the last century and described in the literature on design patterns. Next, I will describe ways to add OOP-like syntax to C.

It is more convenient to use C structures as a basis for storing class instance data. Of course, you can use a byte buffer, create your own structure for classes, methods, but why reinvent the wheel? After all, we are already reinventing the syntax.

Class data

Example of GameObject “class” data fields:

struct GameObjectStruct {
    struct sp1_ss *gameObjectSprite;
    unsigned char *sprite_col;
    unsigned char x;
    unsigned char y;
    unsigned char referenceCount;
    unsigned char beforeHideX;
    unsigned char beforeHideY;
};
typedef struct GameObjectStruct GameObject;

We save our class as “GameObject.h”, #include “GameObject.h” in the right place and use it.

Class Methods

Let’s take the experience of Objective-C language developers into account, the class method signature will be functions in the global scope, the first argument will always be the data structure, then the method arguments. Below is an example of a “method” of the “class” GameObject:

void GameObject_hide(GameObject *gameObject) {
    gameObject->beforeHideX = gameObject->x;
    gameObject->beforeHideY = gameObject->y;
    gameObject->y = 200;
}

The method call looks like this:

GameObject_hide(gameObject);

Constructors and destructors are implemented in the same way. It is possible to implement a constructor as an allocator and field initializer, but I prefer to control object allocation and initialization separately.

Working with memory

Manual memory management of the form using malloc and free wrapped in new and delete macros to match C++:

#define new(X) (X*)malloc(sizeof(X))
#define delete(X) free(X)

For objects that are used by several classes at once, semi-manual memory management is implemented based on reference counting, in the image and likeness of the old Objective-C Runtime ARC mechanism:

void GameObject_retain(GameObject *gameObject) {
    gameObject->referenceCount++;
}

void GameObject_release(GameObject *gameObject) {
    gameObject->referenceCount--;

    if (gameObject->referenceCount < 1) { sp1_MoveSprAbs(gameObject->gameObjectSprite, &Renderer_fullScreenRect, NULL, 0, 34, 0, 0);
        sp1_DeleteSpr(gameObject->gameObjectSprite);
        delete(gameObject);
    }
}

Thus, each class must declare the use of a shared object with retain, and release ownership with release. Modern ARC uses automatic placement of retain/release calls.

We’re making noise!

The Spectrum has a tweeter capable of playing 1-bit music; composers of that time were able to play up to 4 sound channels on it simultaneously.

Spectrum 128k contains a separate sound chip AY-3-8910, which can play tracker music.

A library is provided for using the buzzer in z88dk

What is yet to be discovered

I was interested in getting acquainted with the Spectrum, implementing the game using z88dk, learning many interesting things. I still have a lot to learn, for example, the Z80 assembler, since it allows you to use the full power of the Spectrum, working with memory banks, working with the AY-3-8910 sound chip. I hope to participate in the contest next year!

Links

https://rgb.yandex
https://vk.com/sinc_lair
https://www.z88dk.org/forum/

Source code

https://gitlab.com/demensdeum/ zx-projects/tree/master/interceptor2020

Death Mask Wild Beta

Death-Mask game enters public beta (wild beta)
The game’s main menu screen has been redesigned, a view of the blue zone of the techno-labyrinth has been added, with pleasant music in the background.

Next, I plan to rework the gameplay controller, add smooth movement like in old shooters, high-quality 3D models of boxes, weapons, enemies, the ability to move to other levels of the techno-labyrinth not only through portals (elevators, doors, falling through holes in the floor, holes in the walls), I will add a little variety to the environment of the generated labyrinth. I will also work on the game balance.
Skeletal animation will be added during the polishing phase before release.

The Good, the Bad and the Ugly Singleton

In this note, I will describe my experience and the experience of my colleagues when working with the Singleton pattern (Singleton in foreign literature), when working on various (successful and not so) projects. I will describe why I personally think this pattern cannot be used anywhere, I will also describe what psychological factors in the team affect the integration of this anti-pattern. Dedicated to all fallen and crippled developers who tried to understand why it all started with one of the team members bringing a cute little puppy, easy to handle, not requiring special care and knowledge on caring for it, and ended with the fact that the bred beast took your project hostage, demands more and more man-hours and eats up the human-nerves of users, your money and draws absolutely monstrous figures for assessing the implementation of seemingly simple things.


Wolf in sheep’s clothing by SarahRichterArt

The story takes place in an alternate universe, all coincidences are random…

Pet a cat at home with Cat@Home

Every person sometimes in life has an irresistible desire to pet a cat. Analysts around the world predict that the first startup to create an application for the delivery and rental of cats will become extremely popular, and in the near future will be bought by the company Moogle for trillions of dollars. Soon this happens – a guy from Tyumen creates the application Cat@Home, and soon becomes a trillionaire, the company Moogle gets a new source of income, and millions of stressed people get the opportunity to order a cat to their home for further petting and calming.

Attack of the Clones

A very rich dentist from Murmansk, Alexey Goloborodko, impressed by an article about Cat@Home from Forbes, decides that he also wants to be astronomically rich. To achieve this goal, through his friends, he finds a company from Goldfield – Wakeboard DevPops, which provides software development services, he orders the development of a clone of Cat@Home from them.

Team of Winners

The project is called Fur&Pure, a talented team of 20 developers is assigned; then we focus on a mobile development group of 5 people. Each team member gets their share of the work, armed with agile and scrum, the team completes the development on time (in six months), without bugs, releases the application in the iStore, where 100,000 users rate it at 5, many comments about how wonderful the application is, how wonderful the service is (it is an alternative universe, after all). The cats are ironed, the application is released, everything seems to be going well. However, Moogle is in no hurry to buy a startup for trillions of dollars, because Cat@Home has already appeared not only cats but also dogs.

The dog barks, the caravan moves on

The app owner decides it’s time to add dogs to the app, asks the company for an estimate, and gets about at least six months to add dogs to the app. In fact, the app will be written from scratch again. During this time, Moogle will add snakes, spiders, and guinea pigs to the app, and Fur&Pur will only get dogs.
Why did this happen? The lack of a flexible application architecture is to blame, one of the most common factors being the Singleton design anti-pattern.

What’s wrong?

In order to order a cat to your home, the consumer needs to create an application and send it to the office, where the office will process it and send a courier with the cat, the courier will then receive payment for the service.
One of the programmers decides to create a class “CatApplication” with the necessary fields, and puts this class in the global application space via a singleton. Why does he do this? To save time (a penny saving of half an hour), because it is easier to put the application in general access than to think through the application architecture and use dependency injection. Then the other developers pick up this global object and bind their classes to it. For example, all the screens themselves access the global object “CatApplication” and show the application data. As a result, such a monolithic application is tested and released.
Everything seems fine, but suddenly a customer appears with a requirement to add applications for dogs to the application. The team frantically begins to estimate how many components in the system will be affected by this change. Upon completion of the analysis, it turns out that 60 to 90% of the code needs to be redone to teach the application to accept in the global singleton object not only “ApplicationForCat” but also “ApplicationForDog”. It is useless to estimate the addition of other animals at this stage, at least two can be handled.

How to avoid singleton

First, at the requirements gathering stage, clearly indicate the need to create a flexible, extensible architecture. Second, it is worth conducting an independent examination of the product code on the side, with a mandatory study of weak points. If you are a developer and you like singletons, then I suggest you come to your senses before it is too late, otherwise sleepless nights and burnt nerves are guaranteed. If you are working with a legacy project that has a lot of singletons, then try to get rid of them as quickly as possible, or from the project.
You need to switch from the anti-pattern of singletons-global objects/variables to dependency injection – the simplest design pattern in which all the necessary data is assigned to the class instance at the initialization stage, without any further need to be tied to the global space.

Sources

https://stackoverflow. com/questions/137975/what-is-so-bad-about-singletons
http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/
https://blog.ndepend.com/singleton-pattern-costs/

Grinding gears

Oh muse, how difficult it is to catch you sometimes.
The development of Death-Mask and related frameworks (Flame Steel Core, Game Toolkit, etc.) is suspended for several months in order to decide on the artistic part of the game, the musical and sound accompaniment, and to think through the gameplay.
The plans include creating an editor for the Flame Steel Game Toolkit, writing an interpreter for game scripts (based on the Rise syntax), and implementing the Death-Mask game for as many platforms as possible.
The most difficult stage has been passed – the possibility of writing your own cross-platform game engine, your own IDE, and a set of libraries has been proven in practice.
I’m moving on to the stage of creating a truly thoughtful, interesting project, stay tuned.

We beat Malevich, black squares Opengl

Malevich periodically comes to any developer on OpenGL. This happens unexpectedly and boldly, you just start the project and see a black square instead of a wonderful render:

Today I will describe for what reason I was visited by a black square, the problems found because of which Opengl does not draw anything on the screen, and sometimes even makes the window transparent.

Use tools

For debugging Opengl, two tools helped me: renderdoc and and apitrace . Renderdoc – tool for debugging the OpenGL rendering process, you can view everything – Vertexes, shaders, textures, debt messages from the driver. Apitrace – A tool for tracing challenges of a graphic API, makes a dump calls and shows arguments. There is also a great opportunity to compare two dumps via WDIFF (or without, but not so convenient)

Check with whom you work

I have an operating system Ubuntu 16.10 with old dependencies SDL2, GLM, Assimp, Glew. In the latest version of Ubuntu 18.04, I get the assembly of the game Death-Mask which does not show anything on the screen (only a black square). When using Chroot and assembly at 16.10 I I get a working assembly of the game with graphics .

It seems something broke in Ubuntu 18.04

LDD showed the linkka to identical libraries SDL2, GL. Driving a non -working build in Renderdoc, I saw garbage at the entrance to the vertex shader, but I needed a more solid confirmation. In order to understand the difference between the binarics, I drove them both through apitrace . Comparison of dumps showed me that the assembly on a fresh Ubunta breaks the program of the prospects in OpenGL, actually sending garbage there:

Matrices gather in the GLM library. After copying GLM from 16.04 – I got the working build of the game again. The problem was the difference in the initialization of a single matrix in GLM 9.9.0, it is necessary to clearly indicate the MAT4 (1.0F) argument in it in the constructor. Having changed the initialization and by writing off the author of the library, I began to do tests for fsgl . In the process of writing which I found flaws in FSGL, I will describe them further.

Determine who is in life

For the correct work with OpenGL, you need to voluntarily forcibly request the context of a certain version. So it looks for SDL2 (you need to put the version strictly before initializing the context):


 sdl_gl_seettrtribute (sdl_gl_context_major_version,  3 );
SDL_GL_SETTRIBUTE (SDL_GL_CONTEXT_MINOR_VERSION, 2 );
SDL_GL_SETTRIBUTE (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

For example, Renderdoc does not work with contexts below 3.2. I would like to note that after switching the context there is a high probability of seeing the same black screen . Why?

Because the context of Opengl 3.2 must require the presence of VAO buffer , without which 99% of graphic drivers do not work. Add it easy:


 Glgenvertexarrays ( 1 ,  &  vao);
GLBINDVERTEXARAY (VAO);

Do not sleep, freeze

I also met an interesting problem on Kubuntu, instead of a black square I was displayed transparent, and sometimes everything was rendered correctly. I found the solution to this problem at Stack Overflow:
https://stackoverflow.com/questions/38411515/sdl2-opengl-window-appears-semi-transparent-sometimes

The FSGL test render code was also present Sleep (2S) ; So on the Xubuntu and Ubuntu I received the correct render and sent the application to sleep, but on Kubuntu I received a transparent screen in 80% of the launch of Dolphin and 30% of launches and terminal. To solve this problem, I added rendering in each frame, after a SDlevent survey, as recommended in the documentation.

Test code:
https://gitlab.com/demensdeum/FSGLtests/blob/master/renderModelTest/

Talk to the driver

Opengl supports the communication channel between the application and the driver, to activate it, you need to turn on the flags Gl_debug_outPut, GL_DEBUG_OUTPUT_SYNCHRONUS, affix the warning GLDEBUGMESSAGECONTROL and tie the calback through GLDEBUGMESSAGECALLBACK .

An example of initialization can be taken here:
https://github.com/rock-core/gui-vizkit3d/blob/master/src/EnableGLDebugOperation.cpp

Don’t be afraid, look how it grows

In this note, I will tell you about my misadventures with smart pointers shared_ptr. After implementing the generation of the next level in my game Death-Mask, I noticed a memory leak. Each new level gave an increase of + 1 megabyte to the consumed RAM. Obviously some objects remained in memory and did not release it. To correct this fact, it was necessary to implement the correct implementation of resources when overloading the level, which apparently was not done. Since I used smart pointers, there were several options for solving this problem, the first was to manually review the code (long and boring), the second involved investigating the capabilities of the lldb debugger, the source code of libstdc++ for the possibility of automatically tracking changes to the counter.

On the Internet, all the advice boiled down to manually reviewing the code, fixing it, and beating yourself with whips after finding the problematic line of code. It was also suggested to implement your own system for working with memory, as all large projects developed since the 90s and 00s have done, before smart pointers came to the C++11 standard. I attempted to use breakpoints on the constructor of a copy of all shared_ptr, but after several days nothing useful came of it. There was an idea to add logging to the libstdc++ library, but the labor costs (o)turned out to be monstrous.


Cowboy Bebop (1998)

The solution came to me suddenly in the form of tracking changes to the private variable shared_ptr – use_count. This can be done using watchpoints built into lldb. After creating a shared_ptr via make_shared, changes to the counter in lldb can be tracked using the line:

watch set var camera._M_refcount._M_pi->_M_use_count

Where “camera” is a shared_ptr object whose counter state needs to be tracked. Of course, the insides of shared_ptr will differ depending on the version of libstdc++, but the general principle is clear. After setting the watchpoint, we launch applications and read the stack trace of each counter change, then we look through the code (sic!), find the problem and fix it. In my case, objects were not released from cache tables and game logic tables. I hope this method will help you deal with leaks when working with shared_ptr, and love this memory management tool even more. Happy debugging.

Games Vision #3

The third issue of the non-permanent column about games Games Vision.

Observer (PC and consoles, Bloober Team) – cyberpunk horror from the valiant Poles. A short and very atmospheric horror starring Rutger Hauer. As a cyberpunk fan, I liked absolutely everything about the game. Not very difficult puzzles, charming glitches of the main character, gameplay with calm moments mixed with action, the ability to literally dig into the memories of the dead, a plot in the style of Ghost in the Shell + many references to Sci-Fi pop culture. Of the minuses – too much glitches, sometimes it seems that because of their abundance it is impossible to play, also some players were annoyed by specific horror elements, frightening so much that they could not continue playing.
Rating: 8/10

Paradigm (Windows/OS X, Jacob Janerka) – a quest that manages to parody and laugh at everything at once. It makes fun of the USSR, America, the quest genre, glam rock, old consoles, people, monuments, IT specialists, cones, computers, women, children, parents, artists, love, scientists, the gaming industry, the players themselves – in general, you can’t list everything. An absolutely unpredictable plot, absurd atmosphere and art, not particularly difficult puzzles. The game has rare bugs and crashes, some moments and jokes are slightly predictable and not original.
Rating: 9/10

Late Shift (PC and consoles, CtrlMovie Ltd) – interactive movie. I really regret that a basically good idea received such a bad implementation. Everything is bad – the plot, the lack of star actors, the acting, constant freezes in the PC version, almost zero variability (illusory). It is completely incomprehensible how it was possible to release a game with so many problems in the 2010s, because in fact it is an ordinary video player, the whole game could have been posted on the Internet, for example, on YouTube, but instead they used Unity and managed to break even such a powerful game engine. The official forum on Steam is dedicated to fixes, hotfixes, workarounds, etc. There is a technical disaster, no user support, all testing takes place directly on the players. Bought rave reviews and testimonials.
Rating: 3/10

Saber-Plus C++ IDE

I started developing my own IDE for C++ – Saber-Plus. The main ideas of the new IDE are to be simple, fast and *helpful* in development. At the moment, the source code is available under the MIT license on GitHub, Qt is used to work with the UI. In the future, I plan to transfer all development related to C++ to Saber-Plus – the Death-Mask game will definitely be migrated. More details on the points:

  • Simple – it is planned not to add more than necessary – for example, not to contain source control clients, built-in terminal and similar things. The functionality is focused only on editing the code, analyzing errors. The editor code should be divided into simple classes that correctly perform their part of the work (Unix-way)
  • Fast – refers to both the IDE code base and the editor behavior itself. All actions in the IDE should be as fast as possible, even such often long and complex ones as creating/importing projects.
  • Assistant – analysis of typical errors when writing, compiling code. Correction of errors, warnings at the user’s request. The idea is to add analysis of the application assembly on a specific platform and output of reference information on the installation of the necessary libraries, components.

To build the editor for your operating system, you need to install Qt 5 SDK, download the IDE code from the repository, open the Saber-Plus.pro file in Qt Creator and run the build:

https://github.com/demensdeum/saberplus

Flame Steel Battle Axe

From today I start developing an editor for the game framework – Flame Steel Battle Axe.

The editor allows you to edit scenes for the Flame Steel Game Toolkit game framework.
I chose the relatively young Java-based Kotlin language to try it out in combat conditions.

You can follow the progress in the repository:
https://github.com/demensdeum/FlameSteelBattleAxe

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

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

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.