## Monday, January 29, 2007

### Simple Particle Rendering.

Particles are really nice to see. usually we can see particle effects in most computer games . They appear as water fountain , flame, wind,sand, etc. It has infinite scope.  Actully we can create anything using particles.. But it will depends on the speed of computer.

In this page i am trying to create a simple particle engine , which renders a water fountain. So what is a particle ? the first answer coming to my mind is it is a point , but this is not fully correct. It can be represented as a point , or triangle , or polygon etc. This will depends on the application which we are writing. For the creation of water fountain we can assume the following attributes for a particle.

It is represented a single point . (GL_POINT in opengl )
it has 3 dimensions.
if follows gravity rules.  ( if we are using gravity).
it has a specific acceleration in all directions. ( 3 directions , x , y z).

Above are the basic things to keep in mind. So now we can create a structure like this

struct Particles
{

double xPos,yPos,zPos;
double xAcc; // xAcc is a constant one.
double yAcc; // this is a diminishing one due to the gravity.
double zAcc; // For the timebeing this is zero.
};
and
#define XACC .05
int        YACC 1.0

now we can create a bunch of particles by declaring an array of Particles.
Particles fountain[MAX_NUMS];

Now we need to design in which way one particle travels. it can be like this in a X-Y plane ( now no depth)

o  o
o         o
o             o
o               o

so for simulating the movement of a single particle we need to make changes on both x , y .we can keep the x acceleration as constant number ( Particles::xAcc) . If u look the image more closely it can be seen that the acceleration in y direction is more compared to X ,  it is also decreasing due to gravity.

so we can do it like this, For each particle particle[i].x += XACC ( constant) , and particle[i].y += particle[i].yAcc; so initially this particle[i].yAcc is initialized to 1. after each rendering this will be decreased by the amount of gravity , like  particle[i].yAcc-=gravity; so when the yAcc becomes -ve we will get a falling effect.

If a particles y value is  -ve and x value is +ve it means that , that particles is falled down to ground. so we need to again reinitialize it position to zero , again sets its acceleration and gravity to the predefined value...

Till now we have drawn only particles in 2d space, ie we haven't changed the z value. we can do that by giving rotating about y axis. The pseudo code is shown below..

For(int i = 0; i < TOT_PARTICLE;i++)
{

for(int j = 10; j < 360 ; j+=90)
{

glRoate(j degrees in y axis);
Apply colors or textures.
DrawParticle(particle[i].x,particle[i].y,particle[i].z);
ChangeAccleration(particle[i]); // here we are changing the accleration in both y and x direction
}
};

Now it is complete I am attaching a sample screen shot which i did with this idea. Hopes this may give some good starting for beginners who want to learn particles.

### How to create a simple particle Engine ( Computer Graphics)

Particles are really nice to see. usually we can see particle effects in most computer games . They appear as water fountain , flame, wind,sand, etc. It has infinite scope.  Actully we can create anything using particles.. But it will depends on the speed of computer.

In this page i am trying to create a simple particle engine , which renders a water fountain. So what is a particle ? the first answer coming to my mind is it is a point , but this is not fully correct. It can be represented as a point , or triangle , or polygon etc. This will depends on the application which we are writing. For the creation of water fountain we can assume the following attributes for a particle.

It is represented a single point . (GL_POINT in opengl )
it has 3 diamensions.
if follows gravity rules.  ( if we are using gravity).
it has a specific accleration in all directions. ( 3 directions , x , y z).

Above are the basic things to keep in mind. So now we can create a structure like this

struct Particles
{

double xPos,yPos,zPos;
double xAcc; // xAcc is a constant one.
double yAcc; // this is a diminishing one due to the gravity.
double zAcc; // For the timebeing this is zero.
};
and

#define XACC .05
int        YACC 1.0
now we can create a bunch of particles by declaring an array of Particles.

Particles fountain[MAX_NUMS];
Now we need to design in which way one particle travels. it can be like this in a X-Y plane ( now no depth)
o  o

o         o

o             o

o               o

so for simulating the movement of a single particle we need to make changes on both x , y .we can keep the x accelration as constant number ( Particles::xAcc) . If u look the image more closely it can be seen that the acceleration in y direction is more compared to X ,  it is also decreasing due to gravity.

so we can do it like this,

For each particle particle[i].x += XACC ( constant) , and particle[i].y += particle[i].yAcc; so initially this particle[i].yAcc is initialized to 1.

