Prevent Direct Execution of EXE

Back in early 2000s was the time when MMOs were very very very poppular in Asian countries. That was also the time when I was crazy about Ragnarok Online, one of the most famous korean MMORPGs of all time. Besides playing the game (which cost around US$10 per month, a large sum for a middle school student like me), I also went into modding the game and ran it on an emulator (private server running locally).

One thing that I noticed was the existence of a mysterious EXE file in its installation directory called “Ragexe.exe” which can never be executed; it will show you an error message whenever you double click on it.

Years later when I started to learn C/C++ programming I finally understood what the hell was that EXE file for; in-fact, it’s the actual game executable and not the other EXE that has the game icon on it, the other EXE is actually the updater client, nothing else.

So finally, the mystery has been solved. However, the question is: How can we re-create this for our own programs/games? What if we also want our users to run the updater first and not directly execute the main program? It turns out, it’s pretty easy to achieve. In the following example I will be using C/C++ and Qt but it should be pretty similar in other programming languages and platforms as well.

The sample code here is pretty simple:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);

	if (argc <= 1)
	{
		QMessageBox::critical(0, "Application Error", "Please run MyGame.exe instead.");
		return 0;
	}
	else
	{
		if (argv[1] != "yourpassword")
		{
			QMessageBox::critical(0, "Application Error", "Please run MyGame.exe instead.");
			return 0;
		}
	}

	MainWindow w;
	w.show();

	return a.exec();
}

In the example above, your EXE will simply pop out an error message that says “Please run MyGame.exe instead.” if you double click on it directly. This is because the argc variable is either 0 or 1 (depending on platform, which means no additional input argument during launch) if you run it directly.

However, if there is one or more arguments being dumped to the program during launch, check (within the argv array) whether the second argument (the first argument is usually the program’s name) matches your secret phrase or password before allowing the program to launch. Usually there will be input arguments if the user drag one or more files to the EXE to make it launch, as this is very useful for programs like text editors or image editors. That’s why we must check if the argument matches your password or not.

Now that your program can no longer be run directly, what about the updater? How to ask the updater to execute your main program with an input argument? It’s actually pretty easy as well. In the following example I will be using C/C++ and Qt, but it should be similar across different programming languages and platforms:

QProcess *process = new QProcess(this);
process->setNativeArguments("yourpassword");
process->startDetached("MyGame.exe");
delete process;

exit(EXIT_SUCCESS);

In the code above, I simply declared a QProcess object and set the native argument before starting the main program and close the updater client.

That’s all, it’s very simple to achieve. The tutorial above is by no mean professional: Technical names and phrases are not necessarily accurate, and the method used is not necessarily the standard way. I’m just trying to share what I know and what I did with my own projects. Peace.

Old Project – 3D Level Editor (2010)

Today I stumbled upon some old screenshots in my backup folder and I thought maybe I should post it here to remind myself how passionate I was.

This is a 3D level editor I did for my hobby game project back in 2010. The level editor was made using Qt 4 and Irrlicht engine. Some of the screenshots below are showing the editor which uses Irrlicht’s native GUI. Irrlicht’s GUI system was quite limited in term of types of widgets and functionality, which later on led me to switching all the GUI over to Qt.

Some of the features supported by the “game engine” I did back then include:
– Basic fixed function 3D rendering
– Basic collision (box collider and trigger)
– Spawn points
– Player camera and animated camera (for in-game cinematic)
– 3D sound (using irrKlang)
– Simple path finding

I made a simple game demo using the game engine and level editor I made. Unfortunately, the game wasn’t finished and I moved on doing something else. Below is the video recording I did back in 2010 showing how the game demo look like, for a competition. Spore Motions was the name of our team back then.

Hopefully I will be back into game development very soon.

SDL2 with OpenGL

Ever since SDL developer joined Valve and revamped most of its source code, SDL 2 has been seen by many as the game changer that will reshape the linux (and Mac OSX) gaming scene by allowing developers to easily port their games to these platforms.

Although there are some other APIs that are equally portable, but none of them are supported by big company with strong financial muscle and development experience like Valve. The major advantage of SDL being used by a company that has had countless experience developing AAA titles is that they can help avoiding ideas that sound good only on paper but not working quite well when applied to real world problems. This is why I think SDL 2 is a library worth studying for long term benefit.

In this tutorial, I’m going to directly use the OpenGL for rendering, instead of using SDL’s own renderer, because OpenGL works better in term of performance and flexibility. You can develop both 2D/3D games with OpenGL but only 2D if you use SDL renderer.

So let’s get it started by opening your favorite C/C++ IDE, which in my case, the Code::Blocks. You have to link your project to several libraries such as OpenGL, GLEW and SDL2. GLEW is basically a library that makes your life easier for connecting to OpenGL extensions. Different IDE has different approach in linking to external libraries, so I will not be explaining it here. Check out other tutorials that are related to your choice of IDE.

