Sunday, November 21, 2010

Trees builder

Hello world!
Suddenly I’ve decided to make the simple trees builder.
No sooner said than done.

You can see result in the image below.


Every time the algorithm generates a new tree.
After some variations variables, I found the results' similarity with the real species of trees.

[Show / hide source code]
//------------------------------------------------------------------------------
// Build a new tree
//------------------------------------------------------------------------------
void BuildTree(Point startPoint, Point endPoint, int k)
{
    Random rnd = new Random((int)DateTime.Now.Ticks);
    Pen pen = new Pen(Color.Black, k);

    if (hasLeaves)
    {
        // set the color to rnd green and width = 5 for last branch as for a leaf
        if (k < 1) pen = new Pen(Color.FromArgb(0, rnd.Next(80, 160), 0), 5);
    }

    m_Graphics.DrawLine(pen, startPoint, endPoint);

    if (k > 0)
    {
        Point pNext = new Point();
     
        // add branch to the right
        pNext = new Point(endPoint.X + rnd.Next(0, spread), endPoint.Y - rnd.Next(0, speed));
        BuildTree(endPoint, pNext, k - 1);
     
        // add branch to the left
        pNext = new Point(endPoint.X - rnd.Next(0, spread), endPoint.Y - rnd.Next(0, speed));
        BuildTree(endPoint, pNext, k - 1);

        Application.DoEvents();
    }
}

* This source code was highlighted with Source Code Highlighter.

Monday, October 18, 2010

Steganography

The word steganography means "concealed writing" from the Greek words steganos meaning "covered", and graphein meaning "to write".

This is very ancient technology. So I’ll try to explain how it works.
It’s not a secret that every color can be represented as tuples of numbers, typically as three or four values or color components (e.g. RGB and CMYK).

It’s possible to use least significant bits of each color component for data storage. Thus it’s possible to use images for information hiding or steganography.
Let’s estimate the color component loss level for data storage.
The maximum loss level for 1 bit for color component coding will be 1b = 1 and the error will be:
1/255 * 100 % = 0,392 %
The maximum loss level for 2 bits per color component coding will be 11b = 3. So the maximum error per color component is equal:
3/255 * 100 % = 1,176 %
For 3 bits the maximum loss level will be 111b = 8 and the error will be:
8/255 * 100 % = 3,137 %
In common, human eye couldn’t distinguish so little difference in colors.

The picture below shows a principle of steganography using 2 bits per color channel coding. 
 
To hide ‘A’ char using 2 bits per color component coding required 4 color components or 2 pixels (RGB and yet another R).
Below you can see source code in C# for 2 bits per color component images coding and decoding.

[Show / hide source code]
//---------------------------------------------------------------------
// CodeStegoImage
//---------------------------------------------------------------------
private Bitmap CodeStegoImage(Image inputImage, string inputText)
{     
  string header = "DSTG"; // Steganorgaphy header
  int textLen = header.Length + inputText.Length + 4; // 4 bytes (65535 chars) for text length
  string lenStr = textLen.ToString("0000"); // make formated NNNN text length string
  string text = header + lenStr + inputText;

  byte[] bytes = new byte[text.Length * 4 + 4]; // 4 bytes for char using 2 bits coding + 4 bytes extra

  for (int i = 0; i < text.Length; i++)
  {
    bytes[i*4+0] = (byte)((System.Convert.ToChar(text[i]) & (byte)System.Convert.ToInt32("11000000", 2)) >> 6);
    bytes[i*4+1] = (byte)((System.Convert.ToChar(text[i]) & (byte)System.Convert.ToInt32("00110000", 2)) >> 4);
    bytes[i*4+2] = (byte)((System.Convert.ToChar(text[i]) & (byte)System.Convert.ToInt32("00001100", 2)) >> 2);
    bytes[i*4+3] = (byte)(System.Convert.ToChar(text[i]) & (byte)System.Convert.ToInt32("00000011", 2));
  }

  Bitmap bmIn = new Bitmap(inputImage);   // input bitmap
  Bitmap bmOut = new Bitmap(inputImage);  // output bitmap
  int counter = 0;

  for (int i = 0; i < inputImage.Height; i++)
  {
    for (int j = 0; j < inputImage.Width; j++)
    {
      Color colIn = bmIn.GetPixel(j, i);

      // clear 2 LSB
      uint ro = (uint)colIn.R & 0xFC; // 0xFC = 11111100b
      uint go = (uint)colIn.G & 0xFC;
      uint bo = (uint)colIn.B & 0xFC;

      Color colOut; // output color
      if (counter < text.Length * 4) // 4 bytes per char
      {
        colOut = Color.FromArgb((int)ro + bytes[counter + 0], (int)go + bytes[counter + 1], (int)bo + bytes[counter + 2]);
        counter += 3; // +3 bytes to next RGB pixel
      }
      else
        colOut = colIn;
      bmOut.SetPixel(j, i, colOut);
    }
  }
  return bmOut;
}

