Friday, May 6, 2011

Simple screen capture example - GDI version.

A Simple screen capture example using windows handle and BitBlt.
This mechanism works for both GDI and DirectX window mode.
However, this screen capture has its own weakness, low performance and
abnormal mouse behaviour. Use it just as reference.



// Functions for captureing WoW screen.
//
HWND        getWoWWindowHandle(void)
{
    HWND        wowWnd;


    //return GetDesktopWindow();

    // Try to find WoW window handle.
    //
    wowWnd = FindWindow(TEXT("GxWindowClass"), TEXT("월드 오브 워크래프트"));
    if( wowWnd )
    {
        // The window is found.
        //
        return wowWnd;
    }
    else
        return NULL;
}


void        captureWoWWindow(HDC hTgtDC)
{
    HWND        hSrcWnd;
    HDC            hSrcDC;

    // Get WoW Window Handle.
    //
    hSrcWnd = getWoWWindowHandle();
    if( hSrcWnd )
    {
        hSrcDC = GetDC(hSrcWnd);

        BitBlt(hTgtDC, 0, 0, 960, 640, hSrcDC, 0, 0, SRCCOPY | CAPTUREBLT);

        ReleaseDC(hSrcWnd, hSrcDC);
    }

    return;
}

Wednesday, May 4, 2011

pthread_detach example c c++

Name

pthread_detach - put a running thread in the detached state

Synopsis

#include <pthread.h>
int pthread_detach(pthread_t th);

Description

pthread_detach puts the thread th in the detached state. This guarantees that the resources consumed by thwill be freed immediately when th terminates. However, this prevents other threads from synchronizing on the termination of th using pthread_join. If, when pthread_detach is called, th has already terminated, all of th's remaining resources will be freed.
A thread can be created initially in the detached state, using the detachstate attribute to pthread_create(3) . In contrast, pthread_detach applies to threads created in the joinable state, and which need to be put in the detached state later.
After pthread_detach completes, subsequent attempts to perform pthread_join on th will fail. If another thread is already joining the thread th at the time pthread_detach is called, th will be detached and pthread_join will eventually return when th terminates but may not return with th's correct return code.

Return Value

On success, 0 is returned. On error, a non-zero error code is returned.

Errors

ESRCH
No thread could be found corresponding to that specified by th
EINVAL
the thread th is already in the detached state
 
#include <stdio.h> 
#include <string.h> 
#include <pthread.h> 
 
pthread_t threads[5]; 
int done[5]; 
 
void *thread_main(void *); 
 
int main(void) 
{ 
    int i; 
    int rc; 
    int status; 
     
    printf("pid=%d\n", getpid()); 
 
    for (i = 0; i < 5; i++) 
    {     
        done[i] = 0; 
        pthread_create(&threads[i], NULL, &thread_main, (void *)i); 
        printf("%d, %d\n", i, threads[i]); 
    } 
 
    for (i = 4; i >= 0; i--) 
    { 
        done[i] = 1; 
        rc = pthread_join(threads[i], (void **)&status); /* detach thead에서는 사용할 필요 없다. */ 
        if (rc == 0) 
        { 
            printf("Completed join with thread %d status= %d\n",i, status); 
        } 
        else 
        { 
            printf("ERROR; return code from pthread_join() is %d, thread %d\n", rc, i); 
                 return -1; 
        } 
    } 
 
    return 0; 
} 
 
void *thread_main(void *arg) 
{ 
    int i; 
    double result=0.0; 
 
    pthread_detach(pthread_self()); /* 쓰레드 분리 */ 
 
    printf("therad: %d, %d\n", (int)arg, getpid()); 
 
    while (!done[(int)arg]) 
    { 
            for (i=0; i < 1000000; i++) 
           { 
                 result = result + (double)random(); 
           } 
           printf("thread: %d, result = %e\n", (int)arg, result); 
    } 
 
    pthread_exit((void *) 0); 
} 
 

pthread_cancel example c c++

NAME         top

       pthread_cancel - send a cancellation request to a thread

SYNOPSIS         top

       #include <pthread.h>

       int pthread_cancel(pthread_t thread);

       Compile and link with -pthread.