After each rendering this will be decreased by the amount of gravity , like  particle[i].yAcc-=gravity; so when the yAcc becomes -ve we will get a falling effect. If a particles y value is  -ve and x value is +ve it means that , that particles is falled down to ground. so we need to again reinitialize it position to zero , again sets its acceleration and gravity to the predefined value...

Till now we have drawn only particles in 2d space, ie we havn't changed the z value. we can do that by giving rotating about y axisl.The pseudo code is shown below..

For(int i = 0; i < TOT_PARTICLE;i++)
{
for(int j = 10; j < 360 ; j+=90)
{
glRoate(j degrees in y axis);
Apply colors or textures.
DrawParticle(particle[i].x,particle[i].y,particle[i].z);
ChangeAccleration(particle[i]); // here we are changing the accleration in both y and x direction
}
};

Now it is complete I am attaching a sample screen shot which i did with this idea. Hopes this may give some good starting for beginners who want to learn particles.

## Friday, January 12, 2007

What is a UI thread ?? its a normal thread with a windows. thats all . But the danger comes when you are creating MFC window's objects like CFrameWnd inside a normal thread created using CreateThread API function.

For example..

{

CFrameWnd * p  = new CFrameWnd()'
p->Create(0,"booommm");
p->ShowWindow(1); // normal show..

while(GetMessage())
{
TranslalteMsg(); DispatchMsg();
}
return 1;
}

When this code executes it will crash.. so use normal CreateWindow() function instead of CFrameWnd :: Create()..

If you want to use CFrameWnd use class CWinThread or AfxBeginThread() for creating threads.. Following code shows how it can be done with CWinThread class..

{

public  :
BOOL InitInstance()
{
CFrameWnd *ptr = new CFrameWnd();
pt->Create("0","painter man");
pt->ShowWindow(1);
}
}

one more thing is you won't need to write a messge loop for this window. This will be autmatically done by this class in CWinThread::Run()..
Life is more easy...

## Wednesday, January 10, 2007

In a Multithreading environment sometimes it usually needs to store data specific to each threads, This storage system is called thread local storage. Note that this is also taken from the total process address space. So In this page i am going to show some way how this can be done in Microsoft Windows systems..
Note that this storage space is very limited , and is varies according to the different implementing platforms (ie OS ).  In windows 2000 , Xp (and later) reserved total 1088 indexes per process. Windows 98 and ME reserves total 80 indexes per process and Windows 98 , NT reserved 64 indexes per process.

So what is this index ? it acts like an handle (not really ) .One thread have only one index at a time . Using this we can access the information specific to that thread. So if i am runnning a program in Xp i can create total 1088 indexes for each threads (Not tried  yet ) in that process. Well , How to get this index ? Microsoft provides APIs to get this indexes as well as storing data to TLS . Following are the APIs

DWORD TlsAlloc(void);
BOOL TlsSetValue( DWORD dwTlsIndex, LPVOID lpTlsValue );
LPVOID TlsGetValue(  DWORD dwTlsIndex);
BOOL TlsFree(  DWORD dwTlsIndex);
Sample usage

DWORD id;
Main()
{

id =  TlsAllc();
TlsFree(id);
}
{
p = ( <type *> )  TlsGetValue(id)
// do as u like
}
{
p = ( <type *> )  TlsGetValue(id)
// do as u like
}
Microsoft also proves much simpler usage. That is __declspec(thread) keryword. This keyword can also be attached to a static or ex tern data members... We know  that usually static data is common to all threads. But if attach _declspec(thread) to that member it is allocated to that threads local storage space.
ex : static __declspec(thread) int tlsData;

### Virtual Function and ZeroMemory

What caused me to write this post is a BUG. Really i am not joking.. Everone know that there is a virtual table pointer is present at the beginning of the object memory . i am also know that.. But i did a mistake long ago . Following lines shows it...

class Base
{
public :
virtual void Render()
{
}
};

class Derived: public Base
{
// i have several data members here..
public :
Derived()
{
// For easily initializing all of my data members to zero , i used ZeroMemory here
ZeroMemory(this,sizeof(Derived));
// Danger .. This also clear the virtual table pointer..
}
void Render()
{
}
};
So when i called it like
Derived *d = new Derived()
d->Render();

it crasheddd .... because of the ZeroMemory in the constructor set the vptr to Zero.

### Virtual Function and ZeroMemory

What caused me to write this post is a BUG. Really i am not joking.. Everyone know that there is a virtual table pointer is present at the  beginning of the object memory . i am also know that.. But i did a mistake long ago. Following lines shows it...

