wxb8888

When offset of x is 0.1 pixel,D3D Render error

Discussion created by wxb8888 on Jun 16, 2009

Source picture:Column Red(255) Green(255) Blue(255)

offset of x is 0.1 pixel

Render error :Result pixel of TopRight and BottomLeft is different

Souce Code:

//-----------------------------------------------------------------------------
// File: test3.cpp
//
//
//-----------------------------------------------------------------------------
#include
#include
#include
#include
#include

 

//-----------------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------------
LPDIRECT3D9             g_pD3D       = NULL; // Used to create the D3DDevice
LPDIRECT3DDEVICE9       g_pd3dDevice = NULL; // Our rendering device
LPDIRECT3DVERTEXBUFFER9 g_pVB        = NULL; // Buffer to hold vertices
LPDIRECT3DTEXTURE9      g_pTexture   = NULL; // Our texture
LPD3DXEFFECT   g_pEffect  =NULL;
LPD3DXFONT    g_pFont=NULL;

int g_nSceneWidth = 720,g_nSceneHeight = 576;

#define SAFE_RELEASE(p){if(p){(p)->Release();(p)=NULL;}}
#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p);   (p)=NULL; } }


// A structure for our custom vertex type. We added texture coordinates
struct CUSTOMVERTEX
{
    D3DXVECTOR3 position; // The position
    D3DCOLOR    color;    // The color
#ifndef SHOW_HOW_TO_USE_TCI
    FLOAT       tu, tv;   // The texture coordinates
#endif
};

// Our custom FVF, which describes our custom vertex structure
#ifdef SHOW_HOW_TO_USE_TCI
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE)
#else
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
#endif


//-----------------------------------------------------------------------------
// Name: InitD3D()
// Desc: Initializes Direct3D
//-----------------------------------------------------------------------------
HRESULT InitD3D( HWND hWnd )
{
    // Create the D3D object.
    if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
        return E_FAIL;

    // Set up the structure used to create the D3DDevice. Since we are now
    // using more complex geometry, we will create a device with a zbuffer.
    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory( &d3dpp, sizeof(d3dpp) );
    d3dpp.Windowed = TRUE;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
    d3dpp.EnableAutoDepthStencil = TRUE;
    d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
    d3dpp.PresentationInterval=D3DPRESENT_INTERVAL_IMMEDIATE;
 d3dpp.BackBufferWidth = g_nSceneWidth;
 d3dpp.BackBufferHeight = g_nSceneHeight;
    // Create the D3DDevice
    if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                      D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                      &d3dpp, &g_pd3dDevice ) ) )
    {
        return E_FAIL;
    }

    // Turn off culling
    g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );

    // Turn off D3D lighting
    g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );

    // Turn on the zbuffer
    g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );

 LPDIRECT3DSURFACE9 pSurf;
 g_pd3dDevice->GetBackBuffer(0,0,D3DBACKBUFFER_TYPE_MONO,&pSurf);
 D3DSURFACE_DESC desc;
 pSurf->GetDesc(&desc);
 SAFE_RELEASE(pSurf); 

    return S_OK;
}

 

#define GRID 2

