November 2009

Warning! Some information on this page is older than 5 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

# Redirecting Standard I/O to Windows Console

20:10
Sat
28
Nov 2009

Every process, no matter if under Windows or Linux, has standard text streams called input, output and error. Of course it makes most sense when you deal with command line applications, where you can directly interact with it using these streams. If you use Linux, you are probably familiar with redirecting streams to file using > operator or to another application using | operator. We use these streams in C++ code with standard C library (like printf and scanf functions) or standard C++ library (like std::cout and std::cin streams). But what if we write a GUI application in Windows (like a game), which has WinMain instead of main entry point and thus doesn't have console?

There is a simple WinAPI function called AllocConsole, which opens this black system console for your Win32 application. But today I've noticed that the console opened this way doesn't handle standard I/O! I've tried to do std::cout << "Hello World" and nothing happened. So after some googling I've found a hacky solution (or maybe rather a smart code snippet? :) in an article hosted at Andrew Tucker's Home Page, published in 1997 in Windows Developer Journal: Adding Console I/O to a Win32 GUI App. Here is my version of this code with all necessary includes:

#include <windows.h>
#include <ios>
#include <cstdio>
#include <io.h>
#include <fcntl.h>

void RedirectStandardIo()
{
  /* This clever code have been found at:
  Adding Console I/O to a Win32 GUI App
  Windows Developer Journal, December 1997
  http://dslweb.nwnexus.com/~ast/dload/guicon.htm
  Andrew Tucker's Home Page */

  // redirect unbuffered STDOUT to the console
  long lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
  int hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  FILE *fp = _fdopen(hConHandle, "w");
  *stdout = *fp;
  setvbuf(stdout, NULL, _IONBF, 0);

  // redirect unbuffered STDIN to the console
  lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
  hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  fp = _fdopen( hConHandle, "r" );
  *stdin = *fp;
  setvbuf(stdin, NULL, _IONBF, 0);

  // redirect unbuffered STDERR to the console
  lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
  hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  fp = _fdopen( hConHandle, "w" );
  *stderr = *fp;
  setvbuf(stderr, NULL, _IONBF, 0);

  // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog point to console as well
  std::ios::sync_with_stdio();
}

Comments | #winapi Share

# The Concept of Immutability and Descriptor

21:35
Fri
27
Nov 2009

An object of some class represents a piece of data, chunk of memory or other resource along with methods to operate on it. It should also automatically free these resources in destructor. But how should modifying these data look like? There are two possible approaches. As an example, let's consider a fictional class to encapsulate Direct3D 9 Vertex Declaration (I'll show my real one in some future blog entry). A Vertex Declaration is an array of D3DVERTEXELEMENT9 structures, which can be used to create IDirect3DVertexDeclaration9 object. First solution is to define class interface in a way that data inside can be modified at any time.

class MyMutableVertexDecl
{
public:
  // Creates an empty declaration.
  MyMutableVertexDecl();
  // Frees all allocated resources.
  ~MyMutableVertexDecl();
  
  // Copies data from another object
  void CopyFrom(const MyMutableVertexDecl &src);
  // Deletes all internal data so object becomes empty again.
  void Clear();
  bool IsEmpty() const;
  
  // I/O (Serialization)
  void SaveToStream(IStream &s) const;
  void LoadFromStream(IStream &s);
  
  // Reading of underlying data
  size_t GetElemCount() const;
  const D3DVERTEXELEMENT9 & GetElem(size_t index) const;
  
  // Modification of underlying array
  void SetElem(const D3DVERTEXELEMENT9 &elem, size_t index);
  void AddElem(const D3DVERTEXELEMENT9 &elem);
  void InsertElem(const D3DVERTEXELEMENT9 &elem, size_t index);
  void RemoveElem(size_t index);
  
  IDirect3DVertexDeclaration9 * GetD3dDecl() const;
  
private:
  std::vector<D3DVERTEXELEMENT9> m_Elems;
  IDirect3DVertexDeclaration9 *m_D3dDecl;
  ...
};

This approach seems very nice as you can create your object any time you wish and fill it with data later, as well as change this data whenever you need to. But at the same time, a question emerges: when to (re)create "destination" IDirect3DVertexDeclaration9 from the "source" D3DVERTEXELEMENT9 array? Each time the array is modified? Or maybe each time the IDirect3DVertexDeclaration9 is retrieved? Optimal solution for the interface above would be to do lazy evaluation, that is to recreate IDirect3DVertexDeclaration9 whenever it is retrieved for the first time since last time the D3DVERTEXELEMENT9 array have been modified. But...