DESCRIPTION         top

       The pthread_cancel() function sends a cancellation request to the thread
       thread.  Whether and when the target thread reacts to the cancellation
       request depends on two attributes that are under the control of that
       thread: its cancelability state and type.

       A thread's cancelability state, determined by pthread_setcancelstate(3),
       can be enabled (the default for new threads) or disabled.  If a thread has
       disabled cancellation, then a cancellation request remains queued until the
       thread enables cancellation.  If a thread has enabled cancellation, then
       its cancelability type determines when cancellation occurs. (pthread_cancel)


       A thread's cancellation type, determined by pthread_setcanceltype(3), may
       be either asynchronous or deferred (the default for new threads).
       Asynchronous cancelability means that the thread can be canceled at any
       time (usually immediately, but the system does not guarantee this).
       Deferred cancelability means that cancellation will be delayed until the
       thread next calls a function that is a cancellation point.  A list of
       functions that are or may be cancellation points is provided in
       pthreads(7).

       When a cancellation requested is acted on, the following steps occur for
       thread (in this order):

       1. Cancellation clean-up handlers are popped (in the reverse of the order
          in which they were pushed) and called.  (See pthread_cleanup_push(3).)

       2. Thread-specific data destructors are called, in an unspecified order.
          (See pthread_key_create(3).)

       3. The thread is terminated.  (See pthread_exit(3).)

       The above steps happen asynchronously with respect to the pthread_cancel()
       call; the return status of pthread_cancel() merely informs the caller
       whether the cancellation request was successfully queued.

       After a canceled thread has terminated, a join with that thread using
       pthread_join(3) obtains PTHREAD_CANCELED as the thread's exit status.
       (Joining with a thread is the only way to know that cancellation has
       completed.)

RETURN VALUE         top

       On success, pthread_cancel() returns 0; on error, it returns a nonzero
       error number.

ERRORS         top

       ESRCH  No thread with the ID thread could be found.

 
Example 

#include <stdio.h> 
#include <string.h> 
#include <pthread.h> 
 
pthread_t threads[5]; 
int done[5]; 
 
void *thread_main(void *); 
 
int main(void) 
{ 
    int i; 
    int rc; 
    int status; 
     
    printf("pid=%d\n", getpid()); 
 
    for (i = 0; i < 5; i++) 
    {     
        done[i] = 0; 
        pthread_create(&threads[i], NULL, &thread_main, (void *)i); 
        printf("%d, %d\n", i, threads[i]); 
    } 
 
    for (i = 4; i >= 0; i--) 
    { 
        rc = pthread_cancel(threads[i]); // 
        if (rc == 0) 
        { 
            // 자동종료 
            rc = pthread_join(threads[i], (void **)&status); 
            if (rc == 0) 
            { 
                printf("Completed join with thread %d status= %d\n",i, status); 
            } 
            else 
            { 
                printf("ERROR; return code from pthread_join() is %d, thread %d\n", rc, i); 
                     return -1; 
            } 
        } 
    } 
 
    return 0; 
} 
 
void *thread_main(void *arg) 
{ 
    int i; 
    double result=0.0; 
 
    printf("therad: %d, %d\n", (int)arg, getpid()); 
 
    while (!done[(int)arg]) 
    { 
      for (i=0; i < 1000000; i++) 
        { 
          result = result + (double)random(); 
      } 
        printf("thread: %d, result = %e\n", (int)arg, result); 
    } 
 
    pthread_exit((void *) 0); 
} 

pthread example - basic 2

A simple pthread example which creates a thread with pthread_create() and
exits with pthread_exit() and pthread_join().

Code for the ptrehad example is listed below.


#include <stdio.h> 
#include <string.h> 
#include <pthread.h> 
 
pthread_t threads[5]; 
int done[5]; 
 
void *thread_main(void *); 
 
int main(void) 
{ 
    int i; 
    int rc; 
    int status; 
     
    printf("pid=%d\n", getpid()); 
     
    for (i = 0; i < 5; i++) 
    {     
        done[i] = 0; 
        pthread_create(&threads[i], NULL, &thread_main, (void *)i); 
        printf("%d, %d\n", i, threads[i]); 
    } 
 
    for (i = 4; i >= 0; i--) 
    { 
        done[i] = 1; 
             rc = pthread_join(threads[i], (void **)&status); 
        if (rc == 0) 
        { 
            printf("Completed join with thread %d status= %d\n",i, status); 
        } 
        else 
        { 
            printf("ERROR; return code from pthread_join() is %d, thread %d\n", rc, i); 
                          return -1; 
        } 
    } 
 
    return 0; 
} 
 
void *thread_main(void *arg) 
{ 
    int i; 
    double result=0.0; 
 
    printf("therad: %d, %d\n", (int)arg, getpid()); 
 
    while (!done[(int)arg]) 
    { 
       for (i=0; i < 1000000; i++) 
          { 
               result = result + (double)random(); 
          } 
          printf("thread: %d, result = %e\n", (int)arg, result); 
    } 
 
    pthread_exit((void *) 0); 
} 
 

glTexImage2D example C/C++

An example of glTextImage2D() function in C/C++ language. Collected from http://stackoverflow.com/questions/679210/how-can-i-use-a-dynamically-sized-texture-array-with-glteximage2d
glTexImage2D() is used to load an image to GPU memory.

