-
Notifications
You must be signed in to change notification settings - Fork 0
/
radiosity_cpp.v4
2011 lines (1700 loc) · 72.6 KB
/
radiosity_cpp.v4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//--------------------------------------------------------------------------------------
// File: Radiosity.cpp
//
// Starting point for new Direct3D applications
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "dxstdafx.h"
#include "dxutmesh.h"
#include "resource.h"
//#define DEBUG_VS // Uncomment this line to debug vertex shaders
//#define DEBUG_PS // Uncomment this line to debug pixel shaders
#define IDC_MOVER_SOL 1
#define IDC_BORDES 2
#define IDC_FLECHITAS 3
#define SHADOWMAP_SIZE 256
#define MAP_SIZE 512
#define RAYTMAP_SIZE 64
#define HELPTEXTCOLOR D3DXCOLOR( 0.0f, 1.0f, 0.3f, 1.0f )
// helper
HRESULT OptimizarMesh( ID3DXMesh** ppInOutMesh );
int interseccion(D3DXVECTOR3 *pRayPos,D3DXVECTOR3 *pRayDir,double *dist,DWORD *f);
void rotar_xy(D3DXVECTOR3 *v,double an)
{
float x =v->x*cos(an)+v->y*sin(an);
float y =v->y*cos(an)-v->x*sin(an);
v->x = x;
v->y = y;
}
void rotar_xz(D3DXVECTOR3 *v,double an)
{
float x =v->x*cos(an)-v->z*sin(an);
float z =v->x*sin(an)+v->z*cos(an);
v->x = x;
v->z = z;
}
void rotar_zy(D3DXVECTOR3 *v,double an)
{
float y =v->y*cos(an)+v->z*sin(an);
float z =v->z*cos(an)-v->y*sin(an);
v->y = y;
v->z = z;
}
// Rotacion sobre un eje arbitrario
void rotar(D3DXVECTOR3 *vect,D3DXVECTOR3 *o,D3DXVECTOR3 *eje,float theta)
{
float a = o->x;
float b = o->y;
float c = o->z;
float u = eje->x;
float v = eje->y;
float w = eje->z;
float u2 = u*u;
float v2 = v*v;
float w2 = w*w;
float cosT = cos(theta);
float sinT = sin(theta);
float l2 = u2 + v2 + w2;
float l = sqrt(l2);
if(l2 < 0.000000001) // el vector de rotacion es casi nulo
return;
float x = vect->x;
float y = vect->y;
float z = vect->z;
float xr = a*(v2 + w2) + u*(-b*v - c*w + u*x + v*y + w*z)
+ (-a*(v2 + w2) + u*(b*v + c*w - v*y - w*z) + (v2 + w2)*x)*cosT
+ l*(-c*v + b*w - w*y + v*z)*sinT;
xr/=l2;
float yr = b*(u2 + w2) + v*(-a*u - c*w + u*x + v*y + w*z)
+ (-b*(u2 + w2) + v*(a*u + c*w - u*x - w*z) + (u2 + w2)*y)*cosT
+ l*(c*u - a*w + w*x - u*z)*sinT;
yr/=l2;
float zr = c*(u2 + v2) + w*(-a*u - b*v + u*x + v*y + w*z)
+ (-c*(u2 + v2) + w*(a*u + b*v - u*x - v*y) + (u2 + v2)*z)*cosT
+ l*(-b*u + a*v - v*x + u*y)*sinT;
zr/=l2;
vect->x = xr;
vect->y = yr;
vect->z = zr;
}
// Ambiente de prueba:
/*
LPCWSTR g_aszMeshFile[] =
{
L"room.x",
L"room.x",
L"pared2.x",
L"pared.x",
L"columna.x",
L"columna.x",
L"columna.x",
L"columna.x",
};
*/
LPCWSTR g_aszMeshFile[] =
{
L"pared.x",
L"pared.x",
L"pared.x",
L"pared.x",
L"pared.x",
};
#define NUM_OBJ (sizeof(g_aszMeshFile)/sizeof(g_aszMeshFile[0]))
D3DXMATRIXA16 g_amInitObjWorld[NUM_OBJ] =
{
// izq
D3DXMATRIXA16( 1, 0, 0, 0,
0, 2, 0, 0,
0, 0, 1, 0,
-5, -1, -5, 1 ),
// der
D3DXMATRIXA16( -1, 0, 0, 0,
0, 2, 0, 0,
0, 0, 1, 0,
10, -1, -5, 1 ),
// piso
D3DXMATRIXA16( 0, 2, 0, 0,
2, 0, 0, 0,
0, 0, 1, 0,
-3.5, -5.5, -5, 1 ),
// techo
D3DXMATRIXA16( 0, -2, 0, 0,
2, 0, 0, 0,
0, 0, 1, 0,
-3.5, 15.5, -5, 1 ),
// pared de atras
D3DXMATRIXA16( 0, 0, -1, 0,
0, 2, 0, 0,
0.6, 0, 0, 0,
1, -1, 8.7, 1 ),
};
// matrices de transf. de model a world
/*
D3DXMATRIXA16 g_amInitObjWorld[NUM_OBJ] =
{
// malla que funciona como piso (+ pared izquierda inferior)
D3DXMATRIXA16( 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1.5, 0,
-6, -2.5, -3, 1 ),
// techo + pared izquierda superior
D3DXMATRIXA16( 1, 0, 0, 0,
0, -1, 0, 0,
0, 0, 1.5, 0,
-6*1, 14-2.5*1, -3, 1 ),
// pared de la derecha
D3DXMATRIXA16( -1, 0, 0, 0,
0, 3, 0, 0,
0, 0, 1.5, 0,
11*1, -4*1, -3, 1 ),
// pared de atras
D3DXMATRIXA16( 0, 0, -1, 0,
0, 3, 0, 0,
1, 0, 0, 0,
0, -4, 16, 1 ),
// columna
D3DXMATRIXA16( 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-7, 1.7, 0, 1 ),
D3DXMATRIXA16( 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-7, 1.7, -3, 1 ),
D3DXMATRIXA16( 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-7, 1.7, -6, 1 ),
D3DXMATRIXA16( 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-7, 1.7, 3, 1 ),
};
*/
/*
D3DXMATRIXA16 g_amInitObjWorld[NUM_OBJ] =
{
// malla que funciona como piso (+ pared izquierda inferior)
D3DXMATRIXA16( 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-6*1, -2.5*1, -5*1, 1 ),
// techo + pared izquierda superior
D3DXMATRIXA16( 1, 0, 0, 0,
0, -1, 0, 0,
0, 0, 1, 0,
-6*1, 14-2.5*1, -5*1, 1 ),
// pared de la derecha
D3DXMATRIXA16( -1, 0, 0, 0,
0, 3, 0, 0,
0, 0, 1, 0,
11*1, -4*1, -5*1, 1 ),
// pared de atras
D3DXMATRIXA16( 0, 0, -1, 0,
0, 3, 0, 0,
1, 0, 0, 0,
0, -4, 8.9, 1 ),
// columna
D3DXMATRIXA16( 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-7, 1.7, 0, 1 ),
D3DXMATRIXA16( 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-7, 1.7, -3, 1 ),
D3DXMATRIXA16( 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-7, 1.7, -6, 1 ),
D3DXMATRIXA16( 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-7, 1.7, 3, 1 ),
};
*/
// necesito que el fomato para el mesh, tenga una coordenada de textura adicional
// que voy a utilizar para incrustar el id de cada vertice
D3DVERTEXELEMENT9 g_aVertDecl[] =
{
{ 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
{ 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
{ 0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
{ 0, 32, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 },
{ 0, 40, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 },
{ 0, 48, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 },
D3DDECL_END()
};
// Vertex format para mesh
struct VERTEX
{
D3DXVECTOR3 position;
D3DXVECTOR3 normal;
D3DXVECTOR2 texcoord;
D3DXVECTOR2 texcoord_id;
D3DXVECTOR2 texcoord_id2;
D3DXVECTOR2 texcoord_id3;
};
#define D3DFVF_VERTEX (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX4)
// Vertex format en memoria para acceder rapidamente al rebote de la luz
struct MEM_VERTEX
{
D3DXVECTOR3 position;
D3DXVECTOR3 normal;
D3DXVECTOR3 color;
int nro_obj;
};
// Vertex format para calcular el maximo
struct CALC_MAX_VERTEX
{
FLOAT x,y,z;
float u,v;
};
#define D3DFVF_CALC_MAX_VERTEX (D3DFVF_XYZ|D3DFVF_TEX1)
// encapsula el mesh con su transformacion y lo relaciono con el primer vertice
struct CObj
{
CDXUTMesh m_Mesh;
D3DXMATRIXA16 m_mWorld;
int primer_vertice;
D3DXVECTOR3 N[50000]; // normales
};
// Esto estas currado del DXUtil, lo dejo tal como esta por el momento
//-----------------------------------------------------------------------------
// Name: class CViewCamera
// Desc: A camera class derived from CFirstPersonCamera. The arrow keys and
// numpad keys are disabled for this type of camera.
//-----------------------------------------------------------------------------
class CViewCamera : public CFirstPersonCamera
{
protected:
virtual D3DUtil_CameraKeys MapKey( UINT nKey )
{
// Provide custom mapping here.
// Same as default mapping but disable arrow keys.
switch( nKey )
{
case 'A': return CAM_STRAFE_LEFT;
case 'D': return CAM_STRAFE_RIGHT;
case 'W': return CAM_MOVE_FORWARD;
case 'S': return CAM_MOVE_BACKWARD;
case 'Q': return CAM_MOVE_DOWN;
case 'E': return CAM_MOVE_UP;
case VK_HOME: return CAM_RESET;
}
return CAM_UNKNOWN;
}
};
//-----------------------------------------------------------------------------
// Name: class CLightCamera
// Desc: A camera class derived from CFirstPersonCamera. The letter keys
// are disabled for this type of camera. This class is intended for use
// by the spot light.
//-----------------------------------------------------------------------------
class CLightCamera : public CFirstPersonCamera
{
protected:
virtual D3DUtil_CameraKeys MapKey( UINT nKey )
{
// Provide custom mapping here.
// Same as default mapping but disable arrow keys.
switch( nKey )
{
case VK_LEFT: return CAM_STRAFE_LEFT;
case VK_RIGHT: return CAM_STRAFE_RIGHT;
case VK_UP: return CAM_MOVE_FORWARD;
case VK_DOWN: return CAM_MOVE_BACKWARD;
case VK_PRIOR: return CAM_MOVE_UP; // pgup
case VK_NEXT: return CAM_MOVE_DOWN; // pgdn
case VK_NUMPAD4: return CAM_STRAFE_LEFT;
case VK_NUMPAD6: return CAM_STRAFE_RIGHT;
case VK_NUMPAD8: return CAM_MOVE_FORWARD;
case VK_NUMPAD2: return CAM_MOVE_BACKWARD;
case VK_NUMPAD9: return CAM_MOVE_UP;
case VK_NUMPAD3: return CAM_MOVE_DOWN;
case VK_HOME: return CAM_RESET;
}
return CAM_UNKNOWN;
}
};
//--------------------------------------------------------------------------------------
// Variables Globales
//--------------------------------------------------------------------------------------
// esto esta currado del dXutil, para que dibuje info de pantalla: fps, etc. lo dejo tal como esta
ID3DXFont* g_pFont = NULL; // Font for drawing text
ID3DXFont* g_pFontSmall = NULL; // Font for drawing text
ID3DXSprite* g_pTextSprite = NULL; // Sprite for batching draw text calls
ID3DXEffect* g_pEffect = NULL; // D3DX effect interface
CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs
CD3DSettingsDlg g_SettingsDlg; // Device settings dialog
CDXUTDialog g_HUD; // dialog for standard controls
//--------------------------------------------------------------------------------------
CFirstPersonCamera g_VCamera; // camara pp dicha
CFirstPersonCamera g_LCamera; // esta la uso para poder ajustar la luz usando el DXutil
//--------------------------------------------------------------------------------------
// Esto tambien esta currado del DXUtil, para manejar el input del mouse etc
bool g_bRightMouseDown = false;// Indicates whether right mouse button is held
bool g_bCameraPerspective // Indicates whether we should render view from
= true; // the camera's or the light's perspective
//--------------------------------------------------------------------------------------
// escena pp dicha
CObj g_Obj[NUM_OBJ];
LPDIRECT3DVERTEXDECLARATION9 g_pVertDecl = NULL;
LPDIRECT3DTEXTURE9 g_pTexDef = NULL; // textura por defecto si falla la carga
CDXUTMesh g_LightMesh; // malla para mostrar un conito que representa la luz
//--------------------------------------------------------------------------------------
// Aca viene la posta:
//--------------------------------------------------------------------------------------
LPDIRECT3DTEXTURE9 g_pShadowMap = NULL; // Texture to which the shadow map is rendered
LPDIRECT3DSURFACE9 g_pDSShadow = NULL; // Depth-stencil buffer for rendering to shadow map
float g_fLightFov; // FOV de la luz
D3DXMATRIXA16 g_mShadowProj; // Projection matrix for shadow map
LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL; // Buffer para vertices
LPDIRECT3DVERTEXBUFFER9 g_pVBCalcMax = NULL; // Buffer para vertices auxiliares para el maximo
LPDIRECT3DTEXTURE9 g_pRMap = NULL; // Radiosity Map Texture para almacenar la cantidad de luz acumulada x vertice
LPDIRECT3DTEXTURE9 g_pRMap2 = NULL;
LPDIRECT3DTEXTURE9 g_pRMap3 = NULL;
LPDIRECT3DTEXTURE9 g_pRayT = NULL; // prueba de intersecciones
LPDIRECT3DSURFACE9 g_pDSRayT = NULL; // Depth-stencil buffer
LPDIRECT3DTEXTURE9 g_pTempTexture = NULL; // textura temporaria para leer el rayt
LPDIRECT3DTEXTURE9 g_pRMapTemp = NULL; // textura temporaria para leer el rmap
LPDIRECT3DTEXTURE9 g_pTexAux = NULL; // texture auxiliar
int step = 0;
int cant_vertices = 0;
int nro_luz = 0;
int cant_luces = 2;
int primer_rebote = 2;
D3DXVECTOR3 g_LightPos; // posicion de la luz actual (la que estoy analizando)
D3DXVECTOR3 g_LightDir; // direccion de la luz actual
D3DXMATRIXA16 g_LightView; //
D3DXVECTOR3 LightPos[256],LightDir[256],LightColor[256];
MEM_VERTEX *g_pVertices = NULL; // global para almacenar todos los vertices
D3DXVECTOR3 vUp(0,1,0);
double g_fTime;
D3DXVECTOR3 ant_LightPos[256],ant_LightDir[256]; // para dibujar las flechas
int ant_cant_luces = 0;
int ant_primer_rebote = 2;
// opciones
bool g_bDibujarFlechas = false;
bool g_bDibujarBordes = false;
bool g_bSolcito = false; // mover el sol desde afuera de la habitacion
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
void InitializeDialogs();
bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext );
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, const D3DCAPS9* pCaps, void* pUserContext );
HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
void CALLBACK OnFrameMove( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext );
void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext );
void RenderText();
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext );
void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext );
void CALLBACK MouseProc( bool bLeftButtonDown, bool bRightButtonDown, bool bMiddleButtonDown, bool bSideButton1Down, bool bSideButton2Down, int nMouseWheelDelta, int xPos, int yPos, void* pUserContext );
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext );
void CALLBACK OnLostDevice( void* pUserContext );
void CALLBACK OnDestroyDevice( void* pUserContext );
void RenderScene( IDirect3DDevice9* pd3dDevice, bool bRenderShadow, float fElapsedTime, const D3DXMATRIX *pmView, const D3DXMATRIX *pmProj );
void ProcesarVertices( IDirect3DDevice9* pd3dDevice,const D3DXMATRIX *pmView, const D3DXMATRIX *pmProj);
void ProcesarPatch(IDirect3DDevice9* pd3dDevice,int L);
void GenerarMaximos(IDirect3DDevice9* pd3dDevice);
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
INT WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
// Initialize the camera
g_VCamera.SetScalers( 0.01f, 2.5f );
g_LCamera.SetScalers( 0.01f, 1.0f );
g_VCamera.SetRotateButtons( true, false, false );
g_LCamera.SetRotateButtons( false, false, true );
// Set up the view parameters for the camera
D3DXVECTOR3 vFromPt = D3DXVECTOR3( 0.0f, 5.0f, -18.0f );
D3DXVECTOR3 vLookatPt = D3DXVECTOR3( 0.2643f, 4.868f, -17.044f );
g_VCamera.SetViewParams( &vFromPt, &vLookatPt );
vFromPt = D3DXVECTOR3( 0.0f, 8.0f, -5.0f );
vLookatPt = D3DXVECTOR3( 1.0f, 6.0f, -5.0f );
g_LCamera.SetViewParams( &vFromPt, &vLookatPt );
/*
D3DXVECTOR3 vFromPt = D3DXVECTOR3( 0.0f, 5.0f, -18.0f );
D3DXVECTOR3 vLookatPt = D3DXVECTOR3( 0.0f, -1.0f, 0.0f );
g_VCamera.SetViewParams( &vFromPt, &vLookatPt );
vFromPt = D3DXVECTOR3( 0.0f, 8.0f, -5.0f );
vLookatPt = D3DXVECTOR3( 0.0f, -2.0f, 1.0f );
g_LCamera.SetViewParams( &vFromPt, &vLookatPt );
*/
LightPos[0] = vFromPt;
LightDir[0] = vLookatPt -vFromPt;
D3DXVec3Normalize(&LightDir[0],&LightDir[0]);
// Initialize the spot light
g_fLightFov = D3DX_PI / 2.0f;
// Set the callback functions. These functions allow DXUT to notify
// the application about device changes, user input, and windows messages. The
// callbacks are optional so you need only set callbacks for events you're interested
// in. However, if you don't handle the device reset/lost callbacks then the sample
// framework won't be able to reset your device since the application must first
// release all device resources before resetting. Likewise, if you don't handle the
// device created/destroyed callbacks then DXUT won't be able to
// recreate your device resources.
DXUTSetCallbackDeviceCreated( OnCreateDevice );
DXUTSetCallbackDeviceReset( OnResetDevice );
DXUTSetCallbackDeviceLost( OnLostDevice );
DXUTSetCallbackDeviceDestroyed( OnDestroyDevice );
DXUTSetCallbackMsgProc( MsgProc );
DXUTSetCallbackKeyboard( KeyboardProc );
DXUTSetCallbackMouse( MouseProc );
DXUTSetCallbackFrameRender( OnFrameRender );
DXUTSetCallbackFrameMove( OnFrameMove );
InitializeDialogs();
// Show the cursor and clip it when in full screen
DXUTSetCursorSettings( true, true );
// Initialize DXUT and create the desired Win32 window and Direct3D
// device for the application. Calling each of these functions is optional, but they
// allow you to set several options which control the behavior of the framework.
DXUTInit( true, true, true ); // Parse the command line, handle the default hotkeys, and show msgboxes
DXUTCreateWindow( L"Radiosity" );
DXUTCreateDevice( D3DADAPTER_DEFAULT, true, 1000, 700, IsDeviceAcceptable, ModifyDeviceSettings );
// Pass control to DXUT for handling the message pump and
// dispatching render calls. DXUT will call your FrameMove
// and FrameRender callback when there is idle time between handling window messages.
DXUTMainLoop();
// Perform any application-level cleanup here. Direct3D device resources are released within the
// appropriate callback functions and therefore don't require any cleanup code here.
return DXUTGetExitCode();
}
//--------------------------------------------------------------------------------------
// Sets up the dialogs
//--------------------------------------------------------------------------------------
void InitializeDialogs()
{
g_SettingsDlg.Init( &g_DialogResourceManager );
g_HUD.Init( &g_DialogResourceManager );
g_HUD.SetCallback( OnGUIEvent );
g_HUD.AddCheckBox( IDC_MOVER_SOL, L"Mover Sol", 0, 0, 160, 22, false);
g_HUD.AddCheckBox( IDC_BORDES, L"Bordes", 0, 30, 160, 22, false);
g_HUD.AddCheckBox( IDC_FLECHITAS, L"Flechas", 0, 60, 160, 22, false);
}
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat,
D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext )
{
// Skip backbuffer formats that don't support alpha blending
IDirect3D9* pD3D = DXUTGetD3DObject();
if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat ) ) )
return false;
// necesitamos shader 3.0
if( pCaps->PixelShaderVersion < D3DPS_VERSION( 3, 0 ) )
return false;
// necesitamos D3DFMT_R32F para render target (para el shadow map y el Radiosity map)
if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType,
AdapterFormat, D3DUSAGE_RENDERTARGET,
D3DRTYPE_CUBETEXTURE, D3DFMT_R32F ) ) )
return false;
// necesitamos D3DFMT_A32B32G32R32F para 3 canales de colores en el Radiosity map)
if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType,
AdapterFormat, D3DUSAGE_RENDERTARGET,
D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F) ) )
return false;
// tambien D3DFMT_A8R8G8B8 para render target
if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType,
AdapterFormat, D3DUSAGE_RENDERTARGET,
D3DRTYPE_CUBETEXTURE, D3DFMT_A8R8G8B8 ) ) )
return false;
return true;
}
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, const D3DCAPS9* pCaps, void* pUserContext )
{
// Turn vsync off
pDeviceSettings->pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
g_SettingsDlg.GetDialogControl()->GetComboBox( DXUTSETTINGSDLG_PRESENT_INTERVAL )->SetEnabled( false );
// If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
// then switch to SWVP.
if( (pCaps->DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) == 0 ||
pCaps->VertexShaderVersion < D3DVS_VERSION(1,1) )
{
pDeviceSettings->BehaviorFlags = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
}
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
#ifdef DEBUG_VS
if( pDeviceSettings->DeviceType != D3DDEVTYPE_REF )
{
pDeviceSettings->BehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING;
pDeviceSettings->BehaviorFlags &= ~D3DCREATE_PUREDEVICE;
pDeviceSettings->BehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
}
#endif
#ifdef DEBUG_PS
pDeviceSettings->DeviceType = D3DDEVTYPE_REF;
#endif
// For the first device created if its a REF device, optionally display a warning dialog box
static bool s_bFirstTime = true;
if( s_bFirstTime )
{
s_bFirstTime = false;
if( pDeviceSettings->DeviceType == D3DDEVTYPE_REF )
DXUTDisplaySwitchingToREFWarning();
}
return true;
}
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
HRESULT hr;
V_RETURN( g_DialogResourceManager.OnCreateDevice( pd3dDevice ) );
V_RETURN( g_SettingsDlg.OnCreateDevice( pd3dDevice ) );
// Initialize the font
V_RETURN( D3DXCreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
L"Arial", &g_pFont ) );
V_RETURN( D3DXCreateFont( pd3dDevice, 12, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
L"Arial", &g_pFontSmall ) );
// Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the
// shader debugger. Debugging vertex shaders requires either REF or software vertex
// processing, and debugging pixel shaders requires REF. The
// D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the
// shader debugger. It enables source level debugging, prevents instruction
// reordering, prevents dead code elimination, and forces the compiler to compile
// against the next higher available software target, which ensures that the
// unoptimized shaders do not exceed the shader model limitations. Setting these
// flags will cause slower rendering since the shaders will be unoptimized and
// forced into software. See the DirectX documentation for more information about
// using the shader debugger.
DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE;
#ifdef DEBUG_VS
dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
#endif
#ifdef DEBUG_PS
dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
#endif
// Cargo y compilo el efecto
WCHAR str[MAX_PATH];
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Radiosity.fx" ) );
ID3DXBuffer *pBuffer = NULL;
if( FAILED(D3DXCreateEffectFromFile( pd3dDevice, str, NULL, NULL, dwShaderFlags,
NULL, &g_pEffect, &pBuffer ) ))
{
// si da error, aca lo puedo analizar:
char *saux = (char *)pBuffer->GetBufferPointer();
return hr;
}
// Creo el vertex declaration
V_RETURN( pd3dDevice->CreateVertexDeclaration( g_aVertDecl, &g_pVertDecl ) );
// Inicializo los mesh
for( int i = 0; i < NUM_OBJ; ++i )
{
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, g_aszMeshFile[i] ) );
if( FAILED( g_Obj[i].m_Mesh.Create( pd3dDevice, str ) ) )
return DXUTERR_MEDIANOTFOUND;
V_RETURN( g_Obj[i].m_Mesh.SetVertexDecl( pd3dDevice, g_aVertDecl ) );
g_Obj[i].m_mWorld = g_amInitObjWorld[i];
}
// Determino la extension del objeto
/*
{
LPD3DXMESH g_pMesh = g_Obj[0].m_Mesh.m_pMesh;
D3DXVECTOR3 min,max;
min = max = D3DXVECTOR3 (0,0,0);
BYTE* pVertices=NULL;
g_pMesh->LockVertexBuffer(D3DLOCK_READONLY, (LPVOID*)&pVertices);
D3DXComputeBoundingBox((D3DXVECTOR3 *)pVertices,g_pMesh->GetNumVertices(),g_pMesh->GetNumBytesPerVertex(),&min,&max);
g_pMesh->UnlockVertexBuffer();
}*/
// necesito que la habitacion tenga mas rectangulos en las paredes
//for(int i=2;i<4;++i)
/*
{
int i = 2;
LPD3DXMESH pMeshOut;
D3DXTessellateNPatches(g_Obj[i].m_Mesh.m_pMesh,NULL,5,FALSE,&pMeshOut,NULL);
g_Obj[i].m_Mesh.m_pMesh->Release();
g_Obj[i].m_Mesh.m_pMesh = pMeshOut;
}*/
//--------------------------------------------------------------------------------------
// Voy a crear un buffer de vertices, que contiene TODOS los vertices de cada una de las mallas.
// Si existia de antes lo borro
if(g_pVB)
g_pVB->Release();
g_pVB = NULL;
// primero cuento cuantos vertices hay, asi puedo allocar suficiente memoria
cant_vertices = 0; // Cantidad total de vertices
int cant_f = 0;
for(int i = 0; i < NUM_OBJ; ++i )
{
LPD3DXMESH pMesh = g_Obj[i].m_Mesh.GetMesh();
cant_vertices += pMesh->GetNumVertices();
cant_f += pMesh->GetNumFaces();
}
// Alloco memoria y creo un buffer para todos los vertices
VERTEX * pVertices;
size_t size = sizeof(VERTEX)*cant_vertices;
if( FAILED( pd3dDevice->CreateVertexBuffer( size,
0 , D3DFVF_VERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL ) ) )
return E_FAIL;
if( FAILED( g_pVB->Lock( 0, size, (void**)&pVertices, 0 ) ) )
return E_FAIL;
// creo el array de vertices en memoria (para no tener que lockear)
g_pVertices = new MEM_VERTEX[cant_vertices];
// lleno los vertices con un ID unico
// El id lo formo con un par de coordenadas i,j que permiten relacionar
// una textura con los vertices
// tex2d(i,j) --> representa el vertice i,j
int id_i = 0;
int id_j = 0;
int k = 0; // nro de vertice
for(int i = 0; i < NUM_OBJ; ++i )
{
LPD3DXMESH pMesh = g_Obj[i].m_Mesh.GetMesh();
g_Obj[i].primer_vertice = k;
int cant_v = pMesh->GetNumVertices();
size_t bpv = pMesh->GetNumBytesPerVertex();
BYTE *pVerticesMesh=NULL;
pMesh->LockVertexBuffer(0, (LPVOID*)&pVerticesMesh);
// Recorro los vertices y los copio al buffer global (que agrupa TODAS los mesh)
for(int j=0;j<cant_v;j++)
{
VERTEX *V = (VERTEX *)(pVerticesMesh+ bpv*j);
// Creo el indice
V->texcoord_id.x = id_i; // el valor u lo uso para almacenar el id_i
V->texcoord_id.y = id_j;
if(++id_i>=MAP_SIZE)
{
id_i = 0;
id_j++;
}
// Almaceno el Vertice en el global
pVertices[k] = *V;
// almaceno el vertice en memoria
g_pVertices[k].color.x = g_pVertices[k].color.y = g_pVertices[k].color.z = 1;
g_pVertices[k].normal = V->normal;
g_pVertices[k].position = V->position;
g_pVertices[k].nro_obj = i;
// ojo, necesito que los vertices esten en coordenadas del mundo (xyz real)
D3DXVec3TransformNormal(&g_pVertices[k].normal,&g_pVertices[k].normal,&g_Obj[i].m_mWorld);
D3DXVec3TransformCoord(&g_pVertices[k].position,&g_pVertices[k].position,&g_Obj[i].m_mWorld);
// un vertice mas
++k;
}
{
// alloco memoria para los indices (para almacenar las normales)
WORD* pIndices=NULL;
pMesh->LockIndexBuffer(D3DLOCK_READONLY, (LPVOID*)&pIndices);
int cant_f = pMesh->GetNumFaces();
for(int f=0;f<cant_f;++f)
{
// tomo como normal el primer vertice
VERTEX *V = (VERTEX *)(pVerticesMesh+ bpv*pIndices[3*f]);
g_Obj[i].N[f] = V->normal;
// de paso asocio los 3 vertices
VERTEX *V2 = (VERTEX *)(pVerticesMesh+ bpv*pIndices[3*f+1]);
VERTEX *V3 = (VERTEX *)(pVerticesMesh+ bpv*pIndices[3*f+2]);
V->texcoord_id2 = V2->texcoord_id;
V->texcoord_id3 = V3->texcoord_id;
V2->texcoord_id2 = V->texcoord_id;
V2->texcoord_id3 = V3->texcoord_id;
V3->texcoord_id2 = V->texcoord_id;
V3->texcoord_id3 = V2->texcoord_id;
}
pMesh->UnlockIndexBuffer();
}
pMesh->UnlockVertexBuffer();
}
g_pVB->Unlock();
// vertices auxiliares para calcular el maximo
{
if(g_pVBCalcMax)
g_pVBCalcMax->Release();
g_pVBCalcMax = NULL;
CALC_MAX_VERTEX vertices[] =
{
{ -1, 1, 1, 0,0, },
{ 1, 1, 1, 1,0, },
{ -1, -1, 1, 0,1, },
{ 1,-1, 1, 1,1, },
};
if( FAILED( pd3dDevice->CreateVertexBuffer( 3*sizeof(CALC_MAX_VERTEX),
0, D3DFVF_CALC_MAX_VERTEX,
D3DPOOL_DEFAULT, &g_pVBCalcMax, NULL ) ) )
{
return E_FAIL;
}
VOID* pVertices;
if( FAILED( g_pVBCalcMax->Lock( 0, sizeof(vertices), (void**)&pVertices, 0 ) ) )
return E_FAIL;
memcpy( pVertices, vertices, sizeof(vertices) );
g_pVBCalcMax->Unlock();
}
// Creo e inicializo la malla flechita que representa la direccion de luz
// (solo cosmetica, para ver donde esta la luz.
// Guarda!: que luz es un patch como cualquier otro, la unica diferencia
// es que es el patch inicial. NO ES UN SPOT LIGHT, . y ojo que
// si bien tiene una direccion, (que en gral es la normal al patch), en teoria el angulo
// solido es todo el hemisferio (fov = 180grados)
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"UI\\arrow.x" ) );
if( FAILED( g_LightMesh.Create( pd3dDevice, str ) ) )
return DXUTERR_MEDIANOTFOUND;
V_RETURN( g_LightMesh.SetVertexDecl( pd3dDevice, g_aVertDecl ) );
return S_OK;
}
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice,
const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
HRESULT hr;
//--------------------------------------------------------------------------------------
// esto es todo currado del dxutil, para la cosmetica de la pantalla
V_RETURN( g_DialogResourceManager.OnResetDevice() );
V_RETURN( g_SettingsDlg.OnResetDevice() );
if( g_pFont )
V_RETURN( g_pFont->OnResetDevice() );
if( g_pFontSmall )
V_RETURN( g_pFontSmall->OnResetDevice() );
if( g_pEffect )
V_RETURN( g_pEffect->OnResetDevice() );
// Create a sprite to help batch calls when drawing many lines of text
V_RETURN( D3DXCreateSprite( pd3dDevice, &g_pTextSprite ) );
g_HUD.SetLocation( pBackBufferSurfaceDesc->Width-170, 0 );
g_HUD.SetSize( 170, pBackBufferSurfaceDesc->Height );
//--------------------------------------------------------------------------------------
// incializo las camaras
float fAspectRatio = pBackBufferSurfaceDesc->Width / (FLOAT)pBackBufferSurfaceDesc->Height;
g_VCamera.SetProjParams( D3DX_PI/4, fAspectRatio, 0.1f, 100.0f );
g_LCamera.SetProjParams( D3DX_PI, fAspectRatio, 0.1f, 100.0f );
// creo una textura por defecto, color gris, para que se use cuando falla alguna carga de textura
// la textura tiene 1 x 1, con lo cual ocupa un solo 32bits
V_RETURN( pd3dDevice->CreateTexture( 1, 1, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_pTexDef, NULL ) );
// asi que no hay duda, accedo directo a los 32 bits
// (si fuese de n x m, tengo que estudiar el tema del pitch) que no lo tengo del todo desculado
D3DLOCKED_RECT lr;
V_RETURN( g_pTexDef->LockRect( 0, &lr, NULL, 0 ) );
*(LPDWORD)lr.pBits = D3DCOLOR_RGBA( 128, 128, 128, 255 );
V_RETURN( g_pTexDef->UnlockRect( 0 ) );
//D3DXCreateTextureFromFile( pd3dDevice, L"bricks_clay_02_512x512.JPG",&g_pTexDef);
// Restore the scene objects
for( int i = 0; i < NUM_OBJ; ++i )
V_RETURN( g_Obj[i].m_Mesh.RestoreDeviceObjects( pd3dDevice ) );
V_RETURN( g_LightMesh.RestoreDeviceObjects( pd3dDevice ) );
//--------------------------------------------------------------------------------------
// Creo el shadowmap.
// lo voy a usar para calcular el factor de visibilidad de la ecuacion del radiosity
// esto es V(i,j) = 1 si el patch j es visible desde el patch, 0 caso contrario.
V_RETURN( pd3dDevice->CreateTexture( SHADOWMAP_SIZE, SHADOWMAP_SIZE,
1, D3DUSAGE_RENDERTARGET,
D3DFMT_R32F,
D3DPOOL_DEFAULT,
&g_pShadowMap,
NULL ) );
// tengo que crear un stencilbuffer para el shadowmap manualmente
// para asegurarme que tenga la el mismo tamaño que el shadowmap, y que no tenga
// multisample, etc etc.
DXUTDeviceSettings d3dSettings = DXUTGetDeviceSettings();
V_RETURN( pd3dDevice->CreateDepthStencilSurface( SHADOWMAP_SIZE,
SHADOWMAP_SIZE,
d3dSettings.pp.AutoDepthStencilFormat,
D3DMULTISAMPLE_NONE,
0,
TRUE,
&g_pDSShadow,
NULL ) );
// por ultimo necesito una matriz de proyeccion para el shadowmap, ya
// que voy a dibujar desde el pto de vista de la luz.
D3DXMatrixPerspectiveFovLH( &g_mShadowProj, g_fLightFov, 1, 0.01f, 100.0f);
//--------------------------------------------------------------------------------------
// Create the mapa para guardar la radiosidad
// nota: en el VS, tengo que acceder a esta textura, para ello tengo
// que usar tex2Dlod, encontre que solo funciona para texturas en formato float:
// Vertex Shader 3.0 supports texture sampling
// The HLSL function that performs texture sampling in VS is tex2Dlod(). It takes two arguments,
// your sampler and a float4 in the format (u, v, mip1, mip2).
// Set mip1 and mip2 to 0 unless you want to do mipmap blending