社区
游戏开发
帖子详情
在D3D里面如何使用Render to Texture?
ChinaShrimp
2004-10-20 05:31:25
我知道在OpenGL可以生成一个float类型的pbuffer,然后将可以渲染到里面去,但是操作起来很复杂。我想D3D里肯定也能实现Render to Texture,而且据说用起来很方便,我想请问一下如何使用?另外我还想问的就是在D3D里面能否设置pbuffer中的数据类型(例如浮点型)?多谢!
...全文
117
3
打赏
收藏
在D3D里面如何使用Render to Texture?
我知道在OpenGL可以生成一个float类型的pbuffer,然后将可以渲染到里面去,但是操作起来很复杂。我想D3D里肯定也能实现Render to Texture,而且据说用起来很方便,我想请问一下如何使用?另外我还想问的就是在D3D里面能否设置pbuffer中的数据类型(例如浮点型)?多谢!
复制链接
扫一扫
分享
转发到动态
举报
写回复
配置赞助广告
用AI写文章
3 条
回复
切换为时间正序
请发表友善的回复…
发表回复
打赏红包
潘李亮
2004-10-24
打赏
举报
回复
SetRenderTarget.把一个纹理当作Surface.
seagate
2004-10-21
打赏
举报
回复
IDirect3DDevice9有个函数是SetRenderTarget。它能实现你要的功能。它有个参数是IDirect3DSurface9,可以作为存放的buffer。数据类型是创建这个surface时自己定的。
lly20000
2004-10-21
打赏
举报
回复
在D3D中可以通过d3dxsavetofile来保存当前的截图
D3DXSaveSurfaceToFile(file_name, D3DXIFF_JPG, frontbuf, NULL, NULL);
d
3d
11
Render
To
Text
ure, RTT
渲染到贴图,
使用
Render
To
Text
ure, RTT, 渲染到纹理的详细代码
D
3D
11_
Render
To2D
Text
ure
D
3D
11_
Render
To2D
Text
ure
D
3D
render
pipeline
This book describes the Direct
3D
graphics pipeline, from presentation of scene data to pixels appearing on the screen. The book is organized sequentially following the data °ow through the pipeline from the application to the image displayed on the monitor. Each major section of the pipeline is treated by a part of the book, with chapters and subsections detailing each discrete stage of the pipeline. This section summarizes the contents of the book. Part I begins with a review of basic concepts used in
3D
computer graphics and their representations in Direct
3D
. The IDirect
3D
9 interface is introduced and device selection is described. The IDirect
3D
Device9 interface is introduced and an overview of device methods and internal state is given. Finally, a basic framework is given for a 2D application. Chapter 1 begins with an overview of the entire book. A review is given of display technology and the important concept of gamma correction. The representation of color in Direct
3D
and the macros for manipulating color values are described. The relevant mathematics of vectors, geometry and matrices are reviewed and summarized. A summary of COM and the IUnknown interface is COM: Component Object Model given. Finally, the coding style conventions followed in this book are presented along with some useful C++ coding techniques. Chapter 2 describes the Direct
3D
object. Every application instantiates this object to select a device from those available. Available devices advertise their location in the Win32 virtual desktop and their capabilities to applications 34 CHAPTER 1. INTRODUCTION through the Direct
3D
object. Selecting a device from those available and exam- ining a device's capabilities are described. Multiple monitor considerations are also discussed. Chapter 3 describes the Direct
3D
device object which provides access to the
render
ing pipeline. The device is the interface an application will use most often and it has a large amount of internal state that controls every stage of the
render
ing pipeline. This chapter provides a high-level overview of the device and its associated internal state. Detailed discussion of the device state appears throughout the rest of the book. Chapter 4 describes the basic architecture of a typical Direct
3D
application. Every
3D
application can use 2D operations for manipulating frame bu®er con- tents directly. An application can run in full-screen or windowed modes and the di®erences are presented here. The handling of Windows messages and a ba- sic display processing loop are presented. At times it may be convenient to use GDI in a Direct
3D
application window and a method for mixing these two Win- dows subsystems is presented. Almost every full-screen application will want to use the cursor management provided by the device. Device color palettes and methods for gamma correction are presented. Part II describes the geometry processing portion of the graphics pipeline. The application delivers scene data to the pipeline in the form of geometric primitives. The pipeline processes the geometric primitives through a series of stages that results in pixels displayed on the monitor. This part describes the start of the pipeline where the processing of geometry takes place. Chapter 5 describes how to construct a scene representing the digital world that is imaged by the imaginary camera of the device. A scene consists of a collection of models drawn in sequence. Models are composed of a collection of graphic primitives. Graphic primitives are composed from streams of vertex and index data de¯ning the shape and appearance of objects in the scene. Vertices and indices are stored in resources created through the device. Chapter 6 covers vertex transformations, vertex blending and user-de¯ned clipping planes. With transformations, primitives can be positioned relative to each other in space. Vertex blending, also called \skinning", allows for smooth mesh interpolation. User-de¯ned clipping planes can be used to provide cut away views of primitives. Chapter 7 covers viewing with a virtual camera and projection onto the viewing plane which is displayed as pixels on the monitor. After modeling, objects are positioned relative to a camera. Objects are then projected from
3D
camera space into the viewing plane for conversion into 2D screen pixels. Chapter 8 describes the lighting of geometric primitives. The lighting model is introduced and the supported shading algorithms and light types are de- scribed. Chapter 9 covers programmable vertex shading. Programmable vertex shaders can process the vertex data streams with custom code, producing a single ver- tex that is used for rasterization. The vertex shading machine architecture and instruction set are presented. Part III covers the rasterization portion of the pipeline where geometry is1.1. OVERVIEW 5 converted to a series of pixels for display on the monitor. Geometric primitives are lit based on the lighting of their environment and their material properties. After light has been applied to a primitive, it is scan converted into pixels for processing into the frame bu®er.
Text
ures can be used to provide detailed surface appearance without extensive geometric modeling. Pixel shaders can be used to provide custom per-pixel appearance processing instead of the ¯xed- function pixel processing provided by the stock pipeline. Finally, the pixels generated from the scan conversion process are incorporated into the
render
target surface by the frame bu®er. Chapter 10 describes the scanline conversion of primitives into pixel frag- ments. Lighting and shading are used to process vertex positions and their associated data into a series of pixel fragments to be processed by the frame bu®er. Chapter 11 describes
text
ures and volumes.
Text
ures provide many e±cient per-pixel e®ects and can be used in a variety of manners. Volumes extend
text
ure images to three dimensions and can be used for a volumetric per-pixel
render
ing e®ects. Chapter 13 describes programmable pixel shaders. Programmable pixel shaders combine
text
ure map information and interpolated vertex information to produce a source pixel fragment. The pixel shading machine architecture and instruction set are presented. Chapter 14 describes how fragments are processed into the frame bu®er. After pixel shading, fragments are processed by the fog, alpha test, depth test, stencil test, alpha blending, dither, and color channel mask stages of the pipeline before being incorporated into the
render
target. A
render
target is presented for display on the monitor and video scan out. Part IV covers the D
3D
X utility library. D
3D
X provides an implementation of common operations used by Direct
3D
client programs. The code in D
3D
X consists entirely of client code and no system components. An application is free to reimplement the operations provided by D
3D
X, if necessary. Chapter 15 introduces D
3D
X and summarizes features not described else- where. Chapter 16 describes the abstract data types provided by D
3D
X. D
3D
X provides support for RGBA color, point, vector, plane, quaternion, and matrix data types. Chapter 17 describes the helper COM objects provided by D
3D
X. D
3D
X provides a matrix stack object to assist in
render
ing frame hierarchies, a font object to assist in the
render
ing of
text
, a sprite object to assist in the
render
ing of 2D images, an object to assist in
render
ing to a surface or an environment map and objects for the
render
ing of special e®ects. Chapter 19 describes the mesh objects provided by D
3D
X. The mesh objects provided by D
3D
X encompass
render
ing of indexed triangle lists as well as progressive meshes, mesh simpli¯cation and skinned meshes. Chapter 21 describes the X ¯le format with the ¯le extension .x. The X ¯le format provides for extensible hierarchical storage of data objects with object instancing.6 CHAPTER 1. INTRODUCTION Part V covers application level considerations. This part of the book de- scribes issues that are important to applications but aren't strictly part of the graphics pipeline. Debugging strategies for applications are presented. Almost all Direct
3D
applications will be concerned with performance; API related per- formance issues are discussed here. Finally, installation and deployment issues for Direct
3D
applications are discussed. Chapter 22 describes debugging strategies for Direct
3D
applications. This includes using the debug run-time for DirectX 9.0c, techniques for debugging full-screen applications and remote debugging. Chapter 23 covers application performance considerations. All real devices have limitations that a®ect performance. A general consideration of how the pipeline state a®ects performance is given. Chapter 24 covers application installation and setup. Appendix A provides a guided tour of the DirectX SDK materials.
StereoIssues
时分法,真正的三维编程,场景渲染 #pragma warning(disable: 4995) #include
#include
#include
// Scenes 场景 #include "Scene.h" #include "StanfordBunnyScene.h" // Include nvstereo, but only for Dx10. #define NO_STEREO_D
3D
9 #include "nvstereo.h" //
Text
render
ing ID
3D
X10Font* gFont10 = NULL; ID
3D
X10Sprite* gSprite10 = NULL; CDXUT
Text
Helper* gTxtHelper = NULL; // our global vector of all our scenes. // Make this global because it's easier to work with DXUT this way const int cNoActiveScene = -1; std::vector
gScenes; int gActiveScene = cNoActiveScene; // A little UI stuff GUI图形用户界面 //CDXUTDialog这个类负责纪录一个对话框的所有属性以及它上面的所有控件信息 //CDXUTDialogResourceManager,这个类保存了所有注册过的对话框链表,以及这些对话框共享的资源 //CDXUTElement 这个类保存了需要渲染的元素信息,经常会在渲染函数中用到 //CGrowableArray< TYPE >类 可动态增长的链表类。 CDXUTDialogResourceManager gDialogResourceManager; CDXUTDialog gUI; // Our parameters for the stereo parameters
text
ure.纹理立体参数 nv::stereo::Param
Text
ureManagerD
3D
10* gStereoTexMgr = NULL; ID
3D
10
Text
ure2D* gStereoParam
Text
ure = NULL; ID
3D
10ShaderResourceView* gStereoParam
Text
ureRV = NULL; // Support going back and forth between fullscreen and windowed mode #define IDC_TOGGLEFULLSCREEN 1 #define IDC_MENU 2 // ------------------------------------------------------------------------------------------------ void Clear
Render
Targets(ID
3D
10Device* d
3d
10) { // Clearing every frame is a good practice for SLI. By clearing surfaces, you indicate to the // driver that information from the previous frame is not needed by the other GPU(s) involved // in
render
ing. float ClearColor[4] = { 0.0, 0.0, 0.5, 0.0 }; ID
3D
10
Render
TargetView* pRTV = DXUTGetD
3D
10
Render
TargetView(); d
3d
10->Clear
Render
TargetView(pRTV, ClearColor); ID
3D
10DepthStencilView* pDSV = DXUTGetD
3D
10DepthStencilView(); d
3d
10->ClearDepthStencilView(pDSV, D
3D
10_CLEAR_DEPTH, 1.0, 0); } // ------------------------------------------------------------------------------------------------ void
Render
World(ID
3D
10Device* d
3d
10, double fTime, float fElapsedTime) { // Give the active scene a shot at
render
ing the world. gScenes[gActiveScene]->
Render
(d
3d
10); } // ------------------------------------------------------------------------------------------------ void
Render
Text
() { //
Render
common
text
, then give the active scene a chance to display
text
information // about itself. gTxtHelper->Begin(); gTxtHelper->SetInsertionPos(8, 8); gTxtHelper->SetForegroundColor(D
3D
XCOLOR(1.0f, 1.0f, 0.0f, 1.0f)); gTxtHelper->Draw
Text
Line(L""); gTxtHelper->Draw
Text
Line(L""); gTxtHelper->Draw
Text
Line(L""); gTxtHelper->Draw
Text
Line(DXUTGetFrameStats(true)); gTxtHelper->Draw
Text
Line(DXUTGetDeviceStats()); bool stereoActive = gStereoTexMgr->IsStereoActive(); if (stereoActive) { gTxtHelper->Draw
Text
Line(L"Stereo Active"); } else { gTxtHelper->SetForegroundColor(D
3D
XCOLOR(1.0f, 0.2f, 0.2f, 1.0f)); gTxtHelper->Draw
Text
Line(L"Stereo is currently disabled--you should see no differences between techniques."); gTxtHelper->SetForegroundColor(D
3D
XCOLOR(1.0f, 0.5f, 0.0f, 1.0f)); } gScenes[gActiveScene]->
Render
Text
(gTxtHelper, stereoActive); gTxtHelper->End(); } // ------------------------------------------------------------------------------------------------ void
Render
Cursor(ID
3D
10Device* d
3d
10) { // Cursor
render
ing is handled by the active scene. // Cursors need a bit of stereo love, so the scenes handle that. gScenes[gActiveScene]->
Render
Cursor(d
3d
10); } // ------------------------------------------------------------------------------------------------ void
Render
HUD(ID
3D
10Device* d
3d
10, double fTime, float fElapsedTime) {
Render
Text
(); gUI.On
Render
( fElapsedTime ); //
Render
the cursor last for the obvious reason that we want it to appear above everything // else
Render
Cursor(d
3d
10); } // ------------------------------------------------------------------------------------------------ HRESULT CreateStereoParam
Text
ureAndView(ID
3D
10Device* d
3d
10) { // This function creates a
text
ure that is suitable to be stereoized by the driver. // Note that the parameters primarily come from nvstereo.h using nv::stereo::Param
Text
ureManagerD
3D
10; HRESULT hr = D
3D
_OK; D
3D
10_
TEXT
URE2D_DESC desc; desc.Width = Param
Text
ureManagerD
3D
10::Parms::StereoTexWidth; desc.Height = Param
Text
ureManagerD
3D
10::Parms::StereoTexHeight; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = Param
Text
ureManagerD
3D
10::Parms::StereoTexFormat; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.Usage = D
3D
10_USAGE_DYNAMIC; desc.BindFlags = D
3D
10_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = D
3D
10_CPU_ACCESS_WRITE; desc.MiscFlags = 0; V_RETURN(d
3d
10->Create
Text
ure2D(&desc;, NULL, &gStereoParam
Text
ure;)); // Since we need to bind the
text
ure to a shader input, we also need a resource view. D
3D
10_SHADER_RESOURCE_VIEW_DESC descRV; descRV.Format = desc.Format; descRV.ViewDimension = D
3D
10_SRV_DIMENSION_
TEXT
URE2D; descRV.
Text
ure2D.MipLevels = 1; descRV.
Text
ure2D.MostDetailedMip = 0; descRV.
Text
ure2DArray.MostDetailedMip = 0; descRV.
Text
ure2DArray.MipLevels = 1; descRV.
Text
ure2DArray.FirstArraySlice = 0; descRV.
Text
ure2DArray.ArraySize = desc.ArraySize; V_RETURN(d
3d
10->CreateShaderResourceView(gStereoParam
Text
ure, &descRV;, &gStereoParam
Text
ureRV;)); return hr; } // ------------------------------------------------------------------------------------------------ bool CALLBACK IsD
3D
10DeviceAcceptable(UINT Adapter, UINT Output, D
3D
10_DRIVER_TYPE DeviceType, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserCon
text
) { // Only accept hardware devices return DeviceType == D
3D
10_DRIVER_TYPE_HARDWARE; } // ------------------------------------------------------------------------------------------------ HRESULT CALLBACK OnD
3D
10CreateDevice(ID
3D
10Device* d
3d
10, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserCon
text
) { HRESULT hr = D
3D
_OK; V_RETURN(gDialogResourceManager.OnD
3D
10CreateDevice(d
3d
10)); V_RETURN(D
3D
X10CreateFont(d
3d
10, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Verdana", &gFont10;)); V_RETURN(D
3D
X10CreateSprite(d
3d
10, 512, &gSprite10;)); gTxtHelper = new CDXUT
Text
Helper(NULL, NULL, gFont10, gSprite10, 15); // Create our stereo parameter
text
ure V_RETURN(CreateStereoParam
Text
ureAndView(d
3d
10)); // Initialize the stereo
text
ure manager. Note that the Stereo
Text
ureManager was created // before the device. This is important, because NvAPI_Stereo_CreateConfigurationProfileRegistryKey // must be called BEFORE device creation. gStereoTexMgr->Init(d
3d
10); // Give each of our scenes a chance to load their resources. for (std::vector
::iterator it = gScenes.begin(); it != gScenes.end(); ++it) { (*it)->SetStereoParamRV(gStereoParam
Text
ureRV); V_RETURN((*it)->LoadResources(d
3d
10)); } return hr; } // ------------------------------------------------------------------------------------------------ void CALLBACK OnD
3D
10DestroyDevice(void* pUserCon
text
) { // Clean everything up. gDialogResourceManager.OnD
3D
10DestroyDevice(); for (std::vector
::iterator it = gScenes.begin(); it != gScenes.end(); ++it) { (*it)->UnloadResources(); } SAFE_RELEASE(gStereoParam
Text
ureRV); SAFE_RELEASE(gStereoParam
Text
ure); SAFE_DELETE(gStereoTexMgr); SAFE_RELEASE(gFont10); SAFE_RELEASE(gSprite10); SAFE_DELETE(gTxtHelper); } // ------------------------------------------------------------------------------------------------ HRESULT CALLBACK OnD
3D
10ResizedSwapChain(ID
3D
10Device* d
3d
10, IDXGISwapChain *pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserCon
text
) { HRESULT hr = D
3D
_OK; V_RETURN(gDialogResourceManager.OnD
3D
10ResizedSwapChain(d
3d
10, pBackBufferSurfaceDesc)); // All scenes need a chance to handle the resize. for (std::vector
::iterator it = gScenes.begin(); it != gScenes.end(); ++it) { (*it)->OnD
3D
10ResizedSwapChain(d
3d
10, pSwapChain, pBackBufferSurfaceDesc); } gUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 ); gUI.SetSize( 170, 170 ); return hr; } // ------------------------------------------------------------------------------------------------ void CALLBACK
Render
(ID
3D
10Device* d
3d
10, double fTime, float fElapsedTime, void* pUserCon
text
) { // First, we update our stereo
text
ure gStereoTexMgr->UpdateStereo
Text
ure(d
3d
10, gStereoParam
Text
ure, false); // Then, we tell the scene what the current convergence depth is. Cursor
render
ing // uses this information to cause the cursor to draw at screen depth if the cursor // isn't currently over an object in the scene. gScenes[gActiveScene]->SetConvergenceDepth(gStereoTexMgr->GetConvergenceDepth()); // Then, clear our
render
targets,
render
the world and finish with the hud. Clear
Render
Targets(d
3d
10);
Render
World(d
3d
10, fTime, fElapsedTime);
Render
HUD(d
3d
10, fTime, fElapsedTime); } // ------------------------------------------------------------------------------------------------ void CALLBACK OnD
3D
10ReleasingSwapChain(void* pUserCon
text
) { gDialogResourceManager.OnD
3D
10ReleasingSwapChain(); } // ------------------------------------------------------------------------------------------------ bool CALLBACK ModifyDeviceSettings(DXUTDeviceSettings* pDeviceSettings, void* pUserCon
text
) { if (pDeviceSettings->ver == DXUT_D
3D
10_DEVICE) { #if _DEBUG // Set debug if debugging. In debug, run aliased mode because // otherwise DXUT deletes a target while bound, causing many, many // spew messages. pDeviceSettings->d
3d
10.CreateFlags |= D
3D
10_CREATE_DEVICE_DEBUG; pDeviceSettings->d
3d
10.sd.SampleDesc.Count = 1; #else // I like AA, so turn it on here. pDeviceSettings->d
3d
10.sd.SampleDesc.Count = 4; #endif pDeviceSettings->d
3d
10.sd.SampleDesc.Quality = 0; } return true; } // ------------------------------------------------------------------------------------------------ LRESULT CALLBACK MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserCon
text
) { // WM_MOUSEMOVE needs to make it to the active scene to draw the cursor in the right place. *pbNoFurtherProcessing = gDialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam); if( *pbNoFurtherProcessing && uMsg != WM_MOUSEMOVE) return 0; // Again, make sure that WM_MOUSEMOVE makes it to the active scene, otherwise the mouse will // freeze when it's over our GUI elements, making it significantly less useful. *pbNoFurtherProcessing = gUI.MsgProc(hWnd, uMsg, wParam, lParam); if( *pbNoFurtherProcessing && uMsg != WM_MOUSEMOVE) return 0; // Pass all remaining windows messages to camera so it can respond to user input if (gActiveScene != cNoActiveScene) { return gScenes[gActiveScene]->HandleMessages(hWnd, uMsg, wParam, lParam); } return 0; } // ------------------------------------------------------------------------------------------------ void CALLBACK Update(double fTime, float fElapsedTime, void* pUserCon
text
) { // Only the active scene gets the update gScenes[gActiveScene]->Update(fTime, fElapsedTime); } // ------------------------------------------------------------------------------------------------ void CALLBACK OnGUIEvent(UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserCon
text
) { switch( nControlID ) { case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break; case IDC_MENU: default: // All other messages need to be given to all scenes, in case they need to handle // them. for (std::vector
::iterator it = gScenes.begin(); it != gScenes.end(); ++it) { (*it)->OnGUIEvent(nEvent, nControlID, pControl, pUserCon
text
); } } } // ------------------------------------------------------------------------------------------------ void InitUI() //UI User Interface 用户界面 { gUI.Init(&gDialogResourceManager;); int y = 10; gUI.SetCallback(OnGUIEvent); gUI.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, y, 125, 22 ); gUI.AddButton(IDC_MENU,L"Menu",-1024,y,125,22); y += 24; int startId = IDC_TOGGLEFULLSCREEN + 1; for (std::vector
::iterator it = gScenes.begin(); it != gScenes.end(); ++it) { (*it)->InitUI(gUI, 35, y, startId); } } // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT) { HRESULT hr; V_RETURN(DXUTSetMediaSearchPath(L"..\\Source\\StereoIssues")); // Set Direct
3D
10 callbacks. This sample won't work with Dx9, so don't bother setting any of // those. 设置 Direct
3D
10回调信号 DXUTSetCallbackD
3D
10DeviceAcceptable(IsD
3D
10DeviceAcceptable); DXUTSetCallbackD
3D
10DeviceCreated(OnD
3D
10CreateDevice); DXUTSetCallbackD
3D
10SwapChainResized(OnD
3D
10ResizedSwapChain); DXUTSetCallbackD
3D
10Frame
Render
(
Render
); DXUTSetCallbackD
3D
10SwapChainReleasing(OnD
3D
10ReleasingSwapChain); DXUTSetCallbackD
3D
10DeviceDestroyed(OnD
3D
10DestroyDevice); // Set the generic callback functions 设置通用的回调函数 DXUTSetCallbackDeviceChanging(ModifyDeviceSettings); DXUTSetCallbackMsgProc(MsgProc); DXUTSetCallbackFrameMove(Update); // We'll deal with our own cursor in fullscreen mode. DXUTSetCursorSettings(false, false); // Needs to be called before any other NVAPI functions, so before device creation is fine. NvAPI_Initialize(); // Param
Text
ureManager must be created before the device to give our settings-loading code a chance to fire. gStereoTexMgr = new nv::stereo::Param
Text
ureManagerD
3D
10; gScenes.push_back(new StanfordBunnyScene); gActiveScene = 0; InitUI(); // UI用户界面 // Initialize DXUT and create the desired Win32 window and Direct
3D
device for the application DXUTInit(true, true); // Stereo is a Vista/Win7 feature for Dx9 and Dx10. One of the restrictions is that it only works // in fullscreen mode, but it's useful to debug and place breakpoints in windowed mode. // In any event, there is a button in the sample to toggle to fullscreen if needed, this only // controls the starting state of the app. bool windowed = false; #ifdef _DEBUG windowed = true; #endif DXUTCreateWindow(L"Stereo Issues"); DXUTCreateDevice(windowed); // Start the
render
loop 开始DXUT主要渲染循环 DXUTMainLoop(); int retval = DXUTGetExitCode(); // Clean everything up DXUTShutdown(retval); // We no longer have an active scene. gActiveScene = cNoActiveScene; // No memory leaks! for (std::vector
::iterator it = gScenes.begin(); it != gScenes.end(); ++it) { SAFE_DELETE(*it); } return retval; }
directx
3d
实例
directx
3d
实例#include #include "d
3d
9.h" #include "d
3d
x9.h" #include "Direct
3D
.h" // Direct
3D
objects IDirect
3D
9 *g_pD
3D
= NULL; IDirect
3D
Device9 *g_pD
3D
Device = NULL; // Sky vertex structure, fvf, vertex buffer, and
text
ure typedef struct { float x, y, z, rhw; float u, v; } sSkyVertex; #define SKYFVF (D
3D
FVF_XYZRHW | D
3D
FVF_TEX1) IDirect
3D
VertexBuffer9 *g_SkyVB = NULL; IDirect
3D
Text
ure9 *g_Sky
Text
ure = NULL; // Land and water meshes D
3D
XMESHCONTAINER_EX *g_WaterMesh = NULL; D
3D
XMESHCONTAINER_EX *g_LandMesh = NULL; // Window class and caption
text
char g_szClass[] = "
Text
ureTransformationClass"; char g_szCaption[] = "
Text
ure Transformation Demo by Jim Adams"; // Function prototypes int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow); long FAR PASCAL WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); void Matrix4x4To3x3(D
3D
XMATRIX *matOut, D
3D
XMATRIX *matIn); BOOL DoInit(HWND hWnd, BOOL Windowed = TRUE); void DoShutdown(); void DoFrame(); int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow) { WNDCLASSEX wcex; MSG Msg; HWND hWnd; // Initialize the COM system CoInitialize(NULL); // Create the window class here and register it wcex.cbSize = sizeof(wcex); wcex.style = CS_CLASSDC; wcex.lpfnWndProc = WindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInst; wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = NULL; wcex.lpszMenuName = NULL; wcex.lpszClassName = g_szClass; wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&wcex)) return FALSE; // Create the main window hWnd = CreateWindow(g_szClass, g_szCaption, WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, 0, 0, 640, 480, NULL, NULL, hInst, NULL); if(!hWnd) return FALSE; ShowWindow(hWnd, SW_NORMAL); UpdateWindow(hWnd); // Call init function and enter message pump if(DoInit(hWnd) == TRUE) { // Start message pump, waiting for user to exit ZeroMemory(&Msg, sizeof(MSG)); while(Msg.message != WM_QUIT) { if(PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&Msg); DispatchMessage(&Msg); } //
Render
a single frame DoFrame(); } } // Call shutdown DoShutdown(); // Unregister the window class UnregisterClass(g_szClass, hInst); // Shut down the COM system CoUninitialize(); return 0; } long FAR PASCAL WindowProc(HWND hWnd, UINT uMsg, \ WPARAM wParam, LPARAM lParam) { // Only handle window destruction messages switch(uMsg) { case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, uMsg, wParam, lParam); } return 0; } BOOL DoInit(HWND hWnd, BOOL Windowed) { // Initialize Direct
3D
InitD
3D
(&g_pD
3D
, &g_pD
3D
Device, hWnd); // Load the land and water meshes LoadMesh(&g_WaterMesh, g_pD
3D
Device, "..\\Data\\Water.x", "..\\Data\\"); LoadMesh(&g_LandMesh, g_pD
3D
Device, "..\\Data\\Land.x", "..\\Data\\"); // Create the sky backdrop sSkyVertex SkyVerts[4] = { { 0.0f, 0.0, 1.0, 1.0f, 0.0f, 0.0f }, { 640.0f, 0.0, 1.0, 1.0f, 1.0f, 0.0f }, { 0.0f, 480.0, 1.0, 1.0f, 0.0f, 1.0f }, { 640.0f, 480.0, 1.0, 1.0f, 1.0f, 1.0f } }; g_pD
3D
Device->CreateVertexBuffer(sizeof(SkyVerts), D
3D
USAGE_WRITEONLY, SKYFVF, D
3D
POOL_DEFAULT, &g_SkyVB, NULL); char *Ptr; g_SkyVB->Lock(0,0, (void**)&Ptr, 0); memcpy(Ptr, SkyVerts, sizeof(SkyVerts)); g_SkyVB->Unlock(); D
3D
XCreate
Text
ureFromFile(g_pD
3D
Device, "..\\Data\\Sky.bmp", &g_Sky
Text
ure); // Setup a light D
3D
LIGHT9 Light; ZeroMemory(&Light, sizeof(Light)); Light.Diffuse.r = Light.Diffuse.g = Light.Diffuse.b = Light.Diffuse.a = 1.0f; Light.Type = D
3D
LIGHT_DIRECTIONAL; D
3D
XVECTOR3 vecLight = D
3D
XVECTOR3(-1.0f, -1.0f, 0.5f); D
3D
XVec3Normalize(&vecLight, &vecLight); Light.Direction = vecLight; g_pD
3D
Device->SetLight(0, &Light); g_pD
3D
Device->LightEnable(0, TRUE); // Start playing a waterfall sound PlaySound("..\\Data\\Waterfall.wav", NULL, SND_ASYNC | SND_LOOP); return TRUE; } void DoShutdown() { // Stop playing an ocean sound PlaySound(NULL, NULL, 0); // Free meshes delete g_WaterMesh; g_WaterMesh = NULL; delete g_LandMesh; g_LandMesh = NULL; // Release sky data ReleaseCOM(g_SkyVB); ReleaseCOM(g_Sky
Text
ure); // Release D
3D
objects ReleaseCOM(g_pD
3D
Device); ReleaseCOM(g_pD
3D
); } void DoFrame() { // Create and set the view transformation D
3D
XMATRIX matView; D
3D
XMatrixLookAtLH(&matView, &D
3D
XVECTOR3(360.0f, -170.0f, -430.0f), &D
3D
XVECTOR3(65.0f, 70.0f, -15.0f), &D
3D
XVECTOR3(0.0f, 1.0f, 0.0f)); g_pD
3D
Device->SetTransform(D
3D
TS_VIEW, &matView); // Clear the device and start drawing the scene g_pD
3D
Device->Clear(NULL, NULL, D
3D
CLEAR_TARGET | D
3D
CLEAR_ZBUFFER, D
3D
COLOR_RGBA(0,0,64,255), 1.0, 0); if(SUCCEEDED(g_pD
3D
Device->BeginScene())) { // Set identity matrix for world transformation D
3D
XMATRIX matWorld; D
3D
XMatrixIdentity(&matWorld); g_pD
3D
Device->SetTransform(D
3D
TS_WORLD, &matWorld); // Draw the sky g_pD
3D
Device->SetFVF(SKYFVF); g_pD
3D
Device->SetStreamSource(0, g_SkyVB, 0, sizeof(sSkyVertex)); g_pD
3D
Device->Set
Text
ure(0, g_Sky
Text
ure); g_pD
3D
Device->DrawPrimitive(D
3D
PT_TRIANGLESTRIP, 0, 2); // Enable lighting g_pD
3D
Device->Set
Render
State(D
3D
RS_LIGHTING, TRUE); // Draw the land meshes DrawMeshes(g_LandMesh); // Setup the
text
ure transformation float TimeFactor = (float)(timeGetTime() / 500.0f); D
3D
XMATRIX mat
Text
ure; D
3D
XMatrixTranslation(&mat
Text
ure, 0.0f, -TimeFactor, 0.0f); Matrix4x4To3x3(&mat
Text
ure, &mat
Text
ure); g_pD
3D
Device->SetTransform(D
3D
TS_
TEXT
URE0, &mat
Text
ure); g_pD
3D
Device->Set
Text
ureStageState(0, D
3D
TSS_
TEXT
URETRANSFORMFLAGS, D
3D
TTFF_COUNT2); // Draw the water (using alpha blending) DrawMeshes(g_WaterMesh); g_pD
3D
Device->Set
Render
State(D
3D
RS_ALPHABLENDENABLE, FALSE); // Disable lighting g_pD
3D
Device->Set
Render
State(D
3D
RS_LIGHTING, FALSE); // Turn off
text
ure transformations g_pD
3D
Device->Set
Text
ureStageState(0, D
3D
TSS_
TEXT
URETRANSFORMFLAGS, D
3D
TTFF_DISABLE); // End the scene g_pD
3D
Device->EndScene(); } // Present the scene to the user g_pD
3D
Device->Present(NULL, NULL, NULL, NULL); } void Matrix4x4To3x3(D
3D
XMATRIX *matOut, D
3D
XMATRIX *matIn) { matOut->_11 = matIn->_11; // Copy over 1st row matOut->_12 = matIn->_12; matOut->_13 = matIn->_13; matOut->_14 = 0.0f; matOut->_21 = matIn->_21; // Copy over 2nd row matOut->_22 = matIn->_22; matOut->_23 = matIn->_23; matOut->_24 = 0.0f; matOut->_31 = matIn->_41; // Copy bottom row matOut->_32 = matIn->_42; // used for translation matOut->_33 = matIn->_43; matOut->_34 = 0.0f; matOut->_41 = 0.0f; // Clear the bottom row matOut->_42 = 0.0f; matOut->_43 = 0.0f; matOut->_44 = 1.0f; }
游戏开发
8,304
社区成员
23,682
社区内容
发帖
与我相关
我的任务
游戏开发
游戏开发相关内容讨论专区
复制链接
扫一扫
分享
社区描述
游戏开发相关内容讨论专区
社区管理员
加入社区
获取链接或二维码
近7日
近30日
至今
加载中
查看更多榜单
社区公告
暂无公告
试试用AI创作助手写篇文章吧
+ 用AI写文章