Reg__ @ Twitter Twitter Updates

reg__ Delicious Bookmarks

Waiting for

IGK-9'2012 Conference - remaining: 36 days

Facebook

Recommended Productions

FX Batch Compiler 1.1

This Windows application supports compilation of FX effect files and HLSL shader files using fxc command line compiler included in DirectX SDK. You can compile many files at time or one file with different settings.

Features:

  • Write compilation scripts in a simple language by specifying parameters for fxc.exe.
  • Compile multiple shaders at time.
  • Compile only shaders that need rebuild checked by file modification time.
  • Review success or failure, warning and error count and compiler output for every task.
  • Compile single HLSL source file with different parameters and preprocessor macros.

Date: 2011-02-09

Download:
FxBatchCompiler_1-1.exe
FxBatchCompiler-1.1-bin.zip
FxBatchCompiler-1.1-src.zip

Block Wizard

My first Flash game. Coded with FlashDevelop in ActionScript 3.

Date: 2010-04-06

CommonLib 9.0

Universal library for C++, created especially with game programmers in mind. Includes: math module (vectors, matrices, quaternions, planes, rich set of collision functions and more), string operations, conversions, smart pointers, configuration files handling, date and time module, exception class hierarchy for error handling, file system handling, stream class hierarchy, FreeList - free memory allocator, complex logger, profiler, library for threading and synchronization, tokenizer, wrappers for compression with zlib.

Language: C++. Platforms: Windows and Linux. License: GNU LGPL. Optional support for Unicode. Optional integration with D3DX. Documentation made with Doxygen.

Date: 2009-12-16

Download:
CommonLib_9_0.zip (4.92 MB)

Aqua Fish 2

Game for children - clone of PacMan. Player swims as a fish and collects points, as well as special items. Player also have to run away from enemies or destroy them. 60 maps in 6 different titlesets. Low hardware requirements. See also YouTube video. Game was published by Play Publishing company.

GameDev Calc

Calculator for game programmers. Basic data unit is a vector of 1-4 floating point numbers, which can be treated as (x,y,z,w) vector or (r,g,b,a) color. Next to basic calculations like addition, multiplication or sinus, vector operations are also available, e.g. vector normalization, conversion between degrees and radians, color conversion between RGB and HSB, finding linear an quadratic function coefficients and much more. Instead of entering single number, here you can see all the history of your calculations in form of stack and all operations are performed on that stack. Data can be entered and retrieved in different formats, like "D3DXVECTOR4(0.0f, 0.5f, 0.752f, 1.0f)" or "0xFF0080C0". Platform: Windows. Language: C#. License: GNU GPL.

Download:
GameDevCalc_1-0.zip (53.06 KB)
GameDevCalc_1-0_src.zip (50.73 KB)

RSS Feed: Adam Sawicki - Homepage (Blog) Blog

22:49
Fri
10
Feb 2012

How to Make Visual Studio Debugger not Step Into STL

It is annoying when you debug your C++ code in Visual Studio, want to step into your function, but the debugger enters source code of some STL container or string. For example, in the following code you will first enter std::basic_string constructor, then std::vector operator[] and then body of MyFunction.

MyFunction(std::string("abc"), myVector[0]);

