Jump to content

  • Log In with Google      Sign In   
  • Create Account


chris2307

Member Since 24 Apr 2012
Offline Last Active Mar 08 2013 09:06 AM

Topics I've Started

Sprite object no longer renders when put in to a Vector

03 February 2013 - 04:08 PM

Hi all, I created a player object and it worked fine. However, now I have put the player object in to a vector (as I want to add more of them later on) and it no longer renders to the screen. The object does exist because on feature of the player is that when you click on it, some player information is displayed above the sprite and this text information is still rendered when I click on the area the object is. I have tested the HRESULT codes coming back from draw() and D3DXCreateTextureFromFileEx() and both indicate success. Also, by clicking on the approximate area where the sprite is and moving the sprite around, I can tell that the sprite moves around as normal too. It just isn't displayed. Neither is this down to the render order - the sprite is rendered after everything in the program. Can anyone help with this?

 

Main

/**********************************************
*
* Title: Store Tycoon
* Author: Chris Ramsey
* Created: January 2013
*
*
*
***********************************************/

#include "Headers.h."
#include "Customer.h"
#include "Background.h"
#include "Counter.h"
#include "GameStations.h"
#include "ConsoleCab.h"
#include "ClothesStand.h"
#include "GamePanel.h"

std::vector<Customer> customers;

Customer customer;
Background background;
Counter counter;
GameStations gameStations;
ConsoleCab consoleCab;
ClothesStand clothesStand;
GamePanel gamePanel;

void initDirectX(HWND hWnd);       // Initializes Direct3D Graphics
void render();                     // Render graphics
void cleanUp();                    // Cleans everything up and releases memory

LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    HWND hWnd;                                          // The handle to the window function
    WNDCLASSEX window;                                  // Pointer to window struct
    ZeroMemory(&window, sizeof(WNDCLASSEX));            // Clears window class so we can use it
    window.cbSize = sizeof(WNDCLASSEX);                 // Size of window
    window.style = CS_HREDRAW | CS_VREDRAW;             // Redraws the entire window if a movement or size adjustment changes the height of the client area.
    window.lpfnWndProc = WindowProc;                    // Pointer to the window procedure
    window.hInstance = hInstance;                       // Handle to current instance
    window.hCursor = LoadCursor(NULL, IDC_ARROW);       // We'll stick with the normal cursor here
    window.lpszClassName = "Window";                    // Gives the class a name
    RegisterClassEx(&window);                           // Registers the window class

    hWnd = CreateWindowEx(NULL,
        "Window",                     // Name of the class
        "Space Game",                 // Title of the window
        WS_EX_TOPMOST | WS_POPUP,     // Fullscreen
        0, 0,                         // Position of window (0,0 for fullscreen)
        SCREEN_WIDTH, SCREEN_HEIGHT,  // Screen resolution (Uses global declaration)
        NULL,                         // Parent window (None)
        NULL,                         // Menus (None)
        hInstance,                    // Application handle
        NULL);                        // Set to NULL as we aren't using more than 1 window

    ShowWindow(hWnd, nCmdShow);                         // Display window
    initDirectX(hWnd);                                  // Initialises the directX graphics
    MSG msg = {0};                                      // msg holds the Windows events message queue

    customers.push_back(Customer());

    background.loadGraphics();
    counter.loadGraphics();
    gameStations.loadGraphics();
    consoleCab.loadGraphics();
    clothesStand.loadGraphics();
    gamePanel.loadGraphics();

    /************************************** Main game loop *************************************************/

    while(TRUE)                                         // Main game loop
    {
        if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))     // If messages are waiting
        {
            TranslateMessage(&msg);                      // Translates the keystroke messages into the correct format
            DispatchMessage(&msg);                       // Sends message to the windowsProc function
            if(msg.message == WM_QUIT)                   // If the message was a quit message
                break;                                   // Breaks out of main game loop
        }
        else                  
        {
            
            for (std::vector<Customer>::iterator customerIT = customers.begin(); customerIT != customers.end(); customerIT++)
            {
                (*customerIT).checkInteractivity();
                (*customerIT).move();
            }

            //customer.checkInteractivity();
            //customer.move();
            gamePanel.hoverDetection();
            render();
        }
    }

    /*******************************************************************************************************/

    // We are out of the main game loop (Due to a WM_QUIT signal)
    cleanUp();                                          // Do some housekeeping before quitting
    return msg.wParam;                                  // Return the WM_QUIT message to Windows. End of program
}

LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)                                     // Sorts through messages
    {
    case WM_DESTROY:                                // When window has been closed
        {
            PostQuitMessage(0);                     // Closes the application
            return 0;  
        }
        break;
    }
    return DefWindowProc (hWnd,                         // Returns any messages the switch statement didn't pick up
        message,
        wParam,
        lParam);
}

void initDirectX(HWND hWnd)
{
    d3d = Direct3DCreate9(D3D_SDK_VERSION);              // Create DirectX9 interface
    D3DPRESENT_PARAMETERS d3dParameters;                 // Pointer to DirectX9 parameters

    ZeroMemory(&d3dParameters, sizeof(d3dParameters));   // Clears the structure so we can use it
    d3dParameters.Windowed = FALSE;                      // Fullscreen
    d3dParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;    // Get rid of old framess
    d3dParameters.hDeviceWindow = hWnd;                  // Sets the window to be used by Direct3D
    d3dParameters.BackBufferFormat = D3DFMT_X8R8G8B8;    // Sets the back buffer format to 32-bit
    d3dParameters.BackBufferWidth = SCREEN_WIDTH;        // Sets the width of the buffer
    d3dParameters.BackBufferHeight = SCREEN_HEIGHT;      // Sets the height of the buffer

    d3d->CreateDevice(D3DADAPTER_DEFAULT,                // Creates a device class
        D3DDEVTYPE_HAL,
        hWnd,
        D3DCREATE_SOFTWARE_VERTEXPROCESSING,
        &d3dParameters,
        &d3dDevice);

    D3DXCreateSprite(d3dDevice, &d3dSprite);
}

void render()
{
    d3dDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(10, 0, 32), 1.0f, 0);   // Clears the screen to a dark blue
    d3dDevice->BeginScene();                                                         // Begins Direct3D scene
    d3dSprite->Begin(D3DXSPRITE_ALPHABLEND);                                         // Begin sprite drawing

    background.draw();

    counter.draw();
    gameStations.draw();
    consoleCab.draw();
    clothesStand.draw();
    gamePanel.updateInformation(564.55, 800.56, 1034.54, "July");

    
    for (std::vector<Customer>::iterator customerIT = customers.begin(); customerIT != customers.end(); customerIT++)
    {
        (*customerIT).draw();
    }

    gamePanel.draw();

    d3dSprite->End();                                                                // End drawing
    d3dDevice->EndScene();                                                           // Ends the Direct3D scene
    d3dDevice->Present(NULL, NULL, NULL, NULL);                                      // Presents the Direct3D scene (Displays to screen)
}

void cleanUp()
{
    d3dDevice->Release();   // Closes the Direct3D device and releases memory
    d3d->Release();         // Closes Direct3D and releases memory
}

 

Player Class

 

#include "Headers.h"
#include "Playercard.h"

class Customer{

private:

    LPDIRECT3DTEXTURE9 texture, playerInfoCard;
    D3DXVECTOR3 position, direction, playerCardPosition;
    D3DXVECTOR3 center;
    LPD3DXFONT font;
    POINT curPos;

    HRESULT rc;
    
    //Playercard playerCard;
    int depthBuffer;
    int walkingAlternator;

    RECT textBox;

    Playercard playercard;


public:

    Customer()
    {
        direction.x = (float)cos(0.558)*4;    // 30 degree movement
        direction.y = (float)sin(0.558)*4;    // 30 degree movement
        position.x = 500;
        position.y = 500;

        playercard.load(name, male, age, cash, productWanted);
        loadGraphics();
    }