class Base
{

public :
virtual void Render()
{
}

};

class Derived: public Base
{

// i have several data members here..

public :

Derived()
{

// For easily initializing all of my data members to zero , i used ZeroMemory here

ZeroMemory(this,sizeof(Derived));
// Danger .. This also clear the virtual table pointer..
}

void Render()
{
}

};

So when i called it like

Derived *d = new Derived()
d->Render();

it crasheddd .... because of the ZeroMemory in the constructor set the vptr to Zero.

## Tuesday, January 9, 2007

### How to get all TCP/UDP ports in the system.

Recently my friend asked me how she can list all the opened TCP ports in the PC. After a quick search in google i found a utility netstat.exe.If you give the command netstat -p tcp this will lists all the established ports in the system. Established means TCP connection established .For getting all ports (which are in any state , like listeing , established etc) give netstat -a -p tcp. if we give netstat -b this will give the process name also, which opened this port.
Fine.. But my friend need some functions not this exe. I have heared about functions like GetTcpTable and GetUdpTable . This functions gives information similar to netstat gives like local port , local ip , remote port ,remote ip. But it hides the process identifier. so is not possible to know the port owners. This leads me to open the utility came with Visual studio 6 . it is famous Depdency checker. the netstat.exe is in system32 folder. I opened the netstat.exe and i found thatit uses the following functions from IPHLPAPI.dll .( GetTcpTable is also from dll ).

AllocateAndGetTcpExTable2FromStack
AllocateAndGetTcpExTableFromStack
AllocateAndGetUdpExTable2FromStack
AllocateAndGetUdpExTableFromStack

I tried with the AllocateAndGetTcpExTableFromStack and AllocateAndGetUdpExTableFromStack function . it is very similar to GetTcpTable and GetUdpTable. These function are kept at undocumented. anyway i am happy.. Thats all for now....

## Friday, January 5, 2007

### Implementation of the MFC Document View Architecture.

We know that every MFC application has a application class CWinApp which is derived from CWinThread class. Here First I am trying to find how the wizard creates the Frame, document, view classes, and how they are organized?

For an MFC application the best place to start is the InitInstance() function. This function is called from AfxWinMain. If IniInstance return false it indicates that application has failed to start. So this causes to immediately terminate the application. So in this case the wizard writes the InitInstance function like this

BOOL CTestApp::InitInstance()
{

INITCOMMONCONTROLSEX InitCtrls;
InitCommonControlsEx(&InitCtrls);

CWinApp::InitInstance();

CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(IDR_MAINFRAME,                        RUNTIME_CLASS(CtestviewDoc),RUNTIME_CLASS(CMainFrame),
RUNTIME_CLASS(CtestviewView));

if (!pDocTemplate)      return FALSE;

CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);

if (!ProcessShellCommand(cmdInfo))return FALSE;

m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
return TRUE;
}

First it creates a CSingleDocumentTemplate class’s object. CSingleDocumentTemplate is derived from CDocumentTemplate.

CDocumentTemplate class contains the following members of CRuntime class.
CRuntimeClass* m_pDocClass;         // class for creating new documents
CRuntimeClass* m_pFrameClass;       // class for creating new frames
CRuntimeClass* m_pViewClass;        // class for creating new views
CRuntimeClass* m_pOleFrameClass;    // class for creating in-place
CRuntimeClass* m_pOleViewClass;

In the IniInstance of CWinapp class wizard is creating a CSingleDocumentTemplate class object and initializes it with Run time class objects of our View. Frame, Doc classes.

After that the app class stores this newly created CSingleDocumentTemplate class object by calling a function AddDocTemplate(CDocTemplate* pTemplate). This is a member function of class CWinApp.

{
if (m_pDocManager == NULL)
m_pDocManager = new CDocManager;
}

m_pDocManager is a member variable of class CWinApp. Declared as  CDocManager* m_pDocManager; CDocManager contains a pointer array.  CWinApp::AddDocTemplate simply calls the function of m_pDocManager->AddDocTemplate(). Then Next line of IniInstance is like this.

CCommandLineInfo cmdInfo;The default command line is FileNew , that means create a new new document.

ParseCommandLine(cmdInfo); The parse command line looks the argv of main function and parses it ,

