source: GTP/trunk/App/Demos/Illum/Envmap/Main.cpp @ 843

Revision 843, 30.1 KB checked in by szirmay, 19 years ago (diff)
Line 
1/**
2  \file
3  \brief Performs DirectX initialization via DXUT callback functions. Adds some additional helper functions to
4  \brief support screenshot capturing.
5
6  - Performs DirectX initialization via DXUT callback functions
7
8  - Adds some additional helper functions to support screenshot capturing.
9
10  \author Istvan Lazanyi, TU Budapest
11  \date   2006-04-26
12*/
13
14//--------------------------------------------------------------------------------------
15// Main.cpp:
16// - DirectX initialization
17// - create resources (textures)
18//--------------------------------------------------------------------------------------
19
20#include "dxstdafx.h"
21#include "resource.h"
22#include <math.h>
23#include <stdio.h>
24#include <time.h>
25
26//#define DEBUG_VS   // Uncomment this line to debug vertex shaders
27//#define DEBUG_PS   // Uncomment this line to debug pixel shaders 
28
29#include "Cube.h"
30#include "Mesh.h"
31#include "Parameters.h"
32#include "EnvMap.h"
33
34const int WIDTH = 640;
35const int HEIGHT = 640;
36const int CHARBUFFER_SIZE = 200;
37
38//--------------------------------------------------------------------------------------
39// Global variables
40//--------------------------------------------------------------------------------------
41
42IDirect3DDevice9*                       g_pd3dDevice;
43ID3DXEffect*                            g_pEffect;
44
45CDXUTDialogResourceManager      g_DialogResourceManager;        ///< Manager for shared resources of dialogs
46CD3DSettingsDlg                         g_SettingsDlg;                          ///< Device settings dialog
47CDXUTDialog                                     g_HUD;                                          ///< Dialog for sample specific controls
48
49ID3DXFont*                                      g_pFont;                                        ///< Font for drawing text
50ID3DXSprite*                            g_pTextSprite;                          ///< Sprite for batching draw text calls
51
52IDirect3DSurface9*                      g_pSaveSurface;                         ///< surface for screenshot capturing
53bool                                            bSavingScreenshot = false;      ///< boolean for screenshot capturing
54int                                                     counter = 0;                            ///< counter for screenshots (see GenerateNewFileName())
55
56HRESULT hr;
57
58EnvMap* envmapRenderer = new EnvMap();  ///< problem-specific stuff
59Parameters pp;                                                  ///< managing parameters of the algorithm
60
61CModelViewerCamera camera;                              ///< camera
62
63
64//--------------------------------------------------------------------------------------
65// Forward declarations (CALLBACK)
66//--------------------------------------------------------------------------------------
67bool    CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext );
68bool    CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, const D3DCAPS9* pCaps, void* pUserContext );
69HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* g_pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
70HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* g_pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
71void    CALLBACK OnFrameMove( IDirect3DDevice9* g_pd3dDevice, double fTime, float fElapsedTime, void* pUserContext );
72void    CALLBACK OnFrameRender( IDirect3DDevice9* g_pd3dDevice, double fTime, float fElapsedTime, void* pUserContext );
73LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext );
74void    CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext );
75void    CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext );
76void    CALLBACK OnLostDevice( void* pUserContext );
77void    CALLBACK OnDestroyDevice( void* pUserContext );
78void    InitParams();
79void    RenderText();
80
81//--------------------------------------------------------------------------------------
82// Forward declarations
83//--------------------------------------------------------------------------------------
84
85void SaveCameraPosition( char* fileName );
86void LoadCameraPosition( char* fileName );
87int GenerateNewFileName( int& counter );
88
89//--------------------------------------------------------------------------------------
90/// \brief Entry point to the program.
91///
92/// Initializes everything and goes into a message processing loop. Idle time is used to render the scene.
93//--------------------------------------------------------------------------------------
94
95INT WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
96{
97    // Enable run-time memory check for debug builds.
98#if defined(DEBUG) | defined(_DEBUG)
99    _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
100#endif
101
102    DXUTSetCallbackDeviceCreated( OnCreateDevice );
103    DXUTSetCallbackDeviceReset( OnResetDevice );
104    DXUTSetCallbackDeviceLost( OnLostDevice );
105    DXUTSetCallbackDeviceDestroyed( OnDestroyDevice );
106    DXUTSetCallbackMsgProc( MsgProc );
107    DXUTSetCallbackKeyboard( KeyboardProc );
108    DXUTSetCallbackFrameRender( OnFrameRender );
109    DXUTSetCallbackFrameMove( OnFrameMove );
110
111        InitParams();
112
113        // Show the cursor and clip it when in full screen
114    DXUTSetCursorSettings( true, true );
115
116        DXUTInit( true, true, true ); // Parse the command line, handle the default hotkeys, and show msgboxes
117    DXUTCreateWindow( L"Environment Mapping Demo" );
118    DXUTCreateDevice( D3DADAPTER_DEFAULT, true, WIDTH, HEIGHT, IsDeviceAcceptable, ModifyDeviceSettings );
119
120        camera.SetButtonMasks( 0, MOUSE_WHEEL, MOUSE_LEFT_BUTTON );
121
122    DXUTMainLoop();
123
124    return DXUTGetExitCode();
125}
126
127/// \brief DXUT callback (called by the framework in case of GUI events).
128void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext )
129{
130        pp.UpdateFromHUD( nControlID );
131}
132
133void OnLoad() {
134        LoadCameraPosition( ".matrix" );
135}
136
137void OnSave() {
138        SaveCameraPosition( ".matrix" );
139        bSavingScreenshot = true;
140}
141
142void OnReset() {}
143
144float Exponent(float f) {
145        return 0.01f * pow(50.0f, 2*f);
146}
147
148void OnChangeCubeMap() {
149        //bool bEnable = !pp.Get( bUseIrradianceMap ) && !pp.Get( bCubeMapFromFile ) ;
150        //pp.SetEnabled( bUseImpostors, bEnable );
151
152        envmapRenderer->InvalidateCubeMap();
153}
154
155void OnChangeShininess() {
156
157        envmapRenderer->InvalidateShininess();
158}
159
160//--------------------------------------------------------------------------------------
161/// \brief Defines application-specific parameters and creates GUI controls (sliders, checkboxes) for them.
162///
163/// Finally, loads initial values for the parameters from file called <b>.params0</b> (Reset).
164//--------------------------------------------------------------------------------------
165void InitParams()
166{
167        g_SettingsDlg.Init( &g_DialogResourceManager );
168        g_HUD.Init( &g_DialogResourceManager );
169        g_HUD.SetCallback( OnGUIEvent );        // Event handling
170
171        //pp.Setup( &g_HUD );
172        pp.Setup( &g_HUD, OnReset, OnSave, OnLoad );    // you can add callbacks to these actions
173
174        //typedef enum { bShowHelp, bUseImpostors, LAST_BOOL } bool_t;
175        //typedef enum { iShowCubeMap, sFresnel, refractionIndex, /*iLoadedCenterObjectMeshID,LAST_NUMBER } number_t;
176
177        pp.Add( bShowHelp, "Help [F1]", VK_F1 );                                // checkboxes
178        pp.Add( bCubeMapFromFile, "CubeMapFrom[F]ile", 'F', OnChangeCubeMap );
179        pp.Add( bAutoGenCubeMap, "[A]utoGenCubeMap", 'A' );
180        //pp.Add( bLocalize, "L[O]CALIZE LOOKUPS", 'O' );
181        //pp.Add( bUseCosTexture, "[G]eometric factor with texture lookup", 'O' /*, OnChangeCubeMap*/ );
182       
183        pp.Add( iWhichMethod, "WhichMethod [TAB,Q]", 4, VK_TAB, 'Q', noconvert, OnChangeCubeMap );      // sliders
184        pp.Add( iWhichMetal, "WhichMetal [M]", 4, 'M' );        // sliders
185        pp.Add( iShowCubeMap, "ShowCubeMap [C]", 3, 'C' );      // sliders
186        pp.Add( sFresnel, "Fresnel [W,E]", 100, 'W', 'E' );
187        pp.Add( refractionIndex, "RefractionIndex [I,O]", 100, 'I', 'O' );
188        pp.Add( fIntensity, "Intensity [+,-]", 100, VK_SUBTRACT, VK_ADD, Exponent );
189        pp.Add( iShininess, "shininess [/,*]", 30, VK_DIVIDE, VK_MULTIPLY, noconvert, OnChangeShininess );
190
191        //pp.SetEnabled( bUseImpostors, false );
192        //pp.SetEnabled( sFresnel, false );
193
194        pp.UpdateFromHUD( IDC_RESET_BUTTON );   // do a reset
195}
196
197//--------------------------------------------------------------------------------------
198/// \brief DXUT callback (Rejects any devices that aren't acceptable by returning false)
199///
200/// DXUT callback. Rejects any devices that aren't acceptable by returning false.
201//--------------------------------------------------------------------------------------
202bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat,
203                                  D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext )
204{
205    // Skip backbuffer formats that don't support alpha blending
206    IDirect3D9* pD3D = DXUTGetD3DObject();
207    if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType,
208                    AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
209                    D3DRTYPE_TEXTURE, BackBufferFormat ) ) )
210        return false;
211
212    return true;
213}
214
215//--------------------------------------------------------------------------------------
216/// \brief DXUT callback (Before a device is created, modifies the device settings as needed)
217//--------------------------------------------------------------------------------------
218bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, const D3DCAPS9* pCaps, void* pUserContext )
219{
220        // VSync off
221        pDeviceSettings->pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
222
223    // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
224    // then switch to SWVP.
225    if( (pCaps->DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) == 0 ||
226         pCaps->VertexShaderVersion < D3DVS_VERSION(1,1) )
227                pDeviceSettings->BehaviorFlags = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
228    else
229                pDeviceSettings->BehaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING;
230
231    // This application is designed to work on a pure device by not using
232    // IDirect3D9::Get*() methods, so create a pure device if supported and using HWVP.
233    if ((pCaps->DevCaps & D3DDEVCAPS_PUREDEVICE) != 0 &&
234        (pDeviceSettings->BehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING) != 0 )
235        pDeviceSettings->BehaviorFlags |= D3DCREATE_PUREDEVICE;
236
237    // Debugging vertex shaders requires either REF or software vertex processing
238    // and debugging pixel shaders requires REF. 
239#ifdef DEBUG_VS
240    if( pDeviceSettings->DeviceType != D3DDEVTYPE_REF )
241    {
242        pDeviceSettings->BehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING;
243        pDeviceSettings->BehaviorFlags &= ~D3DCREATE_PUREDEVICE;                           
244        pDeviceSettings->BehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
245    }
246#endif
247#ifdef DEBUG_PS
248    pDeviceSettings->DeviceType = D3DDEVTYPE_REF;
249#endif
250
251        // For the first device created if its a REF device, optionally display a warning dialog box
252    static bool s_bFirstTime = true;
253    if( s_bFirstTime )
254    {
255        s_bFirstTime = false;
256        if( pDeviceSettings->DeviceType == D3DDEVTYPE_REF )
257            DXUTDisplaySwitchingToREFWarning();
258    }
259        return true;
260}
261
262//--------------------------------------------------------------------------------------
263/// @brief DXUT callback (You should create any D3DPOOL_MANAGED resources here)
264///
265/// Compiles the effect file (EnvMap.fx) and displays error message if compilation fails.
266/// Finally, forwards call to EnvMap::OnCreateDevice.
267//--------------------------------------------------------------------------------------
268HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
269{
270        ::g_pd3dDevice = pd3dDevice;
271
272        HRESULT hr;
273
274    V_RETURN( g_DialogResourceManager.OnCreateDevice( g_pd3dDevice ) );
275    V_RETURN( g_SettingsDlg.OnCreateDevice( g_pd3dDevice ) );
276
277    // Initialize the font
278    V_RETURN( D3DXCreateFont( g_pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
279                         OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
280                         L"Arial", &g_pFont ) );
281
282       
283        // ----------- fx compilation options -----------
284
285        LPCWSTR fileName = L"EnvMap.fx";
286
287        DWORD dwShaderFlags = 0;
288    #ifdef DEBUG_VS
289        dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
290    #endif
291    #ifdef DEBUG_PS
292        dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
293    #endif
294
295        dwShaderFlags |= D3DXSHADER_SKIPOPTIMIZATION;
296
297        // ----------- compiling fx file -----------
298
299        long clock1 = clock();
300
301        ID3DXBuffer* errBuff;   // buffer for error message
302
303        if (FAILED(hr = D3DXCreateEffectFromFile( g_pd3dDevice, fileName, NULL, NULL, dwShaderFlags,
304                                        NULL, &g_pEffect, &errBuff )))  // if compilation error occurs
305        {
306                int BufSize = errBuff->GetBufferSize();
307
308                wchar_t* wbuf = new wchar_t[BufSize];
309                mbstowcs( wbuf, (const char*)errBuff->GetBufferPointer(), BufSize );
310                MessageBox(NULL, wbuf, L".fx Compilation Error", MB_ICONERROR);         // error message
311
312                delete wbuf;
313                exit(-1);
314        }
315
316        long clock2 = clock();
317        float tb = (float)(clock2-clock1)/CLOCKS_PER_SEC;
318
319        wchar_t wbuf[100];
320        swprintf( wbuf, L"Compilation took %f sec", tb );
321    //MessageBox(NULL, wbuf, L"Info", MB_ICONINFORMATION);
322
323        envmapRenderer->OnCreateDevice( g_pd3dDevice, g_pEffect );
324
325        float initialEyeDist = 6.82;
326        D3DXVECTOR3 vecEye(0, 0, -initialEyeDist);
327        D3DXVECTOR3 vecAt (0.0f, 0.0f, -0.0f);
328        camera.SetViewParams( &vecEye, &vecAt );
329
330        return S_OK;
331}
332
333//--------------------------------------------------------------------------------------
334/// \brief DXUT callback (You should release resources created in the OnCreateDevice callback here)
335///
336/// Forwards call to EnvMap::OnDestroyDevice.
337//--------------------------------------------------------------------------------------
338void CALLBACK OnDestroyDevice( void* pUserContext )
339{
340    g_DialogResourceManager.OnDestroyDevice();
341    g_SettingsDlg.OnDestroyDevice();
342
343    SAFE_RELEASE(g_pEffect);
344    SAFE_RELEASE(g_pFont);
345
346        envmapRenderer->OnDestroyDevice();
347}
348
349
350//--------------------------------------------------------------------------------------
351/// \brief DXUT callback (You should create any D3DPOOL_DEFAULT resources here)
352///
353/// Resets camera and HUD elements. Initializes #g_pSaveSurface according to the
354/// current screen resolution.
355/// Then it forwards call to EnvMap::OnResetDevice.
356//--------------------------------------------------------------------------------------
357HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* g_pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
358{
359    HRESULT hr;
360
361    V_RETURN( g_DialogResourceManager.OnResetDevice() );
362    V_RETURN( g_SettingsDlg.OnResetDevice() );
363
364    if( g_pFont )   V_RETURN( g_pFont->OnResetDevice() );
365    if( g_pEffect ) V_RETURN( g_pEffect->OnResetDevice() );
366
367    // Create a sprite to help batch calls when drawing many lines of text
368    V_RETURN( D3DXCreateSprite( g_pd3dDevice, &g_pTextSprite ) );
369
370        // Create a surface to save screenshots
371        IDirect3DTexture9* pSaveTexture = NULL;
372
373        V( D3DXCreateTexture( g_pd3dDevice, pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height, 1,
374        //V( D3DXCreateTexture( g_pd3dDevice, 64, 64, 1,
375                D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &pSaveTexture) );
376        pSaveTexture->GetSurfaceLevel( 0, &g_pSaveSurface );
377        SAFE_RELEASE( pSaveTexture );
378
379        // Setup the camera's projection parameters
380    float fAspectRatio = pBackBufferSurfaceDesc->Width / (FLOAT)pBackBufferSurfaceDesc->Height;
381
382        camera.SetProjParams( D3DX_PI/4, fAspectRatio, 0.1, 100 );
383    camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height );
384
385        envmapRenderer->OnResetDevice();
386
387    // Position the on-screen dialog
388    g_HUD.SetLocation( 0, 0 );
389    g_HUD.SetSize( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height );
390
391    return S_OK;
392}
393
394//--------------------------------------------------------------------------------------
395/// DXUT callback (You should release resources created in the OnResetDevice callback here)
396//--------------------------------------------------------------------------------------
397void CALLBACK OnLostDevice( void* pUserContext )
398{
399    g_DialogResourceManager.OnLostDevice();
400    g_SettingsDlg.OnLostDevice();
401
402    if( g_pFont )       g_pFont->OnLostDevice();
403    if( g_pEffect )     g_pEffect->OnLostDevice();
404
405    SAFE_RELEASE( g_pTextSprite );
406        SAFE_RELEASE( g_pSaveSurface );
407
408        envmapRenderer->OnLostDevice();
409}
410
411//--------------------------------------------------------------------------------------
412/// \brief DXUT callback (Message processing).
413///
414/// Forwards messages to the DirectX settings window, the GUI controls or the camera, respecively.
415//--------------------------------------------------------------------------------------
416LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext )
417{
418    // Always allow dialog resource manager calls to handle global messages
419    // so GUI state is updated correctly
420    *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam );
421    if( *pbNoFurtherProcessing )
422        return 0;
423
424    if( g_SettingsDlg.IsActive() )
425    {
426        g_SettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam );
427        return 0;
428    }
429
430        // Give the dialogs a chance to handle the message first
431    *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam );
432    if( *pbNoFurtherProcessing )
433        return 0;
434
435    // Pass all remaining windows messages to camera so it can respond to user input
436        camera.HandleMessages( hWnd, uMsg, wParam, lParam );
437
438    return 0;
439}
440
441//--------------------------------------------------------------------------------------
442/// \brief DXUT callback (Handle updates to the scene)
443//--------------------------------------------------------------------------------------
444void CALLBACK OnFrameMove( IDirect3DDevice9* g_pd3dDevice, double fTime, float fElapsedTime, void* pUserContext )
445{
446    camera.FrameMove( fElapsedTime );
447}
448
449//--------------------------------------------------------------------------------------
450/// \brief DXUT callback (Render the scene). Also responsible for screenshot taking.
451///
452/// If a screenshot is being taken (#bSavingScreenshot), sets #g_pSaveSurface as the render target
453/// and saves it to a non-existent file (GenerateNewFileName()). Also saves current camera parameters (SaveCameraPosition()).
454///
455/// To perform actual rendering, it forwards call to EnvMap::OnFrameRender with current camera matrices.
456//--------------------------------------------------------------------------------------
457void CALLBACK OnFrameRender( IDirect3DDevice9* g_pd3dDevice, double fTime, float fElapsedTime, void* pUserContext )
458{
459    // If the settings dialog is being shown, then
460    // render it instead of rendering the app's scene
461    if( g_SettingsDlg.IsActive() )
462    {
463        g_SettingsDlg.OnRender( fElapsedTime );
464        return;
465    }
466
467        IDirect3DSurface9* oldRenderTarget = NULL;
468        if (bSavingScreenshot) {
469                V( g_pd3dDevice->GetRenderTarget(0, &oldRenderTarget) );
470                V( g_pd3dDevice->SetRenderTarget(0, g_pSaveSurface) );
471        }
472
473
474        V( g_pd3dDevice->BeginScene() );
475
476
477                D3DXMATRIXA16 mView = *camera.GetViewMatrix();
478                D3DXMATRIXA16 mProj = *camera.GetProjMatrix();
479
480                envmapRenderer->camera = &camera;
481                envmapRenderer->OnFrameRender( g_pd3dDevice, mView, mProj );
482               
483                if (!bSavingScreenshot)
484                {
485                        RenderText();
486                        V( g_HUD.OnRender( fElapsedTime ) );
487                }
488
489        V( g_pd3dDevice->EndScene() );
490
491
492        if (bSavingScreenshot)
493        {
494                // saving surface
495                char buf[CHARBUFFER_SIZE];
496                wchar_t wbuf[CHARBUFFER_SIZE];
497
498                GenerateNewFileName( counter );
499                sprintf(buf, "shots\\%03i.png", counter);
500                mbstowcs( wbuf, buf, CHARBUFFER_SIZE );
501
502                D3DXSaveSurfaceToFileW(wbuf, D3DXIFF_PNG, g_pSaveSurface, NULL, NULL);
503
504                sprintf(buf, "shots\\%03i", counter);
505                pp.SaveToFile( buf );
506
507                sprintf(buf, "shots\\%03i.matrix", counter);
508                SaveCameraPosition( buf );
509
510                g_pd3dDevice->SetRenderTarget(0, oldRenderTarget);
511                bSavingScreenshot = false;
512        }
513}
514
515//--------------------------------------------------------------------------------------
516/// \brief Generates a non-existing filename to store the screenshot in the <b>shots</b> directory.
517///
518/// Generated file names are shots/000.png, shots/001.png, ...
519//--------------------------------------------------------------------------------------
520
521int GenerateNewFileName( int& counter )
522{
523        char buf[CHARBUFFER_SIZE];
524        FILE* f;
525        do {
526                sprintf(buf, "shots\\%03i.png", counter);
527                if ( (f = fopen(buf, "rt")) != NULL )
528                {
529                        fclose( f );
530                        counter++;
531                }
532        } while (f != NULL);
533        return counter;
534}
535
536//--------------------------------------------------------------------------------------
537/// \brief DXUT callback (Keystroke messages)
538//--------------------------------------------------------------------------------------
539void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext )
540{
541        envmapRenderer->KeyboardProc( nChar, bKeyDown, bAltDown );
542}
543
544//--------------------------------------------------------------------------------------
545/// \brief Writes current camera settings to file.
546///
547/// Writes current #camera settings (world matrix and camera position) to file.
548/// Useful when capturing multiple screenshots from the same view.
549/// \param fileName the name of the file to be created
550//--------------------------------------------------------------------------------------
551
552void SaveCameraPosition( char* fileName )
553{
554        // save parameters to file:
555        // world matrix (4x4)
556        // camera position (3)
557
558        // save world matrix
559        D3DXMATRIXA16 W = *camera.GetViewMatrix();
560
561        FILE* f;
562
563        if ((f = fopen(fileName, "wt")) == NULL)
564        {
565                wchar_t wbuf[CHARBUFFER_SIZE];
566                mbstowcs( wbuf, fileName, CHARBUFFER_SIZE );
567        MessageBox(NULL, wbuf, L"File creation failed!", MB_ICONEXCLAMATION);
568                return;
569        }
570
571        fprintf(f, "\n");
572        fprintf(f, "World matrix:\n");
573        fprintf(f, "%10.4g %10.4g %10.4g %10.4g\n", W._11, W._12, W._13, W._14);
574        fprintf(f, "%10.4g %10.4g %10.4g %10.4g\n", W._21, W._22, W._23, W._24);
575        fprintf(f, "%10.4g %10.4g %10.4g %10.4g\n", W._31, W._32, W._33, W._34);
576        fprintf(f, "%10.4g %10.4g %10.4g %10.4g\n", W._41, W._42, W._43, W._44);
577
578        // save camera position
579        fprintf(f, "\n");
580        fprintf(f, "Camera position:\n");
581        const D3DXVECTOR3* eye = camera.GetEyePt();
582        fprintf(f, "%10g %10g %10g", eye->x, eye->y, eye->z);
583        fprintf(f, "\n");
584
585        fclose(f);
586}
587
588//--------------------------------------------------------------------------------------
589/// \brief Loads camera settings from file.
590///
591/// Loads #camera settings (world matrix and camera position) from an existing file.
592/// Useful when capturing multiple screenshots from the same view.
593/// \param fileName the name of the file to load from.
594//--------------------------------------------------------------------------------------
595
596void LoadCameraPosition( char* fileName )
597{
598        FILE* f;
599
600        if ((f = fopen(fileName, "rt")) == NULL) {
601                wchar_t wbuf[CHARBUFFER_SIZE];
602                mbstowcs( wbuf, fileName, CHARBUFFER_SIZE );
603        MessageBox(NULL, wbuf, L"File not found!", MB_ICONEXCLAMATION);
604                return;
605        }
606
607        const int BufSize = 500;        // size of char buffers
608        char buf[BufSize];
609        D3DXMATRIXA16 W;
610
611        fgets(buf, BufSize, f);         // skip comment
612        fgets(buf, BufSize, f);         // skip comment
613        fgets(buf, BufSize, f);         sscanf(buf, "%f %f %f %f", &W._11, &W._12, &W._13, &W._14);
614        fgets(buf, BufSize, f);         sscanf(buf, "%f %f %f %f", &W._21, &W._22, &W._23, &W._24);
615        fgets(buf, BufSize, f);         sscanf(buf, "%f %f %f %f", &W._31, &W._32, &W._33, &W._34);
616        fgets(buf, BufSize, f);         sscanf(buf, "%f %f %f %f", &W._41, &W._42, &W._43, &W._44);
617
618        // load camera position
619        D3DXVECTOR3 vecAt(0.0f, 0.0f, 0.0f);
620        D3DXVECTOR3 vecEye;
621        fgets(buf, BufSize, f);         // skip comment
622        fgets(buf, BufSize, f);         // skip comment
623        fgets(buf, BufSize, f);         sscanf(buf, "%f %f %f", &vecEye.x, &vecEye.y, &vecEye.z);
624
625        fclose(f);
626
627        camera.SetViewParams( &vecEye, &vecAt );
628
629        D3DXQUATERNION q;
630        D3DXQuaternionRotationMatrix(&q, &W);
631        camera.SetViewQuat(q);
632}
633
634//--------------------------------------------------------------------------------------
635/// \brief Util function. Creates an empty texture that shall be used as render target.
636///
637/// Note that render targets (D3DUSAGE_RENDERTARGET) must be created in the default memory pool (D3DPOOL_DEFAULT).
638/// @param size size of the new texture
639/// @param format format of the new texture (eg. D3DFMT_A32B32G32R32F)
640//--------------------------------------------------------------------------------------
641IDirect3DTexture9* CreateTexture( int size, D3DFORMAT Format )
642{
643        HRESULT hr;
644        IDirect3DTexture9* pTexture;
645        V( g_pd3dDevice->CreateTexture( size, size,             // dimensions
646                                                                        1,                              // mipmap levels
647                                                                        D3DUSAGE_RENDERTARGET, // usage
648                                                                        Format,                 
649                                                                        D3DPOOL_DEFAULT,// memory pool
650                                                                        &pTexture, NULL ) );
651        return pTexture;
652}
653
654//--------------------------------------------------------------------------------------
655/// \brief Util function. Creates an empty cubemap texture that shall be used as render target.
656///
657/// @param size size of the new texture
658/// @param format format of the new texture (eg. D3DFMT_A32B32G32R32F)
659//--------------------------------------------------------------------------------------
660
661IDirect3DCubeTexture9* CreateCubeTexture( int size, D3DFORMAT Format )
662{
663        HRESULT hr;
664        IDirect3DCubeTexture9* pCubeTexture;
665        V( g_pd3dDevice->CreateCubeTexture(     size, 1, D3DUSAGE_RENDERTARGET,
666                                                                                Format, D3DPOOL_DEFAULT, &pCubeTexture, NULL ) );
667        return pCubeTexture;
668}
669
670//--------------------------------------------------------------------------------------
671/// \brief Renders help and statistics text and displays algorithmic-specific parameters.
672///
673/// - Statistics: FPS value, screen resolution
674///
675/// - Help: displays avaliable keyboard shortcuts after the user presses F1.
676///
677/// - Algorithmic-specific parameters: describes the currently selected method and
678/// displays its most important parameters.
679//--------------------------------------------------------------------------------------
680void RenderText()
681{
682        const D3DSURFACE_DESC* backBufferDesc = DXUTGetBackBufferSurfaceDesc();
683
684    CDXUTTextHelper txtHelper( g_pFont, g_pTextSprite, 15 );
685    txtHelper.Begin();
686
687        txtHelper.SetInsertionPos( 5, 5 );
688        txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) );
689
690        txtHelper.DrawFormattedTextLine( L"%.2f fps @ %i x %i",
691                DXUTGetFPS(), backBufferDesc->Width, backBufferDesc->Height );
692        //txtHelper.DrawTextLine( DXUTGetFrameStats() );
693        txtHelper.DrawTextLine( DXUTGetDeviceStats() );
694        txtHelper.DrawTextLine( L"" );
695       
696        txtHelper.SetInsertionPos( 30, 180 );
697        txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) );
698       
699        switch (pp.GetInt( iWhichMethod )) {
700                case IDEAL:     
701                case IDEAL_LOCALIZED:   
702                        if ( pp.GetInt( iWhichMethod ) == IDEAL ) {
703                                txtHelper.DrawFormattedTextLine( L"Method : Ideal reflection / refr."); break;
704                        }
705                        else
706                        if (!pp.Get( bCubeMapFromFile ))
707                                 txtHelper.DrawFormattedTextLine( L"Method : Ideal reflection / refr. using depth impostors");
708                        else txtHelper.DrawFormattedTextLine( L"Method : Ideal reflection / refr. (no depth info. available from file!)"); break;
709                case DIFFUSE_SPECULAR: 
710                        if (pp.GetInt( iShininess ) > 0)
711                                txtHelper.DrawFormattedTextLine( L"Method : Specular reflections");
712                        else
713                                txtHelper.DrawFormattedTextLine( L"Method : Diffuse reflections");
714                        break;
715                case DIFFUSE_SPECULAR_LOCALIZED:
716                        if (pp.GetInt( iShininess ) > 0)
717                                txtHelper.DrawFormattedTextLine( L"Method : Specular reflections with localization");
718                        else
719                                txtHelper.DrawFormattedTextLine( L"Method : Diffuse reflections with localization");
720                        break;
721                case DIFFUSE_SPECULAR_LOCALIZED_COSTEX:
722                        if (pp.GetInt( iShininess ) > 0)
723                                txtHelper.DrawFormattedTextLine( L"Method : Specular reflections with localization and cos.texture");
724                        else
725                                txtHelper.DrawFormattedTextLine( L"Method : Diffuse reflections with localization and cos.texture");
726                        break;  }
727
728        txtHelper.DrawFormattedTextLine( L"IOR : %.2f Fresnel : %.2f", pp.Get( refractionIndex ), pp.Get( sFresnel ));
729        txtHelper.DrawFormattedTextLine( L"Shininess (s) : %i Intensity multiplier : %.2f", pp.GetInt( iShininess ), pp.Get( fIntensity ));
730
731        D3DXVECTOR3 ref = envmapRenderer->GetReferencePos();
732        txtHelper.DrawFormattedTextLine( L"Reference_pos: %.2g %.2g %.2g", ref.x, ref.y, ref.z);
733
734        if (pp.GetInt( iWhichMethod ) == IDEAL)
735        {
736                switch (pp.GetInt( iWhichMetal )) {
737                        case 0: txtHelper.DrawFormattedTextLine( L""); break;
738                        case 1: txtHelper.DrawFormattedTextLine( L"Metal: COPPER"); break;
739                        case 2: txtHelper.DrawFormattedTextLine( L"Metal: GOLD"); break;
740                        case 3: txtHelper.DrawFormattedTextLine( L"Metal: SILVER"); break;
741                        case 4: txtHelper.DrawFormattedTextLine( L"Metal: ALUMINUM"); break;
742                }
743        }
744        else txtHelper.DrawFormattedTextLine( L"");
745
746        txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) );
747
748        if ( pp.Get( bShowHelp ) )
749        {
750                txtHelper.SetInsertionPos( backBufferDesc->Width - 260, backBufferDesc->Height-24*15 );
751
752                txtHelper.DrawTextLine(
753                                L"Controls (F1 to hide):\n"
754                                L"___________________________________\n"
755                                L"                     GENERAL CONTROLS\n"
756                                L"Left click drag: Rotate mesh\n"
757                                L"Mouse wheel: Zoom\n"
758                                L"Arrow keys: Move object\n"
759                                //L"F2: Settings\n"
760                                //L"F3: Switch to REF device\n"
761                                L"F8: Switch to Wireframe mode\n"
762                                L"___________________________________\n"
763                                L"                             ALGORITHM\n"
764                                L"0-9: choose object mesh\n"
765                                L"TAB,Q: choose shading method\n"
766                                L"C: choose visualized cube map\n"
767                                L"A: refresh cube maps for every frame\n"
768                                L"L: LOCALIZE cube map lookups\n"
769                                L"SPACE: refresh cube maps MANUALLY\n"
770                                L"I,O: adjust Index of refraction (IOR)\n"
771                                L"W,E: adjust Fresnel term\n"
772                                L"gray +,-: adjust intensity\n"
773                                L"gray /,*: adjust specular shininess\n"
774                                L"___________________________________\n"
775                                L"                             UTILITIES\n"
776                                L"L: [L]oad params\n"
777                                L"S: [S]ave params & take SCREENSHOT\n"
778                                L"R: [R]eset params\n"
779                                L"___________________________________\n"
780                                L"                             Quit: ESC");
781        }
782        else
783        {
784                txtHelper.DrawTextLine( L"Press F1 for help" );
785        }
786
787        txtHelper.End();
788}
Note: See TracBrowser for help on using the repository browser.