    void move()
    {
        if(KEY_DOWN(0x57) || KEY_DOWN(VK_UP))
        {
            position.y -= direction.y;
            position.x += direction.x;
            walkingUp();
        }
        else if(KEY_DOWN(0x41) || KEY_DOWN(VK_LEFT))
        {
            position.y -= direction.y;
            position.x -= direction.x;
            walkingLeft();
        }
        else if(KEY_DOWN(0x53) || KEY_DOWN(VK_DOWN))
        {
            position.y += direction.y;
            position.x -= direction.x;
            walkingDown();
        }
        else if(KEY_DOWN(0x44) || KEY_DOWN(VK_RIGHT))
        {
            position.y += direction.y;
            position.x += direction.x;
            walkingRight();
        }
        else
        {
            // Reset the sprite here so that the feet are together in resting position AND so that sprite is facing the way it was going when it stopped
        }
    }

    void loadGraphics()
    {
        D3DXCreateTextureFromFileEx(d3dDevice, "player_information_card.png", D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 0, 0,
            D3DFMT_UNKNOWN, D3DPOOL_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), NULL, NULL, &playerInfoCard);
        
/*        if(rc == D3D_OK)
        {
            diagFile.open("Diag.txt");
            diagFile.write("CreateTexture was okay", 100);
            diagFile.close();
        }*/