//-----------------------------------------------------------------------------
// Name: InitGeometry()
// Desc: Create the textures and vertex buffers
//-----------------------------------------------------------------------------
HRESULT InitGeometry()
{
 HRESULT hr=S_OK;
    // Use D3DX to create a texture from a file based image
 
 g_pd3dDevice->CreateTexture(720,576,1,D3DUSAGE_DYNAMIC,D3DFMT_A8R8G8B8,D3DPOOL_DEFAULT,&g_pTexture,NULL);
 D3DLOCKED_RECT lr;
 g_pTexture->LockRect(0,&lr,NULL,0);
 for(int y = 0;y < 576;y ++)
 {
  DWORD *pCr = (DWORD*)((BYTE*)lr.pBits + lr.Pitch * y);
  for(int x = 0; x < 360 * 2;x ++)
  {
   switch (x % 3)
   {
    /*
   case 0:PCr[x] = 0x00ff00ff;break;
   case 1:PCr[x] = 0xff00ff00;break;
   case 2:PCr[x] = 0xff0000ff;break;
   */
   case 0:PCr[x] = 0xffff0000;break;
   case 1:PCr[x] = 0xff00ff00;break;
   case 2:PCr[x] = 0xff0000ff;break;
   }

  }
 }
 g_pTexture->UnlockRect(0);
 // Create the vertex buffer.
 if( FAILED( g_pd3dDevice->CreateVertexBuffer( GRID*2*sizeof(CUSTOMVERTEX),
  0, 0/*D3DFVF_CUSTOMVERTEX*/,
  D3DPOOL_DEFAULT, &g_pVB, NULL ) ) )
 {
  return E_FAIL;
 }

 // Fill the vertex buffer. We are setting the tu and tv texture
 // coordinates, which range from 0.0 to 1.0
 CUSTOMVERTEX* pVertices;
 if( FAILED( g_pVB->Lock( 0, 0, (void**)&pVertices, 0 ) ) )
  return E_FAIL;
 for( DWORD i=0; i {
  FLOAT theta = (2*D3DX_PI*i)/(GRID-1);
  float x=sinf(theta),y=1.0f,z=cosf(theta);
  x=i*1.0f/(GRID-1)*2.0f-1.0f;
  z=0.0f;
  x *= 0.5f;
  y *= 0.5f;
  pVertices[2*i+0].position = D3DXVECTOR3( x,-y, z );
  pVertices[2*i+0].color    = 0xffffffff;
#ifndef SHOW_HOW_TO_USE_TCI
  pVertices[2*i+0].tu       = ((FLOAT)i)/(GRID-1);
  pVertices[2*i+0].tv       = 1.0f;
#endif

  pVertices[2*i+1].position = D3DXVECTOR3( x, y, z );
  pVertices[2*i+1].color    = 0xff808080;
#ifndef SHOW_HOW_TO_USE_TCI
  pVertices[2*i+1].tu       = ((FLOAT)i)/(GRID-1);
  pVertices[2*i+1].tv       = 0.0f;
#endif
 }
 g_pVB->Unlock();

 ID3DXBuffer* pBuffer;
 //if(FAILED(hr=D3DXCreateEffectFromResource(m_pd3dDevice,NULL,MAKEINTRESOURCE(IDR_FX),
 //    NULL,NULL,/*D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT|D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT*/NULL,NULL,
 //    &m_pEffect,&pBuffer)))

 

 //f:\\user\\shader30test\\//
 if(FAILED(hr=D3DXCreateEffectFromFile(g_pd3dDevice,"test3.fx",
  NULL,NULL,
  /*D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT|D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT*/
  D3DXSHADER_PARTIALPRECISION,
  //NULL,
  NULL,
  &g_pEffect,&pBuffer)))
 {
  if(pBuffer)
  {
   char buffer[1024];
   LPVOID p=pBuffer->GetBufferPointer();
   sprintf_s(buffer,"%s",(LPTSTR)p);
   pBuffer->Release(); 
  }
  return hr;
 }
 D3DXCreateFont( g_pd3dDevice, 30, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
  OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
  "Arial", &g_pFont ) ;

 
//  float a = 0.2f;
//  float b = 1.0f;
//  float c = 0.0f;
//  while (1)
//  {
//   c = a + b;
//   b += 1.0f;
//  }
    return S_OK;
}

 


//-----------------------------------------------------------------------------
// Name: Cleanup()
// Desc: Releases all previously initialized objects
//-----------------------------------------------------------------------------
VOID Cleanup()
{
 SAFE_RELEASE(g_pFont);
 SAFE_RELEASE(g_pTexture);
 SAFE_RELEASE(g_pEffect);
 SAFE_RELEASE(g_pVB);
 SAFE_RELEASE(g_pd3dDevice);
 SAFE_RELEASE(g_pD3D);   
}


float fXMove = 0.0f;
//-----------------------------------------------------------------------------
// Name: SetupMatrices()
// Desc: Sets up the world, view, and projection transform matrices.
//-----------------------------------------------------------------------------
VOID SetupMatrices()
{
    // Set up world matrix
    D3DXMATRIXA16 matWorld;
    D3DXMatrixIdentity( &matWorld );
    //D3DXMatrixRotationX( &matWorld, timeGetTime()/1000.0f );
     //matWorld._41 = -0.5f / 720.0f;
  //matWorld._42 = 0.5f / 576.0f;
//  
   matWorld._41 += 0.1f / 720.0f;

 //fXMove += 1e-3;
    // Set up our view matrix. A view matrix can be defined given an eye point,
    // a point to lookat, and a direction for which way is up. Here, we set the
    // eye five units back along the z-axis and up three units, look at the
    // origin, and define "up" to be in the y-direction.
    D3DXVECTOR3 vEyePt( 0.0f, 0.0f,-0.5f/tan(D3DX_PI/8.0f) );
    D3DXVECTOR3 vLookatPt( 0.0f, 0.0f, 0.0f );
    D3DXVECTOR3 vUpVec( 0.0f, 1.0f, 0.0f );
    D3DXMATRIXA16 matView;
    D3DXMatrixLookAtLH( &matView, &vEyePt, &vLookatPt, &vUpVec );
   

    // For the projection matrix, we set up a perspective transform (which
    // transforms geometry from 3D view space to 2D viewport space, with
    // a perspective divide making objects smaller in the distance). To build
    // a perpsective transform, we need the field of view (1/4 pi is common),
    // the aspect ratio, and the near and far clipping planes (which define at
    // what distances geometry should be no longer be rendered).
    D3DXMATRIXA16 matProj;
    D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 1.0f, 0.001f, 1000.0f );
   
 //g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
 //g_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );
 //g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
 g_pEffect->SetMatrix(_T("g_matWorldViewProj"),&(matWorld*matView*matProj));

 D3DXVECTOR3 v(-0.5f,0.5f,0.0f);
 D3DVIEWPORT9 vPort;
 g_pd3dDevice->GetViewport (&vPort);

 D3DXVec3Project(&v,&v,&vPort,&matProj,&matView,&matWorld);

}

 