* This source code was highlighted with Source Code Highlighter.

Thursday, September 30, 2010

Solving the riddle

Solving the riddle "Hidden Message #3" from The Science of Deduction I've found the solution.

It turned out that it is encrypted with pigpen cipher.

The pigpen cipher (sometimes referred to as the masonic cipher, Freemason's cipher, or Rosicrucian cipher) is a geometric simple substitution cipher which exchanges letters for symbols which are fragments of a grid. The example key shows one way the letters can be assigned to the grid.


The solution to the riddle, using the picture above is obvious:
Sherlock I have found you

Monday, September 13, 2010

Programmer Day

Happy Programmer's Day!

Tuesday, August 24, 2010

HB

Happy Birthday Aximedia Soft! С днём рождения Аксимедиа Софт.
Aximedia Soft logo

Sunday, July 4, 2010

The IT Crowd

I like the 4th season of "The IT Crowd" very much. That's awesome! It made me laugh out loud )))

Friday, July 2, 2010

Riddles

В перерывах между работой решили занять себя математическими и логическими загадками.
Началось всё с простого и понеслась. Начали загадывать друг другу известные всем последовательности.
Russian version English equivalent
1) О Д Т Ч П ... O T T F F S S E N ...
2) П В С Ч П ... S M T W T ...
3) И Р Д В Т ?
4) К О Ж З ... R O Y G ...
5) Д Т П С О ... T T F S E ...
6) М В З М Ю ... M V E M J ...
7) 1 5 10 50 1 2 ...
8) E A D G ...
9) (1, 1) – (2, 3) – (1, 5) – (2, 7) – (4, 8) – (6, 7) – ?
10) 1 2 7 0 0 ?
11) IIIIIVIVIXII... ( "," present )
[+/-] Show / hide answers
1) Один Два Три Четыре Пять Шесть ...
One Two Three Four Five Six Seven Eight Nine Ten ...

2) Понедельник Вторник Среда Четверг Пятница Суббота ...
Sunday Monday Tuesday Wednesday Thursday Friday ...

3) Именительный Родительный Дательный Винительный Творительный Предложный

4) Красный Оранжевый Жёлтый Зелёный Голубой Синий ...
Red Orange Yellow Green Blue Violet

5) 2 3 5 7 11 13 17... Простые числа
Prime numbers

6) Меркурий Венера Земля Марс Юпитер Сатурн ...
Mercury Venus Earth Mars Jupiter Saturn ...

7) 1 коп 5 коп 10 коп 50 коп 1 руб 2 руб 5 руб ...

8) E A D G B E Основная настройка гитары

9) (1, 1) – (2, 3) – (1, 5) – (2, 7) – (4, 8) – (6, 7) – (8, 8) - ...
Ход шахматного коня

10) IP 127.0.0.1

11) 3,1415926535...

Thursday, June 17, 2010

Visual Studio 2010 Launch - Wave 2

В Microsoft решили, что запуску Visual Studio 2010 уделено недостаточно внимания.
По этой причине в России проходит вторая волна запуска VS2010.
В центре инноваций Microsoft ТПУ 23 июня пройдет Visual Studio 2010 Launch Wave 2.

Я прочитаю два доклада:
Отладка в Visual Studio 2010.
Менеджер расширений Visual Studio 2010.