Let’s start writing some code. First of all, you need to link all the relevant header files to your main source file, using the #include macro. Notice we used #define GLEW_STATIC before #include <GL/glew.h> in-order to build GLEW statically into your project. Without the macro, you need to provide the dynamic library file for the compiler.

// OpenGL headers
#define GLEW_STATIC
#include &lt;GL/glew.h&gt;
#include &lt;GL/glu.h&gt;
#include &lt;GL/gl.h&gt;

// SDL headers
#include 
#include 
#include 

Next, define all the necessary variables, in this case, a boolean which determines whether the game is still running or not, as well as other pointers/references that are linked to the SDL window, OpenGL context, and SDL event.

bool quit;

SDL_Window* window;
SDL_GLContext glContext;
SDL_Event sdlEvent;

After that, let’s move on to the main() function. Here we define the quit variable as false, so that later on we can use it for the game loop and keep the game running without closing. We also set the OpenGL’s context to 3.1 core profile. Do notice that in version 3.1 above, the fixed-function pipeline is completely deprecated, so you need to be careful when picking the right context for your OpenGL renderer.

int main(int argc, char *argv[])
{
    quit = false;

    //Use OpenGL 3.1 core
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
}

Next, we call SDL_Init(SDL_INIT_VIDEO) to initiate SDL. If the result returned by the function is -1, it means something is going wrong and you should stop immediately. Otherwise, you are good to go and start creating the rendering window using SDL_CreateWindow(). There are several inputs for this functions, such as:

1. Title
2. Horizontal position
3. Vertical position
4. Width
5. Height
6. Flags

We need to specifically set the type of window as OpenGL rendering window using the SDL_WINDOW_OPENGL flag. Otherwise, SDL will not be able to use OpenGL to do the rendering.

After we have created a window, use it to create the OpenGL context by calling SDL_GL_CreateContext(window). Call glewInit() to automatically load all the relevant extensions based on the OpenGL context you have just set.