void ShowText()
{
 LARGE_INTEGER llFre;
 QueryPerformanceFrequency (&llFre);
 static LARGE_INTEGER llLast={0};
 LARGE_INTEGER llCur;
 QueryPerformanceCounter(&llCur);
 static int nFrame=0;
 static TCHAR buffer[100]={0};

 float fTime=(llCur.QuadPart-llLast.QuadPart)*1.0f/llFre.QuadPart;

 if(fTime>1.0f)
 {
  float fFre=nFrame/fTime;
  nFrame=0;
  llLast=llCur;  
  sprintf_s(buffer,"%6.3f\n",fFre);

  OutputDebugString(buffer);
 }
 else
  nFrame++;

 RECT rcTxt;
 SetRect(&rcTxt,0,0,100,50);
 g_pFont->DrawTextA(NULL,buffer,-1,&rcTxt,DT_LEFT,0xffff0000);
}

//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Draws the scene
//-----------------------------------------------------------------------------
VOID Render()
{
    // Clear the backbuffer and the zbuffer
    g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,
                         D3DCOLOR_XRGB(0,0,0), 1.0f, 0 );

    // Begin the scene
    if( SUCCEEDED( g_pd3dDevice->BeginScene() ) )
    {
        // Setup the world, view, and projection matrices
        SetupMatrices();       

        // Render the vertex buffer contents
        g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof(CUSTOMVERTEX) );
        g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );

  g_pEffect->SetTechnique(_T("RenderScene"));
  g_pEffect->SetTexture(_T("g_txScene"),g_pTexture);
  UINT cPass,uPass;
  g_pEffect->Begin(&cPass,0);
  for(uPass=0;uPass  {
   g_pEffect->BeginPass(uPass);
   g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2*GRID-2 );
   g_pEffect->EndPass();
  }
  g_pEffect->End();

  //ShowText();
        // End the scene
        g_pd3dDevice->EndScene();
    }

  LPDIRECT3DSURFACE9 pSurf;
  g_pd3dDevice->GetBackBuffer(0,0,D3DBACKBUFFER_TYPE_MONO,&pSurf);
  D3DXSaveSurfaceToFile("c:\\temp\\22.bmp",D3DXIFF_BMP,pSurf,NULL,NULL);
  SAFE_RELEASE(pSurf); 

    // Present the backbuffer contents to the display
    g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
}

 


//-----------------------------------------------------------------------------
// Name: MsgProc()
// Desc: The window's message handler
//-----------------------------------------------------------------------------
LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch( msg )
    {
        case WM_DESTROY:
            Cleanup();
            PostQuitMessage( 0 );
            return 0;
    }

    return DefWindowProc( hWnd, msg, wParam, lParam );
}

 


//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: The application's entry point
//-----------------------------------------------------------------------------
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT )
{
    // Register the window class
    WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L,
                      GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
                      "D3D Tutorial", NULL };
    RegisterClassEx( &wc );

 RECT rc = { 0, 0, g_nSceneWidth, g_nSceneHeight };
 AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );

    // Create the application's window
    HWND hWnd = CreateWindow( "D3D Tutorial", "test3",
                              WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top,
                              GetDesktopWindow(), NULL, wc.hInstance, NULL );

    // Initialize Direct3D
    if( SUCCEEDED( InitD3D( hWnd ) ) )
    {
        // Create the scene geometry
        if( SUCCEEDED( InitGeometry() ) )
        {
            // Show the window
            ShowWindow( hWnd, SW_SHOWDEFAULT );
            UpdateWindow( hWnd );

            // Enter the message loop
            MSG msg;
            ZeroMemory( &msg, sizeof(msg) );
            while( msg.message!=WM_QUIT )
            {
                if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
                {
                    TranslateMessage( &msg );
                    DispatchMessage( &msg );
                }
                else
                    Render();
            }
        }
    }

    UnregisterClass( "D3D Tutorial", wc.hInstance );
    return 0;
}

/* test3.fx*/

float4x4 g_matWorldViewProj;

texture g_txScene;

sampler g_samBack=
sampler_state

 Texture=;
 MinFilter=Linear;
 MagFilter=Linear;
 MipFilter=Linear;
 AddressU=Wrap;
 AddressV=Clamp;
};


void VertScene(float4 vPos:POSITION,
    float3 vDiffues:COLOR0,
    float2 vTex:TEXCOORD0,    
    out float4 oPos:POSITION,    
    out float2 oTex:TEXCOORD0)

 oPos=mul(vPos,g_matWorldViewProj);
 oTex=vTex + 0.50f / float2(720.0f,576.0f);  

float4 PixScene(float2 Tex:TEXCOORD0):COLOR0

  
 float4 fColor=(float4)0;  
  
 fColor=tex2D(g_samBack,Tex);  
   return fColor;
}

technique RenderScene
{
 PASS P0
 {
  VertexShader=compile vs_3_0 VertScene();
  PixelShader=compile  ps_3_0 PixScene();
  CullMode=None;
  
 }
}

Outcomes