Read full entry > | Comments | #software engineering #directx #.net #physics #c++ Share

# FileChangeMonitor

21:34
Tue
24
Nov 2009

Today I'd like to show a piece of my code with an interesting solution. The problem is: Most of us have to restart our applications to see changes made in textures, shaders and other data files. It may not be a problem at the beginning, but as the application and the amount of resources grow, loading the whole thing takes longer and longer. Wouldn't be great if we could change or replace asset files and immediately see the results without restarting the game? This idea seems fascinating especially after watching some of the videos about CryEngine 3 editor :)

So here is my solution: FileChangeMonitor.cpp, FileChangeMonitor.hpp. It's not a ready-to-use code snippet, but rather something you can base on when writing your own code. I've created a FileChangeMonitor class and a global variable to give access to its single instance to everyone. The purpose of this class is monitoring some files for change in their "last modified" date. Here is the way to use it:

Of course I didn't want to block entire application for the time of retrieving file date, so I do it on separate thread. That thread has a loop (with some delay of course), checks modification time of registered files and posts a small structure to a queue after noticing file change. ProcessEvents method called in main thread only processes this queue and dispatches received events to registered listeners.

I'm aware this code is not perfect. The more files are registered, the less frequent each file is checked for modification. I could also use some lockless data structure as a queue instead of std::vector protected by mutex. I could even use totally different solution, like monitoring changes in a directory provided by Windows API (look for ReadDirectoryChangesW function in MSDN). But this solution works OK for me, the implementation can be changed without changing its very simple interface and my point here is just to tell you that it's very convenient when you can change a texture, shader code or any other asset and it is automatically reloaded in a second, without restarting your application.

Comments | #engine Share

# Adventures with Windows XP and Windows 7

18:07
Sun
22
Nov 2009

So I'm back after hardware upgrade and system reinstallation. What I want to write about today is my recent adventures with installing Windows. I've decided to install Windows 7 64-bit (as I believe it's already good and very promising platform which will soon become a standard) and Windows XP 32-bit (in case something I need wouldn't work in Win7, like the connection with my Mio palmtop).

I've installed Windows 7 first. While inside the installer, I've created an NTFS partition for that system, called "Win_7". Win7 created one additional 100 MB NTFS partition at the very beginning of my disk, named it "System Reserved" and didn't mount it as any drive letter. Oh well, maybe it's just needed for something...

Then I wanted to install old good Windows XP. Unfortunately WinXP SP2 setup doesn't recognize my SATA disk. I didn't want to switch it from native SATA (AHCI) to IDE emulation mode in BIOS as it degrades performance AFAIK. My motherboard manual and many other sources give a solution as a driver which has to be recorded on a... floppy disk and given to WinXP setup. And I don't even have a floppy disk drive!

Fortunately I've googled another solution. This article shows how to prepare your own "distribution" of Windows XP install CD with selected drivers and updates already integrated inside. All I had to do was to copy original install CD to my hard disk, download and unpack SATA/RAID drivers for my motherboard, install freeware nLite program and use it to burn new CD. It works perfectly! Now I have WinXP install CD which recognizes my SATA disk.

While installing XP, I've created another (third) NTFS partition. I named that partition "Win_XP" and set up WinXP on it. Everything went fine and the only strange thing was different naming of partitions in both systems (you can't change drive letter of the system partition).

But then I was unable to start my Win7 as WinXP installation overwritten MBR with its own, old bootloader without detecting Win7 and adding it to the boot menu. It's interesting that WinXP, although installed on the "Win_XP" partition (E:), placed its Boot.ini file on the "System Reserved" partition.

I tried to modify boot.ini to add Win7 to the menu, but nothing seemed to work. The WinXP boot manager simply isn't able to start Windows 7 and that's exactly what I've found when searching Google. Win7 has its own, new boot menu which has to be used to be able to boot this system.

To restore MBR of Windows 7:

Now, how to add WinXP entry to the Win7 boot menu? The new boot manager of Windows 7 is not such simple text file as boot.ini was, but it's a database stored in this invisible "System Reserved" partition. User can edit the menu using bcdedit command line tool (you must run Command Prompt as Administrator to use it), but there is another solution: a freeware application called EasyBCD. Not only it simplifies this task by providing GUI, but it's also able to switch MBR between XP and Vista/7 version and it also works in Windows XP! It seemed like I was almost there...

But unfortunately the Win7 boot menu sees partitions just like Win7 does, so the first partition - the one where WinXP placed its boot.ini file - was invisible to it. My solution (© Reg ;) was to run WinXP (by switching MBR to XP version), to copy files needed for booting - boot.ini, ntdetect.com, ntldr - from "System Reserved" to "Win_XP" partition and point WinXP entry in the 7 boot menu to the "Win_XP" partition (E:). Finally I could switch back to Win7 MBR with my boot menu working for both systems.

Comments | #windows Share

# Fractals, IFS and a Fern

21:16
Sat
14
Nov 2009

Today I've started playing with fractals. Doing such experiments is now easy as I have in my home framework a whole bunch of useful functions like exposing structure fields into a property window or executing computational/IO tasks on the separate thread in the background. My first effect is Barnsley's fern, coded according to the algorithm from Wikipedia.

Comments | #rendering #fractals Share

# Executable File Path

17:18
Sat
14
Nov 2009

There have been a question recently at our forum about how to get the full path of the current executable file.

First idea proposed was to use argv[0] argument from main function, but this solution is wrong. The proof is a simple example with my program called Parametrizer. As this screenshot shows, program run from the command line with current directory equal to the directory where the executable file lies results in the argv[0] being set to only file name, without the full path.

The correct solution for Windows is to use GetModuleFileName function, just like this:

char exePath[MAX_PATH];
GetModuleFileName(NULL, exePath, _countof(exePath));

Then you can extract only the directory path and append any other file name to be sure you always access files installed with your application from the correct directory refered by the full, absolute path. I'll write more about function for path string processing and the concept of current directory soon...

Comments | #c++ #winapi Share

# Properties of Pascal Triangle

19:10
Thu
12
Nov 2009

Pascal Triangle is a mathematical object that looks like triangle with numbers arranged the way like bricks in the wall. Each next row has one more number, ones on both sides and every inner number is the sum of two numbers above it. It can span infinitely.

Despite simple algorithm this triangle has some interesting properties. First, if you draw only odd numbers, you get a fractal - Sierpinski Triangle.

Second, graph of numbers in each row resembles Gaussian distribution function. The lower row you take from the triangle (containing more numbers), the more precise graph you get.

I've made these images with Octave - a free Matlab alternative. I like it and I think concepts behind this Matlab programming language can be quite useful for doing computations, but doing graphics is painfully slow. Whole seconds to draw several dozens of texts or rectangles? WTF?!

Comments | #fractals #math #tools Share

# Game Programming FFFFFUUUU

00:18
Wed
11
Nov 2009

There is this "FFFFFUUUU" meme spreading in the Internet from 4chan, just like earlier "lolcats" or "pedobear". It's often more stupid than funny, but why don't we try to make our own, game development "FFFFFUUUU" drawings? Here are my ideas:

Comments | #humor Share

# Unreal Engine for Free

11:21
Sun
08
Nov 2009

This week the news of the week was the release of the famous, probably world's best game engine free to download and uncommercial use. I'm talking about Unreal Engine in form of UDK - Unreal Development Kit.

At first glance it looks like a small revolution, but when you download (562 MB) and install (1.25 GB) the package, you will see it's actually not an SDK at all. There is no source code or even headers and libraries to code your own game in C++ using this engine. It's just the game editor and the only thing you can do besides graphics and level design is scripting gameplay mechanics in UnrealScript. Just like Game Maker, only more advanced ;)

Nevertheless I think it's important news and the editor is worth seeing. All in all Unreal Engine is a great technology used by countless commercial game developers. I've started reading UnrealScript Reference and I'm amazed by concepts of this language like object states, latent code or replication. Now I feel like making a game with the Unreal Engine, but as I'm neither good artist nor good level designer, soon I will probably go back to my own C++ code, just knowing how a good game engine should look like.

Comments | #engine #tools Share

STAT NO AD
[Stat] [STAT NO AD] [Download] [Dropbox] [pub] [Mirror]
Copyright © 2004-2017