        D3DXCreateTextureFromFileEx(d3dDevice, "Characters/female_shopper1.png", D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,
            D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), NULL, NULL, &texture);

        D3DXVECTOR3 position(100.0f, 100.0f, 0.0f);
        D3DXVECTOR3 center(0.0f, 0.0f, 0.0f);
        
        D3DXCreateFont(d3dDevice,                    // the D3D Device
                   20,                                // font height of 30
                   0,                                // default font width
                   FW_NORMAL,                        // font weight
                   1,                                // not using MipLevels
                   false,                            // italic font
                   DEFAULT_CHARSET,                    // default character set
                   OUT_DEFAULT_PRECIS,                // default OutputPrecision,
                   DEFAULT_QUALITY,                    // default Quality
                   DEFAULT_PITCH | FF_DONTCARE,        // default pitch and family
                   "Georgia",                        // use Facename Arial
                   &font);                            // the font object    
    }

    void draw()
    {
        d3dSprite->Draw(texture, NULL, &center, &position, D3DCOLOR_XRGB(255, 255, 255));
        
        if(displayPlayerCard)
        {
            playerCardPosition = position;
            playerCardPosition.y -= 128;
            playerCardPosition.x += 32;

            SetRect(&textBox, (int)playerCardPosition.x+5, (int)playerCardPosition.y+5, (int)playerCardPosition.x+256-5, (int)playerCardPosition.y+128-5);

            d3dSprite->Draw(playerInfoCard, NULL, &center, &playerCardPosition, D3DCOLOR_XRGB(255, 255, 255));
            font->DrawTextA(d3dSprite, playercard.plCard(), -1, &textBox, DT_LEFT, D3DCOLOR_XRGB(255, 255, 255));
        }
    }

    void walkingDown()
    {
        if(walkingAlternator == 1 || walkingAlternator == 2 || walkingAlternator == 3 || walkingAlternator == 4 || walkingAlternator == 5
            || walkingAlternator == 6 || walkingAlternator == 7 || walkingAlternator == 8 || walkingAlternator == 9 || walkingAlternator == 10)
        {
            D3DXCreateTextureFromFileEx(d3dDevice, "Characters/female_shopper2.png", D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,
            D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), NULL, NULL, &texture);
            walkingAlternator++;
        }
        else if(walkingAlternator == 11 || walkingAlternator == 12 || walkingAlternator == 13 || walkingAlternator == 14 || walkingAlternator == 15
            || walkingAlternator == 16 || walkingAlternator == 17 || walkingAlternator == 18 || walkingAlternator == 19 || walkingAlternator == 20)
        {
            D3DXCreateTextureFromFileEx(d3dDevice, "Characters/female_shopper3.png", D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,
            D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), NULL, NULL, &texture);
            walkingAlternator++;
        }

        if(walkingAlternator >= 20)
        {
            walkingAlternator = 1;
        }
    }

    void walkingUp()
    {
        if(walkingAlternator == 1 || walkingAlternator == 2 || walkingAlternator == 3 || walkingAlternator == 4 || walkingAlternator == 5
            || walkingAlternator == 6 || walkingAlternator == 7 || walkingAlternator == 8 || walkingAlternator == 9 || walkingAlternator == 10)
        {
            D3DXCreateTextureFromFileEx(d3dDevice, "Characters/female_shopper1_back2.png", D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,
            D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), NULL, NULL, &texture);
            walkingAlternator++;
        }
        else if(walkingAlternator == 11 || walkingAlternator == 12 || walkingAlternator == 13 || walkingAlternator == 14 || walkingAlternator == 15
            || walkingAlternator == 16 || walkingAlternator == 17 || walkingAlternator == 18 || walkingAlternator == 19 || walkingAlternator == 20)
        {
            D3DXCreateTextureFromFileEx(d3dDevice, "Characters/female_shopper1_back1.png", D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,
            D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), NULL, NULL, &texture);
            walkingAlternator++;
        }

        if(walkingAlternator >= 20)
        {
            walkingAlternator = 1;
        }
    }

    void walkingLeft()
    {
        if(walkingAlternator == 1 || walkingAlternator == 2 || walkingAlternator == 3 || walkingAlternator == 4 || walkingAlternator == 5
            || walkingAlternator == 6 || walkingAlternator == 7 || walkingAlternator == 8 || walkingAlternator == 9 || walkingAlternator == 10)
        {
            D3DXCreateTextureFromFileEx(d3dDevice, "Characters/female_shopper1_back3.png", D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,
            D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), NULL, NULL, &texture);
            walkingAlternator++;
        }
        else if(walkingAlternator == 11 || walkingAlternator == 12 || walkingAlternator == 13 || walkingAlternator == 14 || walkingAlternator == 15
            || walkingAlternator == 16 || walkingAlternator == 17 || walkingAlternator == 18 || walkingAlternator == 19 || walkingAlternator == 20)
        {
            D3DXCreateTextureFromFileEx(d3dDevice, "Characters/female_shopper1_back4.png", D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,
            D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), NULL, NULL, &texture);
            walkingAlternator++;
        }

        if(walkingAlternator >= 20)
        {
            walkingAlternator = 1;
        }
    }

    void walkingRight()
    {
        if(walkingAlternator == 1 || walkingAlternator == 2 || walkingAlternator == 3 || walkingAlternator == 4 || walkingAlternator == 5
            || walkingAlternator == 6 || walkingAlternator == 7 || walkingAlternator == 8 || walkingAlternator == 9 || walkingAlternator == 10)
        {
            D3DXCreateTextureFromFileEx(d3dDevice, "Characters/female_shopper4.png", D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,
            D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), NULL, NULL, &texture);
            walkingAlternator++;
        }
        else if(walkingAlternator == 11 || walkingAlternator == 12 || walkingAlternator == 13 || walkingAlternator == 14 || walkingAlternator == 15
            || walkingAlternator == 16 || walkingAlternator == 17 || walkingAlternator == 18 || walkingAlternator == 19 || walkingAlternator == 20)
        {
            D3DXCreateTextureFromFileEx(d3dDevice, "Characters/female_shopper5.png", D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,
            D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), NULL, NULL, &texture);
            walkingAlternator++;
        }

        if(walkingAlternator >= 20)
        {
            walkingAlternator = 1;
        }
    }

    void checkInteractivity()
    {
        GetCursorPos(&curPos);
        if (GetKeyState(VK_LBUTTON) & 0x80 &&                        
            curPos.x >= position.x && curPos.x <= position.x+64 &&   
            curPos.y >= position.y && curPos.y <= position.y+128)    
        {
            displayPlayerCard = true;
        }
        else
        {
            displayPlayerCard = false;
        }
    }

    D3DXVECTOR3 returnPosition()
    {
        return position;
    }

    D3DXVECTOR3 returnPosition(bool returnCentreOfSprite)
    {
        return position;
    }

};

 