If finds anything it adds it to the cmdInfo object. For example if the command line is app sample.txt it sets the m_nShellCommand memmber of CCommandLineInfo class to FileOpen ,  And m_strFileName to the sample.txt. So in this case there is no command line arguments. Since the default command line is FileNew the ParseCommandLine lines just returns. The Next step wizrd does is calling the function CWinApp::ProcessShellCommand(cmdInfo). The ProcessShellCommand is written like this(removed all other codes.). So in our case it FileNew

switch (rCmdInfo.m_nShellCommand)
{

case CCommandLineInfo::FileNew:
OnFileNew()
break;
case CCommandLineInfo::FileOpen:
break;
case CCommandLineInfo::FilePrintTo:
case CCommandLineInfo::FilePrint:
break;
case CCommandLineInfo::FileDDE:
case CCommandLineInfo::AppRegister:
break;
case CCommandLineInfo::AppUnregister:
break;
};

In this case it finaly calls CWinApp::OnFileNew() function. Where all creation takes place. The CWinApp::OnFileNew simlpy calls the doc manager object’s OnFileNew. Like this

void CWinApp::OnFileNew()
{
if (m_pDocManager != NULL)
m_pDocManager->OnFileNew();
}

The CDocManager ::OnFileNew() checks for multiple templates . In this case here only 1 temmplate is present(becs this is SDI APP ). Earlier I told that CDocManager stores a list of CDocuemntTemplate class object. Here it gets the First object from list and calls the OpenDocumentFile(0) function. (psuedo code shown below )

void CDocManager::OnFileNew()
{
pTemplate->OpenDocumentFile(NULL);
}

The next part is the important part , where all creation takes place. So i am going to dig the CSingleDocument::OpenDoumentFile() function.This function creates the the object of CDocument ( our applications CDocument derived object) , Application's Frame class(CFrameWnd) and application's View class(CView). Well , lets see how these things happpens. Below i am presenting the skelton of CSingleDocTemplate::OpenDocumentFile() function.

CDocument* CSingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, BOOL bMakeVisible)
{
CDocument *pDocument = NULL;
CFrameWnd *pFrameWnd = NULL;
pDocument = CreateNewDocument();
pFrameWnd = CreateNewFrame();
}

Looking through the above function , we can understand that the Wizrd created document object by calling a function CreateNewObject function. So what is in this CreateNewDocument function ?? . i did dig again and find that , here wizard uses the CRuntime class's object .
Here i am rembering you about CDocTemplate class contains 3 CRuntime class members representing View,Document,Frame. Since CSingleDocTemaplte is derived from CDocTemplate it also gets these members. What i am trying to convey is that the CreateNewDocument function creates a new document using these runtime class. If you remember the Documnet class properly you can see the macros  DECLARE_DYNCREATE and  IMPLEMENT_DYNCREATE .

CDocument * CDocTemplate::CreateNewDocument()
{
CDocument* pDocument = (CDocument*)m_pDocClass->CreateObject();
return pDocument;

}

So what these macros doing ? we can see a CreateObject function in CreateNewDocument function. (m_pDocClass->CreateObject()). Actually this function is implemented by the IMPLEMENT_DYNCREATE macro. it just returning a pointer to our class.

Below is the implemenation of IMPLEMENT_DYNCREATE .

IMPLEMENT_DYNCREATE(class_name, base_class_name) \
CObject* PASCAL class_name::CreateObject() \
{
return new class_name; } \

IMPLEMENT_RUNTIMECLASS(class_name, base_class_name, 0xFFFF, \
class_name::CreateObject, NULL)

The CreateObject function is highlighted in red. So i think that part is clear. We learned how wizard is creating a new application Document class object. the next is with FrameWnd . Lets look the CreateNewFrame function. The CreateNewFrame function also creates the object of CFrameWnd class by using the Runtime class associated with the CDocTemplate class.The CreateNewFrame function is shown below.

CFrameWnd* CDocTemplate::CreateNewFrame(CDocument* pDoc, CFrameWnd* pOther)
{
CCreateContext context;
context.m_pCurrentFrame = pOther;
context.m_pCurrentDoc = pDoc;
context.m_pNewViewClass = m_pViewClass;
context.m_pNewDocTemplate = this;
if (pDoc != NULL) ASSERT_VALID(pDoc);

ASSERT(m_nIDResource != 0); // must have a resource ID to load from
CFrameWnd* pFrame = (CFrameWnd*)m_pFrameClass->CreateObject();
ASSERT_KINDOF(CFrameWnd, pFrame);
return pFrame;
}