It turns out there is a way to disable stepping into certain code, using regular expressions. To do this:

  1. Run Registry Editor (regedit.exe).
  2. Navigate to the key appropriate to your version of Visual Studio or Visual C++. "VCExpress" is for free Visual C++ Express, while "VisualStudio" is for commercial Visual Studio. Number is product version. Additional "Wow6432Node" should be used when working in 64-bit Windows. For example:
    • Visual C++ 2005 Express in 32-bit Windows: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VCExpress\8.0\NativeDE\StepOver
    • Visual Studio 2005 Professional in 32-bit Windows: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\NativeDE\StepOver
    • Visual Studio 2008 Professional in 64-bit Windows: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\NativeDE\StepOver (for version 2008 it's 9.0 not 8.0, the article linked below is wrong!)
    • Visual Studio 2010 Professional in 64-bit Windows: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\NativeDE\StepOver
  3. Create new String Value with any name and a value containing regular expression to match against identifiers you want to exclude, like "std\:\:.+" for all identifiers from STL namespace (including members of std::string, std::vector and so on). I assume you know the syntax of regular expressions.
  4. In Visual up to 2008, it starts working after you start new debug session (e.g. with F5). In Visual 2010, you have to restart whole IDE.

Here is the full story:

In May 2007 I asked the question on forum.warsztat.gd and written this blog entry (in Polish). Now I've also found this article: How to Not Step Into Functions using the Visual C++ Debugger, Andy Pennell's Blog and this StackOverflow question: Is there a way to automatically avoiding stepping into certain functions in Visual Studio?

From that I've learned that Visual Studio 6.0 used autoexp.dat file, while new versions use Windows registry.

Rules entered in registry can be suffixed with case-insensitive "=NoStepInto" (which is the default) or "=StepInto".

Aside from regular expression syntax you can use additional special codes: \cid (identifier), \funct (function name), \scope (class or namespace, like myns::CClass::), \anything (any string) and \oper (C++ operator).

Double backslashes you can meet on some web pages come from the REG file format, where backslash must be additionally escaped, like "\\:". If you enter regular expression straight into regedit, it should be "\:".

Comments (1) | Tags: debugger visual studio c++

22:05
Wed
08
Feb 2012

Optimizing Subqueries in MySQL

I'm not SQL guru, but I have to use databases from time to time, whether at home or at work, for desktop or (mostly) web applications. Some time ago I discovered a trick which greatly optimizes performance of complex queries that contain subqueries. I used it again recently when coding new comments administration panel for this website.

In my previous job I had a case when after several months of work my system gathered so much data that it couldn't generate report in any reasonable time. After applying this optimization reports from same data were generated instantly.

I know for these who deal with databases every day this "trick" or "optimization" is probably very basic, but if you - just like me - do only simple database tasks, it can be new to you. Here are the details:

Let's say we code a blog CMS and we have two tables:

CREATE TABLE posts (
    post_id int(11) NOT NULL AUTO_INCREMENT,
    title varchar(128) NOT NULL,
    content text NOT NULL,
    time datetime NOT NULL,
    PRIMARY KEY (post_id),
    KEY time_k (time)
);

CREATE TABLE comments (
    comment_id int(11) NOT NULL AUTO_INCREMENT,
    post_id int(11) NOT NULL,
    author varchar(32) NOT NULL,
    text text NOT NULL,
    time datetime NOT NULL,
    PRIMARY KEY (comment_id),
    KEY post_id_fk (post_id),
    CONSTRAINT post_id_fk FOREIGN KEY (post_id)
        REFERENCES posts (post_id) ON DELETE CASCADE ON UPDATE CASCADE
);

Read full entry > | Comments (1) | Tags: sql

17:38
Sat
04
Feb 2012

Algorithms for Managing Tree Structure

What are the ways of storing a tree data structure in memory? I mean a tree with arbitrary number of child nodes. Probably first thing that comes to our minds - as high level programmers - is to dynamically allocate each node as object of some class that would store its data and a collection of pointers to its children. Opposite approach would be to store all nodes in some array - a continuous piece of memory, where each node would refer to other nodes by index or something. Third approach - something in between in terms of sophistication, as well as efficiency - is to have dynamically allocated nodes, but not to store a collection of all child nodes. It is a good idea to employ kind of linked list here. I'd like to describe such data structure and basic algorithms for manipulating it.

The idea is that each node stores - besides its data - 5 pointers (possibly null) to some other nodes: parent, previous sibling, next sibling, first child and last child. It could be seen as equivalent to doubly linked list. It has much more pointers that is needed to be able to traverse whole tree, but thanks to this you can traverse such tree in any order, as well as insert and remove nodes at any point, with best possible time complexity. A node with Parent == null is considered a tree root. Here is a picture of a single node and example tree:

Read full entry > | Comments (3) | Tags: algorithms .net

18:05
Thu
02
Feb 2012

CPrintStream - Polymorphic Printf

Constructing and sending somewhere (like to the console or to file) a string created ("formatted") from multiple values of different types (strings, numbers) is a common task in every programming language. C implements it using printf function, which is very convenient, although not type safe. In C++ it is recommended to use streams from standard library, but they are slower, as well as much less pleasant to code comparing to the functions that use formatting string. Let's say you have a numeric variable and you want to print it as 8-digit hexadecimal value, like "0x00001234". Which option looks better?

#include <cstdlib>
#include <iostream>
#include <iomanip>

unsigned u = 0x1234;

// Option 1
printf("0x%08X\n", u);

// Option 2
std::cout << "0x" << std::setw(8) << std::setfill('0') << std::hex << u << std::endl;

I choose option 1 :) In the world of GUI applications, printing text messages may seem not so common, but sometimes it it useful, e.g. for logging debug information. Recently I thought: Why not connect the C-style printing with what is good in C++: classes and polymorphism? That's how I coded simple CPrintStream class and some derived classes, which I'd like to share here:

PrintStream.hpp
PrintStream.cpp

Abstract base class CPrintStream defines method printf(const char* format, ...) for printing a formatted message to some kind of target. Derived classes implemented this as printing to system console (CConsolePrintStream), file (CFilePrintStream) or a buffer in memory (CMemoryPrintStream).

Here are some implementation details. First problem I had to overcome was that the variable argument list ... cannot be passed from function to function. It has to be resolved to a value of type va_list using va_start and va_end functions. Fortunately this va_list object can be passed as argument to another function and all functions that take ... (like printf, fprintf) have their equivalents taking va_list (like vprintf, vfprintf). So my CPrintStream::printf method just converts ... to va_list and passes it to another method called vprintf, and only this one is pure virtual to be overriden in derived classes.

class CPrintStream {
public:
    virtual ~CPrintStream() = 0 { }
    void printf( const char* format, ... );
    virtual void vprintf( const char* format, va_list argList ) = 0;
};

CConsolePrintStream does its job using vprintf function from standard C library - the va_list equivalent of printf. CFilePrintStream uses fopen_s to open a file of type FILE* and does printing with vfprintf function - the va_list equivalent of fprintf.

Finally, the CMemoryPrintStream uses std::vector<char> as buffer for raw binary data. I believe that's the best choice as: 1. STL vector can be easily resized, 2. char is the type recommended to represent raw bytes, 3. vector stores data in continuous memory that you can safely access by writing &myVector[index], which is not guaranteed in std::string. How do I store formatted string in memory? I use vsprintf_s - the va_list equivalent of sprintf. But before this, I calculate required length with _vscprintf - a function I've learned about recently. I believe using it is much better than sprintf-ing to some buffer of constant length, e.g. char temp[1024], like many programmers do.

Comments (6) | Tags: c++

22:53
Tue
31
Jan 2012

Visual C++ is so Liberal

Here is an issue in C++ code I've came across some time ago and recently I've found again in some other code. This code is invalid according to language standard, still it compiles in Visual C++/Visual Studio and works correctly. Can you see what's wrong with it?

class Class1
{
public:
    int m_Number;
    Class1( int number ) : m_Number( number ) { }
};

void Function1( Class1& obj1 )
{
    obj1.m_Number = 2;
}

int main()
{
    Function1( Class1( 1 ) );
}

The problem is that we pass a temporary object of Class1 to the Function1, while this function takes object by reference, not by reference to const. Such R-value shouldn't be converted to non-const reference, or else we could modify the temporary object - which we actually do inside the function.

Visual C++ 2008 and 2010 with default project options compiles this without any warning. Setting Warning Level to 4 (/W4) generates a warning:

warning C4239: nonstandard extension used : 'argument' : conversion from 'Class1' to 'Class1 &'

Using Disable Language Extensions (/Za) makes it an error:

error C2664: 'Function1' : cannot convert parameter 1 from 'Class1' to 'Class1 &' A non-const reference may only be bound to an lvalue

It means we are dealing with a nonstandard Microsoft extension here. GCC refuses to compile this code, even with standard options:

error: invalid initialization of non-const reference of type 'Class1&' from an rvalue of type 'Class1' error: in passing argument 1 of 'void Function1(Class1&)'

Another story: Today I've learned that C++ standard doesn't have forward declarations of enums. I used it for long time and now I know it's another nonstandard Microsoft extension.

My conclusion is that programming in C++ using Visual C++ is like programming in DirectX using NVIDIA graphics cards: the platform is so liberal that your code may work even if you do something invalid. It also means that to use portable libraries instead of WinAPI is not enought to write code portable from Windows to Linux and other platform. You should also check if your code is accepted by other compilers. Increasing warning level in project options can also help with that, just like using Debug Version of Direct3D in DiectX Control Panel and observing debugger Output to find possible problems in calls to Direct3D API. It's better to ensure early that your code is valid instead of later complain that alternative (GCC) compiler or alternative (AMD) GPU driver causes problems.

On the other hand I believe that platform independence and strict C++ standard correctness is not a great value in itself. If you know your code is supposed to just work under Windows and be compiled in Visual C++, why not make use of available extensions and rely on specific compiler behavior? It can be convenient, while maintaining code that have to work with different compilers and platforms is a lot of additional work, possibly unnecesary.

Comments (5) | Tags: c++ visual studio

20:02
Sat
28
Jan 2012

Improved RSS Feed

I improved the script for generating news feed for my website. It now shows entire contents of my blog posts, including HTML formatting. So if you visit my blog sometimes and haven't done it yet, subscribe to my...

RSS Feed: Adam Sawicki - Homepage (Blog) RSS Feed

using some desktop or online reader, like the popular Google Reader. I use this one for some time and I like it a lot. RSS/Atom is really good technology. With it you can see unread updates from dozens of your favourite blogs in a single place and read them all without actually visiting the website.

Comments (0) | Tags: homepage webdev web

23:58
Fri
27
Jan 2012

New Colors

As you can see, I changed colors of my website. New new colors scheme is based on Solarized palette, which claims to be carefully designed to have some good properties. How do you like it?

EDIT: OK, you are right. That colors looked bad. But I will leave rounded corners from that new stylesheet :)

Comments (3) | Tags: homepage

19:01
Fri
27
Jan 2012

Unusual RAII from LibVLC

RAII (Resource Acquisition Is Intialization) is a programming technique recommended in C++ for managing and freeing all kinds of resources, like allocated memory or opened files. It involves creating on the stack (by value) an object of some class that will automatically free contained resources in its destructor, at the end of the scope. That's how smart pointers work. Using it is not only needed for exception safety. It generally helps not to forget about freeing resources, like when doing return or break in the middle of the code, as well as not to duplicate this freeing code.

When working with LibVLC library, I've spotted an interesting RAII-like pattern in its source code. It is based on a local structure inside a function, which holds resources and frees in its destructor these resources that are already acquired - like this:

bool DoLotsOfStuff()
{
    struct Resources
    {
        int* array;
        FILE* file;

        ~Resources()
        {
            if( file )
                fclose( file );
            if( array )
                delete[] array;
        }
    } resources = { 0 };

    // Do some startup...

    if( CheckSomeError() )
        return false;

    resources.array = new int[1024];

    // Do some work...

    if( CheckSomeError() )
        return false;

    resources.file = fopen( fileName, "rb" );
    if( resources.file == NULL )
        return false;

    // Do some more work...

    if( CheckSomeError() )
        return false;

    // array is freed and file is closed no matter if control reached here or returned earlier.
    
    return true;
}

Comments (4) | Tags: c++

Older entries >

STAT NO AD [Stat] [Admin] [STAT NO AD] [pub] [Mirror] Copyright © 2004-2012 Adam Sawicki
Copyright © 2004-2012 Adam Sawicki