Thanks


Struggling to change render order of lists of objects (XNA)

25 January 2013 - 12:54 PM

Hi all.

 

I am making a driving game where the object is to run over zombies who are walking in the road, in front of you. The view is a perspective one and you are driving forward so lots of stuff on the road and around it coming down the screen and being scaled up in size.

 

I have two C# lists at the moment; one containing zombies and the other debris which appears in the road. I wanted to get the render order right so that when the zombie is higher up, than a debris object it would be rendered behind the debris and vise versa. If it was just two separate objects, this would be easier - I would use the Y pos value to determine which to draw to the screen first. However, I need to compare every zombie on the screen to every piece of debris.

 

So I constructed the following nests of loops and if statements to try and get this correct render order.

 

            if (debrisList.Count != 0 && zombies.Count != 0)  // If both types of sprite are on screen
            {
                foreach (Zombie zom in zombies)
                {
                    foreach (Debris deb in debrisList)
                    {
                        if (zom.ReturnPosition().Y >= deb.ReturnPos().Y)
                        {
                            deb.Draw(this.spriteBatch);
                            zom.Draw(this.spriteBatch);
                        }
                    }
                    foreach(Debris deb in debrisList)
                    {
                        if (zom.ReturnPosition().Y <= deb.ReturnPos().Y)
                        {
                            zom.Draw(this.spriteBatch);
                            deb.Draw(this.spriteBatch);
                        }
                    }
                }
            }
            else
            {
                foreach (Zombie zom in zombies)
                {
                    zom.Draw(this.spriteBatch);
                }
                foreach (Debris deb in debrisList)
                {
                    deb.Draw(this.spriteBatch);
                }
            }

 

What the code is supposed to do (in my mind) is first of all check if both lists are not empty. If one is empty then it draws to screen as normal and no consideration is given to the order. If both lists are not empty what should be going on is that the zombies list is iterated through and for each zombie, I compare its Y position to the Y position of each debris item and render accordingly.

 

However, the zombie is always rendered on top of the debris.

 

Hopefully I have explained what I am trying to do and hopefully someone can help me. This has been driving me crazy for a few hours now!

 

Thanks


Sprite fails to draw when calling my draw() method

10 January 2013 - 10:57 AM

Hi All,

 

I am trying to draw a sprite to the screen. So far, when making small games I have loaded textures and drawn them in a very un-OO way and just used OO techniques for the game mechanics. Now, I wanted to load the textures in to the object and draw them from their own method too. I wrote what I thought would work but the sprite is not being drawn to the screen. The background get drawn fine and there are no compile or runtime errors. Can someone spot what I am doing wrong please?

 

Headers.h

#ifndef HEADERS_H
#define HEADERS_H
#include <windows.h>
#include <windowsx.h>
#include <vector>
#include <d3d9.h>
#include <d3dx9.h>
#include <string>
#pragma comment (lib, "d3d9.lib")
#pragma comment (lib, "d3dx9.lib")
#define SCREEN_WIDTH  1024
#define SCREEN_HEIGHT 768
LPDIRECT3D9 d3d;                 // Pointer to Direct3D interface
LPDIRECT3DDEVICE9 d3dDevice;     // Pointer to the device class
LPD3DXSPRITE d3dSprite;          // Pointer to Direct3D Sprite interface
#endif

 

Customer.h

#include "Headers.h";
class Customer{
private:
    LPDIRECT3DTEXTURE9 textureT;
    D3DXVECTOR3 position;
    D3DXVECTOR3 center;
public:
    Customer()
    {
        D3DXCreateTextureFromFileEx(d3dDevice, "man.png", D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,
        D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), NULL, NULL, &textureT);
        D3DXVECTOR3 position (10.0f, 10.0f, 0.0f);
        D3DXVECTOR3 center (0.0f, 0.0f, 0.0f);
    }
    void Draw()
    {
        d3dSprite->Draw(textureT, NULL, &center, &position, D3DCOLOR_XRGB(255, 255, 255));
    }
};

 