// Initialize video subsystem
if(SDL_Init(SDL_INIT_VIDEO) &lt; 0)
{
    // Display error message
    printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
    return false;
}
else
{
    // Create window
    window = SDL_CreateWindow("Hello World!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN );
    if( window == NULL )
    {
        // Display error message
        printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
        return false;
    }
    else
    {
        // Create OpenGL context
        glContext = SDL_GL_CreateContext(window);

        if( glContext == NULL )
        {
            // Display error message
            printf( "OpenGL context could not be created! SDL Error: %s\n", SDL_GetError() );
            return false;
        }
        else
        {
            // Initialize glew
            glewInit();
        }
    }
}

You have now created an empty window that doesn’t render anything and will be closed once it’s being launched. This happen because we have not yet created the game loop for it. A game loop is basically a while loop that keeps on running repeatedly until the user closes the application. In gaming term, each loop is called a “frame” or a “tick”. Graphics will be rendered and displayed on the screen for several times a second, hence the term for measuring the rate of rendering is called “frame-per-second”.

To create the game loop, we will be using the quit variable that we have defined previously. If the variable quit is true, the window will never be closed and keep the rendering going. Within the game loop, we detect the keyboard event and check if player has pressed the Escape button. If the Escape button is pressed, set quit as true and the application will then be closed.

We also set the background color as cornflower blue, and then ask OpenGL to start rendering the scene by swapping the render buffer. We don’t have anything to be rendered for now so you will just see a blue color background.

// Game loop
while (!quit)
{
    while(SDL_PollEvent(&amp;sdlEvent) != 0)
    {
        // Esc button is pressed
        if(sdlEvent.type == SDL_QUIT)
        {
            quit = true;
        }
    }

    // Set background color as cornflower blue
    glClearColor(0.39f, 0.58f, 0.93f, 1.f);
    // Clear color buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    // Update window with OpenGL rendering
    SDL_GL_SwapWindow(window);
}

Lastly, we need to clean everything up if the variable quit is set to true and breaks the game loop. It’s important to quit the application neatly! Destroy the rendering window properly by calling SDL_DestroyWindow(window), then clear the window pointer from the memory by setting the pointer to NULL, and lastly call SDL_Quit() to make sure SDL quits properly.

//Destroy window
SDL_DestroyWindow(window);
window = NULL;

//Quit SDL subsystems
SDL_Quit();

return 0;

For those who are lazy, this is the full source code:

// OpenGL headers
#define GLEW_STATIC
#include &lt;GL/glew.h&gt;
#include &lt;GL/glu.h&gt;
#include &lt;GL/gl.h&gt;

// SDL headers
#include 
#include 
#include 

bool quit;

SDL_Window* window;
SDL_GLContext glContext;
SDL_Event sdlEvent;

int main(int argc, char *argv[])
{
    quit = false;

    //Use OpenGL 3.1 core
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

    // Initialize video subsystem
    if(SDL_Init(SDL_INIT_VIDEO) &lt; 0)
    {
        // Display error message
        printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
        return false;
    }
    else
    {
        // Create window
        window = SDL_CreateWindow("Hello World!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN );
        if( window == NULL )
        {
            // Display error message
            printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
            return false;
        }
        else
        {
            // Create OpenGL context
            glContext = SDL_GL_CreateContext(window);

            if( glContext == NULL )
            {
                // Display error message
                printf( "OpenGL context could not be created! SDL Error: %s\n", SDL_GetError() );
                return false;
            }
            else
            {
                // Initialize glew
                glewInit();
            }
        }
    }

    // Game loop
    while (!quit)
    {
        while(SDL_PollEvent(&amp;sdlEvent) != 0)
        {
            // Esc button is pressed
            if(sdlEvent.type == SDL_QUIT)
            {
                quit = true;
            }
        }

        // Set background color as cornflower blue
        glClearColor(0.39f, 0.58f, 0.93f, 1.f);
        // Clear color buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        // Update window with OpenGL rendering
        SDL_GL_SwapWindow(window);
    }

    //Destroy window
    SDL_DestroyWindow(window);
    window = NULL;

    //Quit SDL subsystems
    SDL_Quit();

    return 0;
}

OGRE Hello World!

In this tutorial, I will teach you how to create an empty window with OGRE graphics engine and C/C++ language. Unlike any other tutorials that you can find on the internet, this tutorial does not rely on ExampleApplication.h and therefore you will be able to learn OGRE completely from scratch.

At the end of this tutorial, you will be able to create an empty window similar to this:

It’s actually not that complicated to code from scratch, just take a look at the full source code below and you will realize that it’s actually pretty simple to understand even for beginners.

#include <Ogre.h>
using namespace Ogre;

int main()
{
    Root *root = new Root("plugins.cfg", "mygame.cfg", "mygame.log");
    root->showConfigDialog();

    root->initialise(true, "My Game");
    RenderWindow *window = root->getAutoCreatedWindow();

    SceneManager *smgr = root->createSceneManager(ST_GENERIC, "SceneManager");

    Camera *cam = smgr->createCamera("MainCamera");

    Viewport *vp = window->addViewport(cam);
    vp->setBackgroundColour(ColourValue(0.3, 0.6, 0.9));

    root->startRendering();

    return 0;
}

Pretty simple isn’t it? I will now explain what the code does part-by-part. First of all, you have to include OGRE’s main header file “Ogre.h” into your project so that you can access its classes and functions for later use:

#include <Ogre.h>
using namespace Ogre;

You can also predefine its namespaces (but not a must) to make your code shorter. For example, instead of calling Ogre::Root *root = new Ogre::Root(), we can use Root *root = new Root() instead, which is much shorter and clean.

After that, create a Root class at the beginning of your main function, like so:

Root *root = new Root("plugins.cfg", "mygame.cfg", "mygame.log");

As you can see, Root requires 3 parameters during initialization: the first one being the config file that defines what plugins to load before starting the program; the second parameter is your game’s rendering config file that defines the resolution, aspect ratio, color depth, and so on which will also be loaded before your game is launched; and the last parameter is the name of the log file that will be generated whenever an error happens and it will tell you what problem had occurred.

After that we will be calling:

root->showConfigDialog();

which displays a config dialog before launching your game. The dialog window looks like this:

It lets the players change display settings before the game starts, which is quite handy especially for debugging purposes during development stages.

Next, we will initialize the Root class and define the window title by doing so:

root->initialise(true, "My Game");
RenderWindow *window = root->getAutoCreatedWindow();

We will then call root->getAutoCreatedWindow() to return the newly created render window and stores it to the a pointer called window. Please note that Ogre uses UK English, therefore you should use initialise instead of initialize.

Next, we will create a scene manager that manages your game’s scene graph (i.e. all the 3D objects in your scene) and save it to a pointer called smgr:

SceneManager *smgr = root->createSceneManager(ST_GENERIC, "SceneManager");

There are two parameters for creating a scene manager. The first parameter defines the type of scene graph you’re about to create. There are multiple types of scene managers you can choose from, such as:

  1. ST_GENERIC – Generic scene manager
  2. ST_EXTERIOR_CLOSE – Old terrain scene manager
  3. ST_EXTERIOR_FAR – Nature scene manager
  4. ST_EXTERIOR_REAL_FAR – Paging scene manager
  5. ST_INTERIOR – BSP scene manager

which each of them serves a very different and specific purpose. In this example, we use ST_GENERIC which is the generic type that works well in most cases. The second parameter simply lets you set a name for your scene manager, in this case, we called it “SceneManager”.

Next, we have the code below:

Camera *cam = smgr->createCamera("MainCamera");

Viewport *vp = window->addViewport(cam);
vp->setBackgroundColour(ColourValue(0.3, 0.6, 0.9));

which simply does the following, in ascending order:

  1. Create a camera and call it “MainCamera”.
  2. Ask the rendering window to link the newly created camera to its viewport.
  3. Set a background color for the viewport which will be used to flush the back buffer.

After everything has been setup correctly, we will now render the scene by calling startRendering() which is quite self-explanatory:

root->startRendering();

and viola! You have now successfully created an empty rendering window that runs on OGRE. That’s all for this tutorial, have fun!