The m_pFrameClass is a member of CDocTemplate Initialized in IniInistance function. (if you are not remembering refer top of this article ).m_pFrameClass is a CRuntimeClass's object. So the by calling the m_pFrameClass ->CreateObject() returns a pointer to fhe application CMainFrame (derived from CFrameWnd ) class object. The next step is creating the  window by calling LoadFrame().

The CFrameWnd::LoadFrame creates the window by calling the Create method , and  loads the accelerator information.  So what happend to View ???  . Lets look the code.. If you look at the CDocTemplate::CreateNewFrame() function above shown , you can see that the function creates an pbject of CCreateContext. ( CCreateContext context;). The wizrd assiging the context.pNewViewClass with runtime class of our view (m_pViewClass , this gets value on CSingleDocumentTemplate creation. refer IniInstance on the top. ).

## Thursday, January 4, 2007

### Some GDI Informations

Yesterday i just read some pages from the book

Windows Graphics Programming Win32 GDI and DirectDraw®

Feng Yuan
The Feng Yuan is working in mircosoft.  In this space i am going to share some knowledge i got from this book.  So Tell me what a GDI handle is ? like HPEN or HBRUSH or HGDIOBJ ? . Somebody may tell it is a pointer . me too thought like that till yesterday

Actually Take HGIOBJ as a 32 bit number (it can be pointer or anything).  We all know about the functions GetStockObject(). it is returning a predefined handle. If we call this GetStockObject(WHITE_BRUSH)  from 2 process it will return the same handle(32 bit Number). So what does it means ? it is not residing in user address space. it is in Kernel address space. May be initialized during system start-up.

The book says that the lower 12 bit of the GDi handle is a index to table. May be that tables stores all other information.The 24th bit position says whether it is a stock object or not. The GDI handle also store information about the type of the handle.

The following function Gives the handle type.
inline unsigned GetObjType(HGDIOBJ hGDIObj)
{
return (((unsigned) hGDIObj) >> 16) & 0x7F;
}

The return value can be one of the following.
typedef enum
{
gdi_objtypeb_dc          = 0x01,
gdi_objtypeb_region      = 0x04,
gdi_objtypeb_bitmap      = 0x05,
gdi_objtypeb_palette     = 0x08,
gdi_objtypeb_font        = 0x0a,
gdi_objtypeb_brush       = 0x10,
gdi_objtypeb_enhmetafile = 0x21,
gdi_objtypeb_pen         = 0x30,
gdi_objtypeb_extpen      = 0x50
};

Fortunately there is an undocumented function in GDI32.dll named GdiQueryTable() . It will return the address of the Table. using that address we can access all handles created by our program.

### Facts of a GDI Handle

Yesterday i just read some pages from the book

Windows Graphics Programming Win32 GDI and DirectDraw®

Feng Yuan
The Feng Yuan is working in mircosoft.  In this space i am going to share some knowledge i got from this book. So Tell me what a GDI handle is ? like HPEN or HBRUSH or HGDIOBJ ? . Somebody may tell it is a pointer . me too thought like that till yesterday , Now its changed.

Actually Take HGIOBJ as a 32 bit number (it can be pointer or anything).  We all know about the functions GetStockObject(). it is returning a predefined handle. If we call this GetStockObject(WHITE_BRUSH)  from 2 process it will return the same handle(32 bit Number). So what does it means ? it is not residing in user address space. it is in Kernel address space. May be initialized during system startup.  The book says that the lower 12 bit of the GDi handle is a index to table. May be that tables stores all other information. The 24th bit position says whether it is a stock object or not. The GDI handle also store information about the type of the handle.
The following function Gives the handle type.

inline unsigned GetObjType(HGDIOBJ hGDIObj)
{
return (((unsigned) hGDIObj) >> 16) & 0x7F;
}

The return value can be one of the following.

typedef enum
{
gdi_objtypeb_dc          = 0x01,
gdi_objtypeb_region      = 0x04,
gdi_objtypeb_bitmap      = 0x05,
gdi_objtypeb_palette     = 0x08,
gdi_objtypeb_font        = 0x0a,
gdi_objtypeb_brush       = 0x10,
gdi_objtypeb_enhmetafile = 0x21,
gdi_objtypeb_pen         = 0x30,
gdi_objtypeb_extpen      = 0x50
};

Fortunatly there is an undocumented function in GDI32.dll named GdiQueryTable() . It will return the address of the Table. using that address we can access all handles created by our program.