Main.cpp

/**********************************************
*
* Title: DirectX 9.0 Standard Fullscreen Template
* Author: Chris Ramsey
* Created: November 2012
*
* This program is a standard template for a full screen
* directX 9.0 application.
*
* Any code from here can be used freely by
* anyone for any reason.
*
***********************************************/
#include "Headers.h."
#include "Customer.h"
Customer customer1;
// DirectX 3D Vectors used for sprite positions
D3DXVECTOR3 center, backgroundP;
// Textures
LPDIRECT3DTEXTURE9 backgroundT;
void initDirectX(HWND hWnd);       // Initializes Direct3D Graphics
void render();                     // Render graphics
void cleanUp();                    // Cleans everything up and releases memory
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    HWND hWnd;                                          // The handle to the window function
    WNDCLASSEX window;                                  // Pointer to window struct
    ZeroMemory(&window, sizeof(WNDCLASSEX));            // Clears window class so we can use it
    window.cbSize = sizeof(WNDCLASSEX);                 // Size of window
    window.style = CS_HREDRAW | CS_VREDRAW;             // Redraws the entire window if a movement or size adjustment changes the height of the client area.
    window.lpfnWndProc = WindowProc;                    // Pointer to the window procedure
    window.hInstance = hInstance;                       // Handle to current instance
    window.hCursor = LoadCursor(NULL, IDC_ARROW);       // We'll stick with the normal cursor here
    window.lpszClassName = "Window";                    // Gives the class a name
    RegisterClassEx(&window);                           // Registers the window class
    hWnd = CreateWindowEx(NULL,
        "Window",                     // Name of the class
        "Space Game",                 // Title of the window
        WS_EX_TOPMOST | WS_POPUP,     // Fullscreen
        0, 0,                         // Position of window (0,0 for fullscreen)
        SCREEN_WIDTH, SCREEN_HEIGHT,  // Screen resolution (Uses global declaration)
        NULL,                         // Parent window (None)
        NULL,                         // Menus (None)
        hInstance,                    // Application handle
        NULL);                        // Set to NULL as we aren't using more than 1 window
    ShowWindow(hWnd, nCmdShow);                         // Display window
    initDirectX(hWnd);                                  // Initialises the directX graphics
    MSG msg = {0};                                      // msg holds the Windows events message queue
    /************************************** Main game loop *************************************************/
    while(TRUE)                                         // Main game loop
    {
        if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))     // If messages are waiting
        {
            TranslateMessage(&msg);                      // Translates the keystroke messages into the correct format
            DispatchMessage(&msg);                       // Sends message to the windowsProc function
            if(msg.message == WM_QUIT)                   // If the message was a quit message
                break;                                   // Breaks out of main game loop
        }
        else                  
        {
            render();
        }
    }
    /*******************************************************************************************************/
    // We are out of the main game loop (Due to a WM_QUIT signal)
    cleanUp();                                          // Do some housekeeping before quitting
    return msg.wParam;                                  // Return the WM_QUIT message to Windows. End of program
}
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)                                     // Sorts through messages
    {
    case WM_DESTROY:                                // When window has been closed
        {
            PostQuitMessage(0);                     // Closes the application
            return 0;  
        }
        break;
    }
    return DefWindowProc (hWnd,                         // Returns any messages the switch statement didn't pick up
        message,
        wParam,
        lParam);
}
void initDirectX(HWND hWnd)
{
    d3d = Direct3DCreate9(D3D_SDK_VERSION);              // Create DirectX9 interface
    D3DPRESENT_PARAMETERS d3dParameters;                 // Pointer to DirectX9 parameters
    ZeroMemory(&d3dParameters, sizeof(d3dParameters));   // Clears the structure so we can use it
    d3dParameters.Windowed = FALSE;                      // Fullscreen
    d3dParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;    // Get rid of old framess
    d3dParameters.hDeviceWindow = hWnd;                  // Sets the window to be used by Direct3D
    d3dParameters.BackBufferFormat = D3DFMT_X8R8G8B8;    // Sets the back buffer format to 32-bit
    d3dParameters.BackBufferWidth = SCREEN_WIDTH;        // Sets the width of the buffer
    d3dParameters.BackBufferHeight = SCREEN_HEIGHT;      // Sets the height of the buffer
    d3d->CreateDevice(D3DADAPTER_DEFAULT,                // Creates a device class
        D3DDEVTYPE_HAL,
        hWnd,
        D3DCREATE_SOFTWARE_VERTEXPROCESSING,
        &d3dParameters,
        &d3dDevice);
    D3DXCreateSprite(d3dDevice, &d3dSprite);
    D3DXVECTOR3 center(0.0f, 0.0f, 0.0f);
    D3DXCreateTextureFromFileEx(d3dDevice, "background2.png", D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,
        D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), NULL, NULL, &backgroundT);
    D3DXVECTOR3 backgroundP(0,0,0);
}
void render()
{
    d3dDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(10, 0, 32), 1.0f, 0);   // Clears the screen to a dark blue
    d3dDevice->BeginScene();                                                         // Begins Direct3D scene
    d3dSprite->Begin(D3DXSPRITE_ALPHABLEND);                                         // Begin sprite drawing
    d3dSprite->Draw(backgroundT, NULL, &center, &backgroundP, D3DCOLOR_XRGB(255, 255, 255));
    customer1.Draw();
    d3dSprite->End();                                                                // End drawing
    d3dDevice->EndScene();                                                           // Ends the Direct3D scene
    d3dDevice->Present(NULL, NULL, NULL, NULL);                                      // Presents the Direct3D scene (Displays to screen)
}
void cleanUp()
{
    d3dDevice->Release();   // Closes the Direct3D device and releases memory
    d3d->Release();         // Closes Direct3D and releases memory
}

 