Currently, I'm able to load in a static sized texture which I have created. In this case it's 512 x 512.
This code is from the header:
#define TEXTURE_WIDTH 512
#define TEXTURE_HEIGHT 512
GLubyte textureArray[TEXTURE_HEIGHT][TEXTURE_WIDTH][4];
Here's the usage of glTexImage2D:
glTexImage2D(
        GL_TEXTURE_2D, 0, GL_RGBA,
        TEXTURE_WIDTH, TEXTURE_HEIGHT,
        0, GL_RGBA, GL_UNSIGNED_BYTE, textureArray);
And here's how I'm populating the array (rough example, not exact copy from my code):
for (int i = 0; i < getTexturePixelCount(); i++)
{
    textureArray[column][row][0] = (GLubyte)pixelValue1;
    textureArray[column][row][1] = (GLubyte)pixelValue2;
    textureArray[column][row][2] = (GLubyte)pixelValue3;
    textureArray[column][row][3] = (GLubyte)pixelValue4;
}
How do I change that so that there's no need for TEXTURE_WIDTH and TEXTURE_HEIGHT? Perhaps I could use a pointer style array and dynamically allocate the memory...

OpenGL SwapBuffers() example Windows.

SwapBuffers(hdc) function is used to switch front and back buffer of OpenGL surface.
So, it effectively requires double-buffering. In OpenGL, your drawing is not updated to screen until you call SwapBuffers(hdc) function.

void    DrawIt()
{
    // Drawing OpenGL Geometry.
    //
    glClear(GL_COLOR_BUFFER_BIT);

    //glPushMatrix();

    glScalef(0.5f, 0.5f, 0.5f);
    glBegin(GL_TRIANGLES);
        glColor3f(1.0f, 0.0f, 0.0f);
        glVertex3f(-1.0f, -1.0f, -1.0f);
        glColor3f(0.0f, 1.0f, 0.0f);
        glVertex3f(1.0f, -1.0f, -1.0f);
        glColor3f(0.0f, 0.0f, 1.0f);
        glVertex3f(0.0f, 1.0f, -1.0f);
    glEnd();

    //glPopMatrix();

    SwapBuffers(g_hDC);

    return;
}

OpenGL Initialization example.

Following code is OpenGL initialization example using WGL.
First, it creates a GL surface for rendering and associate it with
current windows Device Context. WGL(an Windows version of EGL) is
used to perform this work. [tag: OpenGL Initialization]

BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

    // Adjust the window size.
    RECT    kRect = { 0, 0, g_iWidth-1, g_iHeight-1 };

    AdjustWindowRect(&kRect, WS_OVERLAPPEDWINDOW, true);

    hInst = hInstance;

    hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      0, 0, kRect.right - kRect.left + 1, kRect.bottom - kRect.top + 1, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   // Get DC for OpenGL.
   g_hDC = GetDC(hWnd);

   {
        // Select format for drawing surface.
        PIXELFORMATDESCRIPTOR    kPFD;
        int                        iPixelFormat;
        BOOL                    bSuccess;

        memset(&kPFD, 0, sizeof(PIXELFORMATDESCRIPTOR));
        kPFD.nSize = sizeof(PIXELFORMATDESCRIPTOR);
        kPFD.nVersion = 1;
        kPFD.dwFlags = PFD_DRAW_TO_WINDOW |
                        PFD_SUPPORT_OPENGL |
                        PFD_GENERIC_ACCELERATED |
                        PFD_DOUBLEBUFFER;
        kPFD.iPixelType = PFD_TYPE_RGBA;
        kPFD.cColorBits = 24;
        kPFD.cDepthBits = 16;
        kPFD.cStencilBits = 8;

        // Choose pixel format.
        iPixelFormat = ChoosePixelFormat(g_hDC, &kPFD);
        if( iPixelFormat == 0 )
        {
            ReleaseDC(hWnd, g_hDC);
            return -1;
        }

        // Set pixel format.
        bSuccess = SetPixelFormat(g_hDC, iPixelFormat, &kPFD);
        if( !bSuccess )
        {
            ReleaseDC(hWnd, g_hDC);
            return -1;
        }

        // Create openGL context.
        g_hGLRC = wglCreateContext(g_hDC);
        if( !g_hGLRC )
        {
            ReleaseDC(hWnd, g_hDC);
            return -3;
        }

        // Make current context.
        bSuccess = wglMakeCurrent(g_hDC, g_hGLRC);
        if( !bSuccess )
        {
            wglDeleteContext(g_hGLRC);
            ReleaseDC(hWnd, g_hDC);
            return -4;
        }

        // Initialize OpenGL Environment.
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();

        // Set viewport.
        glViewport(0, 0, g_iWidth, g_iHeight);

        // Set ModelView matrix.
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        // Set clear color.
        glClearColor(0.2f, 0.0f, 0.0f, 1.0f);
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}