Подробнее на сайте tpudotnet.ineta.ru

Saturday, May 29, 2010

One-liner

Сколько будет DBA + DBA ? 1B74

Tuesday, May 25, 2010

LOST is over

Thanks for amazing show!

Tuesday, May 18, 2010

House

Fox has announced that House M.D. will return for a 7th season.

Friday, April 30, 2010

Trigraphs

One of the surprising things to me during the reading of c++ standard were trigraphs.
A trigraph (Greek: tri- = three, -graph = write) is a combination of three symbols, most commonly letters used to represent a single speech sound.

Trigraph
Replacement
??=
 #
??/
\
??'
^
??(
[
??)
]
??!
|
??<
{
??>
}
??-
~

The trigraph sequences are used for compatibility of source code written in ISO-646 or EBCDIC charset.

Trigraphs have been proposed for removal in C++0x.
You can read about it in the paper N2910 that discusses trigraph deprecation.

Here is another interesting article - EBCDIC and the P-BIT (The Biggest Computer Goof Ever).

GNU C guide says: "You don't need this brain damage." The GCC compiler has trigraph support disabled by default.

??=include <stdio.h>
??=include <windows.h>

void main()
??<    
    unsigned char *a = new unsigned char??(2??);
    a??(0??) = 0x6; // 00000110 = 6
    a??(1??) = 0xc; // 00001100 = 12
    
    printf("%d or %d = %d\n", a[0], a[1], a[0] ??! a[1]); // 0110 | 1100 = 1110 = 14
    printf("%d xor %d = %d\n", a[0], a[1], a[0] ??' a[1]); // 0110 ^ 1100 = 1010 = 10
    printf("not 0x%08X = 0x%08X\n", 0x12345678, ??-0x12345678); // ~12345678 = EDCAB987

    printf("Trigraphs!!!\n"); 
    
    // comment ??/
    comment too!!!
??>

Support for trigraphs in Visual Studio 2010 is disabled by default. So use the /Zc:trigraphs compiler option to enable trigraphs support.

Sunday, April 25, 2010

XNB reverse engineering

XNB is XNA Game Studio Express XNA Framework Content Pipeline Binary File.

About two years ago, my friends wrote the game in XNA. XNA has not been installed on my PC at the time, but I was curious to see the game content, especially images from this game.
And to my great disappointment, all the contents had an unusual format XNB.

So I decided to analyze this file format and to write a simple converter.
First of all I mentioned that the XNB files size is too big.
I assumed that the image is stored in the XNB as a 32-bit uncompressed image. Unfortunately, I later discovered that XNB can store compressed images.

After some binary data analysis, I almost completely decoded the structure of XNB header.

XNB files may contain several different resources. Besides images whose content type is "Microsoft.Xna.Framework.Content.Texture2DReader" they can store Sprite Fonts, Lists, Vectors, Rectangles et al.

I convert XNB file containing only the uncompressed image to uncompressed 32-bit TGA file.

Here the source code:
#ifndef XNBFILE_H
#define XNBFILE_H

#include <stdio.h>
#include <windows.h>

class XnbFile
{
private:

    #define XNB_CONTENT_TEXTURE2D "Microsoft.Xna.Framework.Content.Texture2DReader"

    #define XNB_IDENT (('w' << 24) + ('B' << 16) + ('N' << 8) + 'X')

    struct ColorRGBA
    {
        unsigned char R; 
        unsigned char G; 
        unsigned char B; 
        unsigned char A;
    };
    
    #pragma pack (push, 1)

    struct XnbHead
    {
        int ident;
        WORD version;
    };    
    
    struct XnbAsset
    {    
        unsigned char text_len;
        char *text;
    };

    struct XnbInfo
    {
        unsigned int file_size;
        unsigned char num_assets;        
    };

    struct XnbImage
    {        
        unsigned char flagA[6]; // probably compression method
        unsigned int width;
        unsigned int height;
        unsigned char flagB[4]; // unknown
        unsigned char flagC[4]; // unknown
    };

    #pragma pack (pop, 1)

public:

    XnbFile() {}
    ~XnbFile() {}

    void LoadXnb(const char *name)
    {
        XnbHead header;
        XnbInfo info;
        XnbAsset asset;
        XnbImage img;        

        FILE *f = fopen(name, "rb");
        if (!f) return;

        fread(&header, 1, sizeof(header), f);

        if (header.ident != XNB_IDENT)
        {
            printf("ID of xnb file is incorrect!\n");
            return;
        }
        
        char *versions[4] = { "1.0", "2.0", "3.0", "3.1" };
        printf("The version of XNA is %s\n", versions[header.version - 1]);

        fread(&info, 1, sizeof(info), f);        
        fread(&asset.text_len, 1, 1, f);

        asset.text = new char[asset.text_len + 1];
        fread(asset.text, 1, asset.text_len, f);
        asset.text[asset.text_len] = '\0';

        fseek(f, 4, SEEK_CUR); 

        if(!strcmp(asset.text, XNB_CONTENT_TEXTURE2D))
        {
            fread(&img, 1, sizeof(img), f);

            ColorRGBA *data = new ColorRGBA[img.width * img.height];
            fread(data, 1, img.width * img.height * 4, f);

            char newname[256];
            strcpy(newname, name);
            strcat(newname, ".tga");

            SaveToTga(newname, (unsigned char*)data, img.width, img.height);
        }
        
        fclose(f);        
    }

    void SaveToTga(const char *name, const unsigned char *data, int w, int h) 
    {
        FILE *f = fopen(name,"wb");
        if (!f) return;

        unsigned char *buf;
        buf = new unsigned char[18 + w * h * 4]; // 18 bytes for header
        memset(buf, 0, 18);
        buf[2] = 2;
        buf[12] = w % 256;
        buf[13] = w / 256;
        buf[14] = h % 256;
        buf[15] = h / 256;
        buf[16] = 32;
        buf[17] = 0x28;
        memcpy(buf + 18, data, w * h * 4);
        fwrite(buf, 1, 18 + w * h * 4, f);

        delete buf;

        fclose(f);    
    }

};

#endif //XNBFILE_H

Tuesday, April 20, 2010

Adding the build counter line to MSVS output

Sometimes it’s very important to know how much builds you have built.
Here is the simple way how to do it.
Everything you need is to make build counter console application.

Source code of buildcounter.cpp:
#include <stdio.h>

void main()
{
    FILE *file1 = fopen("build.txt", "r");
    int build = 0;
    if (file1) fscanf(file1, "%d", &build); else return;
    fclose(file1);
    
    printf("Build %d\n", build);

    FILE *file2 = fopen("build.txt", "w+");
    if (file2) fprintf(file2, "%d\n", ++build); else return;
    fclose(file2);
}
As you can see current build is written to the file build.txt.

Thereafter you need to add your buildcounter.exe to pre-build event command line.


Finally, you'll get the following result:

Thursday, April 15, 2010

Set locale и русские буквы в консоли

Часто при написании консольных приложений можно увидеть следующую картину:


Возникает вопрос: как выводить русские буквы в консоль?

Для этого необходимо в коде добавить setlocale(LC_ALL, "rus");
и подключить модуль locale.h

Source code of test.cpp:

#include <stdio.h>
#include <locale.h>
#include <windows.h>

void main()
{
    setlocale(LC_ALL, "rus");
    printf("%s", "Привет мир!!!\n");
    system("pause");
}

В итоге получим:

Monday, April 12, 2010

Compiling code from the command line

Иногда, требуется собрать код написанный в блокноте.

Source code of test.cpp:

#include <stdio.h>
#include <windows.h>

void main()
{
     printf("Hello world!!!\n");
}

Для того чтобы скомпилить данный код, достаточно создать cmd или bat файл со следующим содержанием:

@echo off
call "%VS80COMNTOOLS%vsvars32.bat"
cl /EHsc /Fetest.exe /O2 test.cpp
test.exe

Где номер 80 в %VS80COMNTOOLS% зависит от версии Visual Studio.
Так для 2005 = 80, для 2008 = 90, а для 2010 = 100.



Sunday, March 28, 2010

First entry

Hello universe!!!