Thanks


WinSock connect() call appears to hang?

03 December 2012 - 12:04 PM

Hi All,

I am having some problems. I had a basic Server and Client app that would connect to each other. I have been doing some work to try and get the client to pass structs to the server (but that is not the issue here). I am certain I have not changed anything but for some reason, the client hangs. I have debugged to the point where it is calling the connect() function but I cannot go any deeper. Can anyone spot any problems?

Thanks

Client Code:

#include <WinSock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <string>
#pragma comment(lib, "Ws2_32.lib")
class WinSockClient
{
private:
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
WSADATA wsaData;
SOCKET ConnectSocket;
int recvbuflen;
int exitCode;
char recvbuf[DEFAULT_BUFLEN];
struct addrinfo *result,
	 *ptr,
	 hints;
public:
WinSockClient()
{
  ConnectSocket = INVALID_SOCKET;
  addrinfo *result = NULL,
	 *ptr = NULL;
  exitCode = 0;
  recvbuflen = DEFAULT_BUFLEN;
}
int Startup()
{
  exitCode = WSAStartup(MAKEWORD(2,2), &wsaData);
  if(exitCode != 0)
  {
   printf("WSAStartup failed: %d\n", result);
   return 1;
  }
  ZeroMemory(&hints, sizeof(hints));
  hints.ai_family = AF_UNSPEC;	   //Unspecified (We can be returned IPv4 or IPv6 addresses)
  hints.ai_socktype = SOCK_STREAM;   //We're using a stream socket
  hints.ai_protocol = IPPROTO_TCP;   //We're using the TCP protocol
  exitCode = getaddrinfo("192.168.0.2", DEFAULT_PORT, &hints, &result);
  if (exitCode != 0)
  {
   printf("getaddrinfo failed: %d\n", exitCode);
   WSACleanup();
   return 1;
  }
}
int Create()
{
  ConnectSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);

  ptr=result;
  ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
  ptr->ai_protocol);
  /* Check that socket is valid */
  if (ConnectSocket == INVALID_SOCKET)
  {
   printf("Error at socket(): %ld\n", WSAGetLastError());
   freeaddrinfo(result);
   WSACleanup();
   return 1;
  }
}
int Connect(int timeout)
{
  /* Connect to server. The application will retry if a connection fails
  up until a maximum timeout of 60 second */
  exitCode = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
  int counter = 0;
  while (exitCode == SOCKET_ERROR)
  {
   printf("Unable to connect to server. Retrying.\n");
   counter++;
   Sleep(1000);
   exitCode = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
   if(counter == timeout)
	break;
  }
  if(exitCode == SOCKET_ERROR)
  {
   closesocket(ConnectSocket);
   ConnectSocket = INVALID_SOCKET;
   printf("Unable to connect to server!\n");
   WSACleanup();
   return 1;
  }
  /* Connection has been made - Free no longer needed resources */
  freeaddrinfo(result);
  printf("Connection made!\n");
}
int Send(playerStats stats)
{
  // Send an initial buffer
  exitCode = send(ConnectSocket, (char const *)&stats, sizeof(stats), 0); // My message is sent here (???)
  if (exitCode == SOCKET_ERROR)
  {
   printf("send failed: %d\n", WSAGetLastError());
   closesocket(ConnectSocket);
   WSACleanup();
   return 1;
  }
  printf("Test Message Sent\n");
  //printf("Bytes Sent: %ld\n", exitCode);
}
int Recieve()
{
  int returnCode = 0;
  int messages;
  do
  {
   messages = recv(ConnectSocket, recvbuf, recvbuflen, 0);
   if (messages > 0)
   {
	//printf("Bytes received: %d\n", messages);
	//printf("\n", recvbuf, "\n");
	returnCode = 0;
	messages = 0;
   }
   else if (messages == 0)
   {
	returnCode = 1;
   }
   else
   {
	printf("recv failed: %d\n", WSAGetLastError());
	returnCode = 2;
   }
  } while (messages > 0);
  return returnCode;
}
int ShutdownConnection()
{
  exitCode = shutdown(ConnectSocket, SD_SEND);
  if (exitCode == SOCKET_ERROR)
  {
   printf("shutdown failed: %d\n", WSAGetLastError());
   closesocket(ConnectSocket);
   WSACleanup();
   return 1;
  }
  return 0;
}
};

Main:

struct playerStats
{
int studentNumber;
int levelAchieved;
};
#include "WinSocketClient.h"
WinSockClient wsClient;
playerStats pStats;

int main()
{
int returnCode;

pStats.studentNumber = 542;
pStats.levelAchieved = 2;
wsClient.Startup();
wsClient.Create();
if(wsClient.Connect(60) == -1)
{
  printf("Connection attempt timedout\n");
  wsClient.ShutdownConnection();
  return 0;
}
wsClient.Send(pStats);
while(returnCode = wsClient.Recieve() == 0)
{
  Sleep(500);
  wsClient.Send(pStats);
}
if(returnCode == 1)
{
  printf("Reply not recieved\n");
}
if(returnCode == 2)
{
  printf("RECV error\n");
}
wsClient.ShutdownConnection();
system("PAUSE");
return 0;
}

Changing the Render Order

14 November 2012 - 03:10 PM

Hi folks,

I am making an isometric game in 2D and am having some difficulty in coming up with a solution to my current problem.

If I have lots of little characters (just an example) running around the screen, I want to know what order to render those sprites in. I already know that I can do this simply by knowing each of the characters Y coordinate (If the Y coordinate is lower than one sprite, then it should be rendered in front).

I have already written a sample program that gives the illusion of a ball orbiting around a pole. Trouble is, if I have lots more than just two sprites - for example 20 sprites... it becomes a little more complicated.

I am struggling because obviously, a web of IF statements will not suffice. I would like to know if there is a common method that people may use in this situation? And, lets say for example I was able to get all the objects Y pos and order some kind of virtual Z buffer array that will help me order the rendering, how would I go about this for those objects already contained in a vector (A vector containing 10 generic automated characters for example).

Any thoughts on this? (That is, if I have explained myself correctly). I am using Direct3D 9.0 and C++ although I am sure languages and library's do not really come in to this much.

Thanks

Chris

PARTNERS