Форум программистов, компьютерный форум, киберфорум
DirectX
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.91/35: Рейтинг темы: голосов - 35, средняя оценка - 4.91
10 / 10 / 0
Регистрация: 10.07.2011
Сообщений: 75

Анимация Меша из Х файла

22.10.2011, 15:31. Показов 6952. Ответов 23
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Не смог по этому поводу найти совсем ничего путнего, то какието неверочтных размеров исходники вроде примера от майкрософт Мультианимации, расскажите плз еси кто знает как просто считать и воспроизвести анимацию для обьекта, еси его грузить из Х файла?
1
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
22.10.2011, 15:31
Ответы с готовыми решениями:

Проблема визуализации меша из .X файла
Задача следующая: есть max файл, который был конвертирован в Х и загружен в приложение d3d, те загружен в меш. При визуализации все...

Координаты меша
Помогите вспомнить как изменить координаты меша, насколько я помню через мировую матрицу? Вот как я делаю: LOCATIONS.posx=0.0f; ...

Некорректное отображение меша на определённом расстоянии
У мешей на некотором расстоянии начинают просвечивать полигоны, которых по идее не должно быть видно. В чем причина? Сорцы и билд...

23
71 / 76 / 9
Регистрация: 30.06.2011
Сообщений: 176
23.10.2011, 08:11
Просто никак.
У Frank Luna есть примерчик с анимацией более понятный (1000 строк).
http://www.d3dcoder.net/d3d9c.htm
0
10 / 10 / 0
Регистрация: 10.07.2011
Сообщений: 75
24.10.2011, 23:00  [ТС]
Я посмотрел, даже попытался что то из этого вытащить но все безуспешно, к основному файлу там подключено столько доп. файлов и т.д. + еще кууча всего что было создано явно для удобства а не для читаемости и понимаемости кода, что как раз бы хотелось увидеть...Я пробовал штурмовать Skinned Mesh и MultiAnimation - там свои проблемы: то DXUT подключат, то понасоздают кучу кода для оформления, и попытки найти в нем то немногое что мне нужно оч. трудно...по таким исходикам выучить и полностью понять что то невозможно, я уже убедился) Может вы заете литературу какую нибудь, туторы, по которым возможно понять принцип что бы далее писать что то свое?
У меня в принципе нет проблем с непонимаем кода, но т.к. я не знаю DirectX, а только хочу его выучить, то очень трудно из исходника большого вытащить то что нужно.
0
71 / 76 / 9
Регистрация: 30.06.2011
Сообщений: 176
27.10.2011, 09:04
Цитата Сообщение от Arkanoid Посмотреть сообщение
еще кууча всего что было создано явно для удобства а не для читаемости и понимаемости кода, что как раз бы хотелось увидеть...
У Frank Luna всё удобно и понятно как раз !
Есть еще: "DirectX продвинутая анимация" - Джим Адамс. Там много хорошей теории
0
10 / 10 / 0
Регистрация: 10.07.2011
Сообщений: 75
12.11.2011, 00:03  [ТС]
я перековырял кучу исходников...поскольку та чать что касается анимации как правило довольно обширная, вот тот код который я составил из одного примера...но возникает много ошибок...вот код:
C++
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
//-----------------------------------------------------------------------------
// File: SkinnedMesh-Mesh.cpp
//
// Desc: CD3DSkinMesh implementation for sample showing skinned meshes in D3D
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#define STRICT
#include <windows.h>
#include <commdlg.h>
#include <tchar.h>
#include <stdio.h>
#include <d3dx9.h>
#include "skinnedmesh-mesh.h"
LPDIRECT3D9         g_pD3D = NULL; // Used to create the D3DDevice
LPDIRECT3DDEVICE9   g_pd3dDevice = NULL; // Our rendering device
 
 
 
class CD3DSkinMesh;
HRESULT InitD3D( HWND hWnd )
{
    // Create the D3D object, which is needed to create the D3DDevice.
    if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
        return E_FAIL;
 
    // Set up the structure used to create the D3DDevice. Most parameters are
    // zeroed out. We set Windowed to TRUE, since we want to do D3D in a
    // window, and then set the SwapEffect to "discard", which is the most
    // efficient method of presenting the back buffer to the display.  And 
    // we request a back buffer format that matches the current desktop display 
    // format.
    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory( &d3dpp, sizeof( d3dpp ) );
    d3dpp.Windowed = TRUE;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
 
    // Create the Direct3D device. Here we are using the default adapter (most
    // systems only have one, unless they have multiple graphics hardware cards
    // installed) and requesting the HAL (which is saying we want the hardware
    // device rather than a software one). Software vertex processing is 
    // specified since we know it will work on all cards. On cards that support 
    // hardware vertex processing, though, we would see a big performance gain 
    // by specifying hardware vertex processing.
    if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                      D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                      &d3dpp, &g_pd3dDevice ) ) )
    {
        return E_FAIL;
    }
 
    // Device state would normally be set here
 
    return S_OK;
}
VOID Cleanup()
{
    if( g_pd3dDevice != NULL )
        g_pd3dDevice->Release();
 
    if( g_pD3D != NULL )
        g_pD3D->Release();
}
LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch( msg )
    {
        case WM_DESTROY:
            Cleanup();
            PostQuitMessage( 0 );
            return 0;
 
        case WM_PAINT:
            
            ValidateRect( hWnd, NULL );
            return 0;
    }
 
    return DefWindowProc( hWnd, msg, wParam, lParam );
}
 
//-----------------------------------------------------------------------------
// Name: Cleanup()
// Desc: Releases all previously initialized objects
//-----------------------------------------------------------------------------
 
 
INT WINAPI wWinMain( HINSTANCE hInst, HINSTANCE, LPWSTR, INT )
{
    UNREFERENCED_PARAMETER( hInst );
 
    // Register the window class
    WNDCLASSEX wc =
    {
        sizeof( WNDCLASSEX ), CS_CLASSDC, MsgProc, 0L, 0L,
        GetModuleHandle( NULL ), NULL, NULL, NULL, NULL,
        L"D3D Tutorial", NULL
    };
    RegisterClassEx( &wc );
    
    // Create the application's window
    HWND hWnd = CreateWindow( L"D3D Tutorial", L"D3D Tutorial 01: CreateDevice",
                              WS_OVERLAPPEDWINDOW, 200, 100, 800, 600,
                              NULL, NULL, wc.hInstance, NULL );
 
    // Initialize Direct3D
    if( SUCCEEDED( InitD3D( hWnd ) ) )
    {
        // Show the window
        ShowWindow( hWnd, SW_SHOWDEFAULT );
        UpdateWindow( hWnd );
 
        // Enter the message loop
        MSG msg;
        while( GetMessage( &msg, NULL, 0, 0 ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
    }
 
    UnregisterClass( L"D3D Tutorial", wc.hInstance );
    return 0;
}
 
//-----------------------------------------------------------------------------
// Name: class CAllocateHierarchy
// Desc: Custom version of ID3DXAllocateHierarchy with custom methods to create
//       frames and meshcontainers.
//-----------------------------------------------------------------------------
class CAllocateHierarchy: public ID3DXAllocateHierarchy
{
public:
    STDMETHOD(CreateFrame)(THIS_ LPCTSTR Name, LPD3DXFRAME *ppNewFrame);
    STDMETHOD(CreateMeshContainer)(THIS_ LPCTSTR Name, LPD3DXMESHDATA pMeshData,
                            LPD3DXMATERIAL pMaterials, LPD3DXEFFECTINSTANCE pEffectInstances, DWORD NumMaterials, 
                            DWORD *pAdjacency, LPD3DXSKININFO pSkinInfo, 
                            LPD3DXMESHCONTAINER *ppNewMeshContainer);
    STDMETHOD(DestroyFrame)(THIS_ LPD3DXFRAME pFrameToFree);
    STDMETHOD(DestroyMeshContainer)(THIS_ LPD3DXMESHCONTAINER pMeshContainerBase);
    CAllocateHierarchy(CD3DSkinMesh *pSkinMesh, D3DCAPS9 d3dCaps) :m_pSkinMesh(pSkinMesh),m_d3dCaps(d3dCaps) {}
 
public:
    CD3DSkinMesh* m_pSkinMesh;
    D3DCAPS9 m_d3dCaps;
};
 
 
 
 
//-----------------------------------------------------------------------------
// Name: AllocateName()
// Desc: Allocates memory for a string to hold the name of a frame or mesh
//-----------------------------------------------------------------------------
HRESULT AllocateName( LPCTSTR Name, LPTSTR *pNewName )
{
    UINT cbLength;
 
    if (Name != NULL)
    {
        cbLength = lstrlen(Name) + 1;
        *pNewName = new TCHAR[cbLength];
        if (*pNewName == NULL)
            return E_OUTOFMEMORY;
        memcpy(*pNewName, Name, cbLength*sizeof(TCHAR));
    }
    else
    {
        *pNewName = NULL;
    }
 
    return S_OK;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: CAllocateHierarchy::CreateFrame()
// Desc: 
//-----------------------------------------------------------------------------
HRESULT CAllocateHierarchy::CreateFrame(LPCTSTR Name, LPD3DXFRAME *ppNewFrame)
{
    HRESULT hr = S_OK;
    D3DXFRAME_DERIVED *pFrame;
 
    *ppNewFrame = NULL;
 
    pFrame = new D3DXFRAME_DERIVED;
    if (pFrame == NULL)
    {
        hr = E_OUTOFMEMORY;
        goto e_Exit;
    }
 
    hr = AllocateName(Name, &pFrame->Name);
    if (FAILED(hr))
        goto e_Exit;
 
    // initialize other data members of the frame
    D3DXMatrixIdentity(&pFrame->TransformationMatrix);
    D3DXMatrixIdentity(&pFrame->CombinedTransformationMatrix);
 
    pFrame->pMeshContainer = NULL;
    pFrame->pFrameSibling = NULL;
    pFrame->pFrameFirstChild = NULL;
 
    *ppNewFrame = pFrame;
    pFrame = NULL;
e_Exit:
    delete pFrame;
    return hr;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: CAllocateHierarchy::CreateMeshContainer()
// Desc: 
//-----------------------------------------------------------------------------
HRESULT CAllocateHierarchy::CreateMeshContainer(LPCTSTR Name, LPD3DXMESHDATA pMeshData,
                            LPD3DXMATERIAL pMaterials, LPD3DXEFFECTINSTANCE pEffectInstances, DWORD NumMaterials, 
                            DWORD *pAdjacency, LPD3DXSKININFO pSkinInfo, 
                            LPD3DXMESHCONTAINER *ppNewMeshContainer) 
{
    HRESULT hr;
    D3DXMESHCONTAINER_DERIVED *pMeshContainer = NULL;
    UINT NumFaces;
    UINT iMaterial;
    UINT iBone, cBones;
    LPDIRECT3DDEVICE9 pd3dDevice = NULL;
 
    LPD3DXMESH pMesh = NULL;
 
    *ppNewMeshContainer = NULL;
 
    // this sample does not handle patch meshes, so fail when one is found
    if (pMeshData->Type != D3DXMESHTYPE_MESH)
    {
        hr = E_FAIL;
        goto e_Exit;
    }
 
    // get the pMesh interface pointer out of the mesh data structure
    pMesh = pMeshData->pMesh;
 
    // this sample does not FVF compatible meshes, so fail when one is found
    if (pMesh->GetFVF() == 0)
    {
        hr = E_FAIL;
        goto e_Exit;
    }
 
    // allocate the overloaded structure to return as a D3DXMESHCONTAINER
    pMeshContainer = new D3DXMESHCONTAINER_DERIVED;
    if (pMeshContainer == NULL)
    {
        hr = E_OUTOFMEMORY;
        goto e_Exit;
    }
    memset(pMeshContainer, 0, sizeof(D3DXMESHCONTAINER_DERIVED));
 
    // make sure and copy the name.  All memory as input belongs to caller, interfaces can be addref'd though
    hr = AllocateName(Name, &pMeshContainer->Name);
    if (FAILED(hr))
        goto e_Exit;        
 
    pMesh->GetDevice(&pd3dDevice);
    NumFaces = pMesh->GetNumFaces();
 
    // if no normals are in the mesh, add them
    if (!(pMesh->GetFVF() & D3DFVF_NORMAL))
    {
        pMeshContainer->MeshData.Type = D3DXMESHTYPE_MESH;
 
        // clone the mesh to make room for the normals
        hr = pMesh->CloneMeshFVF( pMesh->GetOptions(), 
                                    pMesh->GetFVF() | D3DFVF_NORMAL, 
                                    pd3dDevice, &pMeshContainer->MeshData.pMesh );
        if (FAILED(hr))
            goto e_Exit;
 
        // get the new pMesh pointer back out of the mesh container to use
        // NOTE: we do not release pMesh because we do not have a reference to it yet
        pMesh = pMeshContainer->MeshData.pMesh;
 
        // now generate the normals for the pmesh
        D3DXComputeNormals( pMesh, NULL );
    }
    else  // if no normals, just add a reference to the mesh for the mesh container
    {
        pMeshContainer->MeshData.pMesh = pMesh;
        pMeshContainer->MeshData.Type = D3DXMESHTYPE_MESH;
 
        pMesh->AddRef();
    }
        
    // allocate memory to contain the material information.  This sample uses
    //   the D3D9 materials and texture names instead of the EffectInstance style materials
    pMeshContainer->NumMaterials = max(1, NumMaterials);
    pMeshContainer->pMaterials = new D3DXMATERIAL[pMeshContainer->NumMaterials];
    pMeshContainer->ppTextures = new LPDIRECT3DTEXTURE9[pMeshContainer->NumMaterials];
    pMeshContainer->pAdjacency = new DWORD[NumFaces*3];
    if ((pMeshContainer->pAdjacency == NULL) || (pMeshContainer->pMaterials == NULL))
    {
        hr = E_OUTOFMEMORY;
        goto e_Exit;
    }
 
    memcpy(pMeshContainer->pAdjacency, pAdjacency, sizeof(DWORD) * NumFaces*3);
    memset(pMeshContainer->ppTextures, 0, sizeof(LPDIRECT3DTEXTURE9) * pMeshContainer->NumMaterials);
 
    // if materials provided, copy them
    if (NumMaterials > 0)            
    {
        memcpy(pMeshContainer->pMaterials, pMaterials, sizeof(D3DXMATERIAL) * NumMaterials);
 
        for (iMaterial = 0; iMaterial < NumMaterials; iMaterial++)
        {
            if (pMeshContainer->pMaterials[iMaterial].pTextureFilename != NULL)
            {
                TCHAR strTexturePath[MAX_PATH] = _T("");
                DXUtil_FindMediaFileCb( strTexturePath, sizeof(strTexturePath), pMeshContainer->pMaterials[iMaterial].pTextureFilename );
                if( FAILED( D3DXCreateTextureFromFile( pd3dDevice, strTexturePath, 
                                                        &pMeshContainer->ppTextures[iMaterial] ) ) )
                    pMeshContainer->ppTextures[iMaterial] = NULL;
 
 
                // don't remember a pointer into the dynamic memory, just forget the name after loading
                pMeshContainer->pMaterials[iMaterial].pTextureFilename = NULL;
            }
        }
    }
    else // if no materials provided, use a default one
    {
        pMeshContainer->pMaterials[0].pTextureFilename = NULL;
        memset(&pMeshContainer->pMaterials[0].MatD3D, 0, sizeof(D3DMATERIAL9));
        pMeshContainer->pMaterials[0].MatD3D.Diffuse.r = 0.5f;
        pMeshContainer->pMaterials[0].MatD3D.Diffuse.g = 0.5f;
        pMeshContainer->pMaterials[0].MatD3D.Diffuse.b = 0.5f;
        pMeshContainer->pMaterials[0].MatD3D.Specular = pMeshContainer->pMaterials[0].MatD3D.Diffuse;
    }
 
    // if there is skinning information, save off the required data and then setup for HW skinning
    if (pSkinInfo != NULL)
    {
        // first save off the SkinInfo and original mesh data
        pMeshContainer->pSkinInfo = pSkinInfo;
        pSkinInfo->AddRef();
 
        pMeshContainer->pOrigMesh = pMesh;
        pMesh->AddRef();
 
        // Will need an array of offset matrices to move the vertices from the figure space to the bone's space
        cBones = pSkinInfo->GetNumBones();
        pMeshContainer->pBoneOffsetMatrices = new D3DXMATRIX[cBones];
        if (pMeshContainer->pBoneOffsetMatrices == NULL)
        {
            hr = E_OUTOFMEMORY;
            goto e_Exit;
        }
 
        // get each of the bone offset matrices so that we don't need to get them later
        for (iBone = 0; iBone < cBones; iBone++)
        {
            pMeshContainer->pBoneOffsetMatrices[iBone] = *(pMeshContainer->pSkinInfo->GetBoneOffsetMatrix(iBone));
        }
 
        // GenerateSkinnedMesh will take the general skinning information and transform it to a HW friendly version
        hr = m_pSkinMesh->GenerateSkinnedMesh(pMeshContainer,
                                              m_d3dCaps,pd3dDevice,
                                              m_pSkinMesh->getSkinningMethod());
        if (FAILED(hr))
            goto e_Exit;
    }
 
    *ppNewMeshContainer = pMeshContainer;
    pMeshContainer = NULL;
e_Exit:
    SAFE_RELEASE(pd3dDevice);
 
    // call Destroy function to properly clean up the memory allocated 
    if (pMeshContainer != NULL)
    {
        DestroyMeshContainer(pMeshContainer);
    }
 
    return hr;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: CAllocateHierarchy::DestroyFrame()
// Desc: 
//-----------------------------------------------------------------------------
HRESULT CAllocateHierarchy::DestroyFrame(LPD3DXFRAME pFrameToFree) 
{
    SAFE_DELETE_ARRAY( pFrameToFree->Name );
    SAFE_DELETE( pFrameToFree );
    return S_OK; 
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: CAllocateHierarchy::DestroyMeshContainer()
// Desc: 
//-----------------------------------------------------------------------------
HRESULT CAllocateHierarchy::DestroyMeshContainer(LPD3DXMESHCONTAINER pMeshContainerBase)
{
    UINT iMaterial;
    D3DXMESHCONTAINER_DERIVED *pMeshContainer = (D3DXMESHCONTAINER_DERIVED*)pMeshContainerBase;
 
    SAFE_DELETE_ARRAY( pMeshContainer->Name );
    SAFE_DELETE_ARRAY( pMeshContainer->pAdjacency );
    SAFE_DELETE_ARRAY( pMeshContainer->pMaterials );
    SAFE_DELETE_ARRAY( pMeshContainer->pBoneOffsetMatrices );
 
    // release all the allocated textures
    if (pMeshContainer->ppTextures != NULL)
    {
        for (iMaterial = 0; iMaterial < pMeshContainer->NumMaterials; iMaterial++)
        {
            SAFE_RELEASE( pMeshContainer->ppTextures[iMaterial] );
        }
    }
 
    SAFE_DELETE_ARRAY( pMeshContainer->ppTextures );
    SAFE_DELETE_ARRAY( pMeshContainer->ppBoneMatrixPtrs );
    SAFE_RELEASE( pMeshContainer->pBoneCombinationBuf );
    SAFE_RELEASE( pMeshContainer->MeshData.pMesh );
    SAFE_RELEASE( pMeshContainer->pSkinInfo );
    SAFE_RELEASE( pMeshContainer->pOrigMesh );
    SAFE_DELETE( pMeshContainer );
    return S_OK;
}
 
 
 
 
 
//-----------------------------------------------------------------------------
// Name: CD3DSkinMesh()
// Desc: skin mesh character constructor. Sets attributes for the skn mesh.
//-----------------------------------------------------------------------------
CD3DSkinMesh::CD3DSkinMesh()
{
    m_pAnimController = NULL;
    m_pFrameRoot = NULL;
 
    m_SkinningMethod = D3DNONINDEXED;
    m_pBoneMatrices = NULL;
    m_NumBoneMatricesMax = 0;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: GenerateSkinnedMesh()
// Desc: Called either by CreateMeshContainer when loading a skin mesh, or when 
//       changing methods.  This function uses the pSkinInfo of the mesh 
//       container to generate the desired drawable mesh and bone combination 
//       table.
//-----------------------------------------------------------------------------
HRESULT CD3DSkinMesh::GenerateSkinnedMesh(D3DXMESHCONTAINER_DERIVED *pMeshContainer,
                                          D3DCAPS9                   m_d3dCaps,           
                                          LPDIRECT3DDEVICE9          m_pd3dDevice,   
                                          METHOD                     m_SkinningMethod)
{
    HRESULT hr = S_OK;
 
    if (pMeshContainer->pSkinInfo == NULL)
        return hr;
 
    SAFE_RELEASE( pMeshContainer->MeshData.pMesh );
    SAFE_RELEASE( pMeshContainer->pBoneCombinationBuf );
 
    // if non-indexed skinning mode selected, use ConvertToBlendedMesh to generate drawable mesh
    if (m_SkinningMethod == D3DNONINDEXED)
    {
 
        hr = pMeshContainer->pSkinInfo->ConvertToBlendedMesh
                                   (
                                       pMeshContainer->pOrigMesh,
                                       D3DXMESH_MANAGED|D3DXMESHOPT_VERTEXCACHE, 
                                       pMeshContainer->pAdjacency, 
                                       NULL, NULL, NULL, 
                                       &pMeshContainer->NumInfl,
                                       &pMeshContainer->NumAttributeGroups, 
                                       &pMeshContainer->pBoneCombinationBuf, 
                                       &pMeshContainer->MeshData.pMesh
                                   );
        if (FAILED(hr))
            goto e_Exit;
 
 
        /* If the device can only do 2 matrix blends, ConvertToBlendedMesh cannot approximate all meshes to it
           Thus we split the mesh in two parts: The part that uses at most 2 matrices and the rest. The first is
           drawn using the device's HW vertex processing and the rest is drawn using SW vertex processing. */
        LPD3DXBONECOMBINATION rgBoneCombinations  = reinterpret_cast<LPD3DXBONECOMBINATION>(pMeshContainer->pBoneCombinationBuf->GetBufferPointer());
 
        // look for any set of bone combinations that do not fit the caps
        for (pMeshContainer->iAttributeSW = 0; pMeshContainer->iAttributeSW < pMeshContainer->NumAttributeGroups; pMeshContainer->iAttributeSW++)
        {
            DWORD cInfl   = 0;
 
            for (DWORD iInfl = 0; iInfl < pMeshContainer->NumInfl; iInfl++)
            {
                if (rgBoneCombinations[pMeshContainer->iAttributeSW].BoneId[iInfl] != UINT_MAX)
                {
                    ++cInfl;
                }
            }
 
            if (cInfl > m_d3dCaps.MaxVertexBlendMatrices)
            {
                break;
            }
        }
 
        // if there is both HW and SW, add the Software Processing flag
        if (pMeshContainer->iAttributeSW < pMeshContainer->NumAttributeGroups)
        {
            LPD3DXMESH pMeshTmp;
 
            hr = pMeshContainer->MeshData.pMesh->CloneMeshFVF(D3DXMESH_SOFTWAREPROCESSING|pMeshContainer->MeshData.pMesh->GetOptions(), 
                                                pMeshContainer->MeshData.pMesh->GetFVF(),
                                                m_pd3dDevice, &pMeshTmp);
            if (FAILED(hr))
            {
                goto e_Exit;
            }
 
            pMeshContainer->MeshData.pMesh->Release();
            pMeshContainer->MeshData.pMesh = pMeshTmp;
            pMeshTmp = NULL;
        }
    }
    // if indexed skinning mode selected, use ConvertToIndexedsBlendedMesh to generate drawable mesh
    else if (m_SkinningMethod == D3DINDEXED)
    {
        DWORD NumMaxFaceInfl;
        DWORD Flags = D3DXMESHOPT_VERTEXCACHE;
 
        LPDIRECT3DINDEXBUFFER9 pIB;
        hr = pMeshContainer->pOrigMesh->GetIndexBuffer(&pIB);
        if (FAILED(hr))
            goto e_Exit;
 
        hr = pMeshContainer->pSkinInfo->GetMaxFaceInfluences(pIB, pMeshContainer->pOrigMesh->GetNumFaces(), &NumMaxFaceInfl);
        pIB->Release();
        if (FAILED(hr))
            goto e_Exit;
 
        // 12 entry palette guarantees that any triangle (4 independent influences per vertex of a tri)
        // can be handled
        NumMaxFaceInfl = min(NumMaxFaceInfl, 12);
 
        if (m_d3dCaps.MaxVertexBlendMatrixIndex + 1 < NumMaxFaceInfl)
        {
            // HW does not support indexed vertex blending. Use SW instead
            pMeshContainer->NumPaletteEntries = min(256, pMeshContainer->pSkinInfo->GetNumBones());
            pMeshContainer->UseSoftwareVP = true;
            Flags |= D3DXMESH_SYSTEMMEM;
        }
        else
        {
            // using hardware - determine palette size from caps and number of bones
            // If normals are present in the vertex data that needs to be blended for lighting, then 
            // the number of matrices is half the number specified by MaxVertexBlendMatrixIndex.
            pMeshContainer->NumPaletteEntries = min( ( m_d3dCaps.MaxVertexBlendMatrixIndex + 1 ) / 2, 
                                                     pMeshContainer->pSkinInfo->GetNumBones() );
            pMeshContainer->UseSoftwareVP = false;
            Flags |= D3DXMESH_MANAGED;
        }
 
        hr = pMeshContainer->pSkinInfo->ConvertToIndexedBlendedMesh
                                                (
                                                pMeshContainer->pOrigMesh,
                                                Flags, 
                                                pMeshContainer->NumPaletteEntries, 
                                                pMeshContainer->pAdjacency, 
                                                NULL, NULL, NULL, 
                                                &pMeshContainer->NumInfl,
                                                &pMeshContainer->NumAttributeGroups, 
                                                &pMeshContainer->pBoneCombinationBuf, 
                                                &pMeshContainer->MeshData.pMesh);
        if (FAILED(hr))
            goto e_Exit;
    }
    // if vertex shader indexed skinning mode selected, use ConvertToIndexedsBlendedMesh to generate drawable mesh
    else if ((m_SkinningMethod == D3DINDEXEDVS) || (m_SkinningMethod == D3DINDEXEDHLSLVS))
    {
        // Get palette size
        // First 9 constants are used for other data.  Each 4x3 matrix takes up 3 constants.
        // (96 - 9) /3 i.e. Maximum constant count - used constants 
        UINT MaxMatrices = 26; 
        pMeshContainer->NumPaletteEntries = min(MaxMatrices, pMeshContainer->pSkinInfo->GetNumBones());
 
        DWORD Flags = D3DXMESHOPT_VERTEXCACHE;
        if (m_d3dCaps.VertexShaderVersion >= D3DVS_VERSION(1, 1))
        {
            pMeshContainer->UseSoftwareVP = false;
            Flags |= D3DXMESH_MANAGED;
        }
        else
        {
            pMeshContainer->UseSoftwareVP = true;
            Flags |= D3DXMESH_SYSTEMMEM;
        }
 
        SAFE_RELEASE(pMeshContainer->MeshData.pMesh);
 
        hr = pMeshContainer->pSkinInfo->ConvertToIndexedBlendedMesh
                                                (
                                                pMeshContainer->pOrigMesh,
                                                Flags, 
                                                pMeshContainer->NumPaletteEntries, 
                                                pMeshContainer->pAdjacency, 
                                                NULL, NULL, NULL,             
                                                &pMeshContainer->NumInfl,
                                                &pMeshContainer->NumAttributeGroups, 
                                                &pMeshContainer->pBoneCombinationBuf, 
                                                &pMeshContainer->MeshData.pMesh);
        if (FAILED(hr))
            goto e_Exit;
 
 
        // FVF has to match our declarator. Vertex shaders are not as forgiving as FF pipeline
        DWORD NewFVF = (pMeshContainer->MeshData.pMesh->GetFVF() & D3DFVF_POSITION_MASK) | D3DFVF_NORMAL | D3DFVF_TEX1 | D3DFVF_LASTBETA_UBYTE4;
        if (NewFVF != pMeshContainer->MeshData.pMesh->GetFVF())
        {
            LPD3DXMESH pMesh;
            hr = pMeshContainer->MeshData.pMesh->CloneMeshFVF(pMeshContainer->MeshData.pMesh->GetOptions(), NewFVF, m_pd3dDevice, &pMesh);
            if (!FAILED(hr))
            {
                pMeshContainer->MeshData.pMesh->Release();
                pMeshContainer->MeshData.pMesh = pMesh;
                pMesh = NULL;
            }
        }
 
        D3DVERTEXELEMENT9 pDecl[MAX_FVF_DECL_SIZE];
        LPD3DVERTEXELEMENT9 pDeclCur;
        hr = pMeshContainer->MeshData.pMesh->GetDeclaration(pDecl);
        if (FAILED(hr))
            goto e_Exit;
 
        // the vertex shader is expecting to interpret the UBYTE4 as a D3DCOLOR, so update the type 
        //   NOTE: this cannot be done with CloneMesh, that would convert the UBYTE4 data to float and then to D3DCOLOR
        //          this is more of a "cast" operation
        pDeclCur = pDecl;
        while (pDeclCur->Stream != 0xff)
        {
            if ((pDeclCur->Usage == D3DDECLUSAGE_BLENDINDICES) && (pDeclCur->UsageIndex == 0))
                pDeclCur->Type = D3DDECLTYPE_D3DCOLOR;
            pDeclCur++;
        }
 
        hr = pMeshContainer->MeshData.pMesh->UpdateSemantics(pDecl);
        if (FAILED(hr))
            goto e_Exit;
 
        // allocate a buffer for bone matrices, but only if another mesh has not allocated one of the same size or larger
        if (m_NumBoneMatricesMax < pMeshContainer->pSkinInfo->GetNumBones())
        {
            m_NumBoneMatricesMax = pMeshContainer->pSkinInfo->GetNumBones();
 
            // Allocate space for blend matrices
            delete []m_pBoneMatrices; 
            m_pBoneMatrices  = new D3DXMATRIXA16[m_NumBoneMatricesMax];
            if (m_pBoneMatrices == NULL)
            {
                hr = E_OUTOFMEMORY;
                goto e_Exit;
            }
        }
 
    }
    // if software skinning selected, use GenerateSkinnedMesh to create a mesh that can be used with UpdateSkinnedMesh
    else if (m_SkinningMethod == SOFTWARE)
    {
        hr = pMeshContainer->pOrigMesh->CloneMeshFVF(D3DXMESH_MANAGED, pMeshContainer->pOrigMesh->GetFVF(),
                                              m_pd3dDevice, &pMeshContainer->MeshData.pMesh);
        if (FAILED(hr))
            goto e_Exit;
 
        hr = pMeshContainer->MeshData.pMesh->GetAttributeTable(NULL, &pMeshContainer->NumAttributeGroups);
        if (FAILED(hr))
            goto e_Exit;
 
        delete[] pMeshContainer->pAttributeTable;
        pMeshContainer->pAttributeTable  = new D3DXATTRIBUTERANGE[pMeshContainer->NumAttributeGroups];
        if (pMeshContainer->pAttributeTable == NULL)
        {
            hr = E_OUTOFMEMORY;
            goto e_Exit;
        }
 
        hr = pMeshContainer->MeshData.pMesh->GetAttributeTable(pMeshContainer->pAttributeTable, NULL);
        if (FAILED(hr))
            goto e_Exit;
 
        // allocate a buffer for bone matrices, but only if another mesh has not allocated one of the same size or larger
        if (m_NumBoneMatricesMax < pMeshContainer->pSkinInfo->GetNumBones())
        {
            m_NumBoneMatricesMax = pMeshContainer->pSkinInfo->GetNumBones();
 
            // Allocate space for blend matrices
            delete []m_pBoneMatrices; 
            m_pBoneMatrices  = new D3DXMATRIXA16[m_NumBoneMatricesMax];
            if (m_pBoneMatrices == NULL)
            {
                hr = E_OUTOFMEMORY;
                goto e_Exit;
            }
        }
    }
    else  // invalid m_SkinningMethod value
    {        
        // return failure due to invalid skinning method value
        hr = E_INVALIDARG;
        goto e_Exit;
    }
 
e_Exit:
    return hr;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: DrawMeshContainer()
// Desc: Called to render a mesh in the hierarchy
//-----------------------------------------------------------------------------
void CD3DSkinMesh::DrawMeshContainer(LPD3DXMESHCONTAINER pMeshContainerBase, LPD3DXFRAME pFrameBase,
                                     D3DCAPS9          m_d3dCaps,
                                     LPDIRECT3DDEVICE9 m_pd3dDevice,
                                     D3DXMATRIXA16     m_matView )
{
    D3DXMESHCONTAINER_DERIVED *pMeshContainer = (D3DXMESHCONTAINER_DERIVED*)pMeshContainerBase;
    D3DXFRAME_DERIVED *pFrame = (D3DXFRAME_DERIVED*)pFrameBase;
    UINT iMaterial;
    UINT NumBlend;
    UINT iAttrib;
    DWORD AttribIdPrev;
    LPD3DXBONECOMBINATION pBoneComb;
 
    UINT iMatrixIndex;
    UINT iPaletteEntry;
    D3DXMATRIXA16 matTemp;
 
    // first check for skinning
    if (pMeshContainer->pSkinInfo != NULL)
    {
        if (m_SkinningMethod == D3DNONINDEXED)
        {
            AttribIdPrev = UNUSED32; 
            pBoneComb = reinterpret_cast<LPD3DXBONECOMBINATION>(pMeshContainer->pBoneCombinationBuf->GetBufferPointer());
 
            // Draw using default vtx processing of the device (typically HW)
            for (iAttrib = 0; iAttrib < pMeshContainer->NumAttributeGroups; iAttrib++)
            {
                NumBlend = 0;
                for (DWORD i = 0; i < pMeshContainer->NumInfl; ++i)
                {
                    if (pBoneComb[iAttrib].BoneId[i] != UINT_MAX)
                    {
                        NumBlend = i;
                    }
                }
 
                if (m_d3dCaps.MaxVertexBlendMatrices >= NumBlend + 1)
                {
                    // first calculate the world matrices for the current set of blend weights and get the accurate count of the number of blends
                    for (DWORD i = 0; i < pMeshContainer->NumInfl; ++i)
                    {
                        iMatrixIndex = pBoneComb[iAttrib].BoneId[i];
                        if (iMatrixIndex != UINT_MAX)
                        {
                            D3DXMatrixMultiply( &matTemp, &pMeshContainer->pBoneOffsetMatrices[iMatrixIndex], pMeshContainer->ppBoneMatrixPtrs[iMatrixIndex] );
                            m_pd3dDevice->SetTransform( D3DTS_WORLDMATRIX( i ), &matTemp );
                        }
                    }
 
                    m_pd3dDevice->SetRenderState(D3DRS_VERTEXBLEND, NumBlend);
 
                    // lookup the material used for this subset of faces
                    if ((AttribIdPrev != pBoneComb[iAttrib].AttribId) || (AttribIdPrev == UNUSED32))
                    {
                        m_pd3dDevice->SetMaterial( &pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D );
                        m_pd3dDevice->SetTexture( 0, pMeshContainer->ppTextures[pBoneComb[iAttrib].AttribId] );
                        AttribIdPrev = pBoneComb[iAttrib].AttribId;
                    }
 
                    // draw the subset now that the correct material and matrices are loaded
                    pMeshContainer->MeshData.pMesh->DrawSubset(iAttrib);
                }
            }
 
            // If necessary, draw parts that HW could not handle using SW
            if (pMeshContainer->iAttributeSW < pMeshContainer->NumAttributeGroups)
            {
                AttribIdPrev = UNUSED32; 
                m_pd3dDevice->SetSoftwareVertexProcessing(TRUE);
                for (iAttrib = pMeshContainer->iAttributeSW; iAttrib < pMeshContainer->NumAttributeGroups; iAttrib++)
                {
                    NumBlend = 0;
                    for (DWORD i = 0; i < pMeshContainer->NumInfl; ++i)
                    {
                        if (pBoneComb[iAttrib].BoneId[i] != UINT_MAX)
                        {
                            NumBlend = i;
                        }
                    }
 
                    if (m_d3dCaps.MaxVertexBlendMatrices < NumBlend + 1)
                    {
                        // first calculate the world matrices for the current set of blend weights and get the accurate count of the number of blends
                        for (DWORD i = 0; i < pMeshContainer->NumInfl; ++i)
                        {
                            iMatrixIndex = pBoneComb[iAttrib].BoneId[i];
                            if (iMatrixIndex != UINT_MAX)
                            {
                                D3DXMatrixMultiply( &matTemp, &pMeshContainer->pBoneOffsetMatrices[iMatrixIndex], pMeshContainer->ppBoneMatrixPtrs[iMatrixIndex] );
                                m_pd3dDevice->SetTransform( D3DTS_WORLDMATRIX( i ), &matTemp );
                            }
                        }
 
                        m_pd3dDevice->SetRenderState(D3DRS_VERTEXBLEND, NumBlend);
 
                        // lookup the material used for this subset of faces
                        if ((AttribIdPrev != pBoneComb[iAttrib].AttribId) || (AttribIdPrev == UNUSED32))
                        {
                            m_pd3dDevice->SetMaterial( &pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D );
                            m_pd3dDevice->SetTexture( 0, pMeshContainer->ppTextures[pBoneComb[iAttrib].AttribId] );
                            AttribIdPrev = pBoneComb[iAttrib].AttribId;
                        }
 
                        // draw the subset now that the correct material and matrices are loaded
                        pMeshContainer->MeshData.pMesh->DrawSubset(iAttrib);
                    }
                }
                m_pd3dDevice->SetSoftwareVertexProcessing(FALSE);
            }
 
            m_pd3dDevice->SetRenderState(D3DRS_VERTEXBLEND, 0);
        }
        else if (m_SkinningMethod == D3DINDEXED)
        {
            // if hw doesn't support indexed vertex processing, switch to software vertex processing
            if (pMeshContainer->UseSoftwareVP)
            {
                m_pd3dDevice->SetSoftwareVertexProcessing(TRUE);
            }
 
            // set the number of vertex blend indices to be blended
            if (pMeshContainer->NumInfl == 1)
                m_pd3dDevice->SetRenderState(D3DRS_VERTEXBLEND, D3DVBF_0WEIGHTS);
            else
                m_pd3dDevice->SetRenderState(D3DRS_VERTEXBLEND, pMeshContainer->NumInfl - 1);
 
            if (pMeshContainer->NumInfl)
                m_pd3dDevice->SetRenderState(D3DRS_INDEXEDVERTEXBLENDENABLE, TRUE);
 
            // for each attribute group in the mesh, calculate the set of matrices in the palette and then draw the mesh subset
            pBoneComb = reinterpret_cast<LPD3DXBONECOMBINATION>(pMeshContainer->pBoneCombinationBuf->GetBufferPointer());
            for (iAttrib = 0; iAttrib < pMeshContainer->NumAttributeGroups; iAttrib++)
            {
                // first calculate all the world matrices
                for (iPaletteEntry = 0; iPaletteEntry < pMeshContainer->NumPaletteEntries; ++iPaletteEntry)
                {
                    iMatrixIndex = pBoneComb[iAttrib].BoneId[iPaletteEntry];
                    if (iMatrixIndex != UINT_MAX)
                    {
                        D3DXMatrixMultiply( &matTemp, &pMeshContainer->pBoneOffsetMatrices[iMatrixIndex], pMeshContainer->ppBoneMatrixPtrs[iMatrixIndex] );
                        m_pd3dDevice->SetTransform( D3DTS_WORLDMATRIX( iPaletteEntry ), &matTemp );
                    }
                }
                
                // setup the material of the mesh subset - REMEMBER to use the original pre-skinning attribute id to get the correct material id
                m_pd3dDevice->SetMaterial( &pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D );
                m_pd3dDevice->SetTexture( 0, pMeshContainer->ppTextures[pBoneComb[iAttrib].AttribId] );
 
                // finally draw the subset with the current world matrix palette and material state
                pMeshContainer->MeshData.pMesh->DrawSubset( iAttrib );
            }
 
            // reset blending state
            m_pd3dDevice->SetRenderState(D3DRS_INDEXEDVERTEXBLENDENABLE, FALSE);
            m_pd3dDevice->SetRenderState(D3DRS_VERTEXBLEND, 0);
 
            // remember to reset back to hw vertex processing if software was required
            if (pMeshContainer->UseSoftwareVP)
            {
                m_pd3dDevice->SetSoftwareVertexProcessing(FALSE);
            }
        }
        else if (m_SkinningMethod == D3DINDEXEDVS) 
        {
            // Use COLOR instead of UBYTE4 since Geforce3 does not support it
            // vConst.w should be 3, but due to COLOR/UBYTE4 issue, mul by 255 and add epsilon
            D3DXVECTOR4 vConst( 1.0f, 0.0f, 0.0f, 765.01f );
 
            if (pMeshContainer->UseSoftwareVP)
            {
                m_pd3dDevice->SetSoftwareVertexProcessing(TRUE);
            }
 
            m_pd3dDevice->SetVertexShader(m_pIndexedVertexShader[pMeshContainer->NumInfl - 1]);
 
            pBoneComb = reinterpret_cast<LPD3DXBONECOMBINATION>(pMeshContainer->pBoneCombinationBuf->GetBufferPointer());
            for (iAttrib = 0; iAttrib < pMeshContainer->NumAttributeGroups; iAttrib++)
            {
                // first calculate all the world matrices
                for (iPaletteEntry = 0; iPaletteEntry < pMeshContainer->NumPaletteEntries; ++iPaletteEntry)
                {
                    iMatrixIndex = pBoneComb[iAttrib].BoneId[iPaletteEntry];
                    if (iMatrixIndex != UINT_MAX)
                    {
                        D3DXMatrixMultiply(&matTemp, &pMeshContainer->pBoneOffsetMatrices[iMatrixIndex], pMeshContainer->ppBoneMatrixPtrs[iMatrixIndex]);
                        D3DXMatrixMultiplyTranspose(&matTemp, &matTemp, &m_matView);
                        m_pd3dDevice->SetVertexShaderConstantF(iPaletteEntry*3 + 9, (float*)&matTemp, 3);
                    }
                }
 
                // Sum of all ambient and emissive contribution
                D3DXCOLOR color1(pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Ambient);
                D3DXCOLOR color2(.25, .25, .25, 1.0);
                D3DXCOLOR ambEmm;
                D3DXColorModulate(&ambEmm, &color1, &color2);
                ambEmm += D3DXCOLOR(pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Emissive);
 
                // set material color properties 
                m_pd3dDevice->SetVertexShaderConstantF(8, (float*)&(pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Diffuse), 1);
                m_pd3dDevice->SetVertexShaderConstantF(7, (float*)&ambEmm, 1);
                vConst.y = pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Power;
                m_pd3dDevice->SetVertexShaderConstantF(0, (float*)&vConst, 1);
 
                m_pd3dDevice->SetTexture(0, pMeshContainer->ppTextures[pBoneComb[iAttrib].AttribId]);
 
                // finally draw the subset with the current world matrix palette and material state
                pMeshContainer->MeshData.pMesh->DrawSubset( iAttrib );
                
            }
 
            // remember to reset back to hw vertex processing if software was required
            if (pMeshContainer->UseSoftwareVP)
            {
                m_pd3dDevice->SetSoftwareVertexProcessing(FALSE);
            }
            m_pd3dDevice->SetVertexShader(NULL);
 
        }
        else if (m_SkinningMethod == D3DINDEXEDHLSLVS) 
        {
            if (pMeshContainer->UseSoftwareVP)
            {
                m_pd3dDevice->SetSoftwareVertexProcessing(TRUE);
            }
 
            pBoneComb = reinterpret_cast<LPD3DXBONECOMBINATION>(pMeshContainer->pBoneCombinationBuf->GetBufferPointer());
            for (iAttrib = 0; iAttrib < pMeshContainer->NumAttributeGroups; iAttrib++)
            { 
                // first calculate all the world matrices
                for (iPaletteEntry = 0; iPaletteEntry < pMeshContainer->NumPaletteEntries; ++iPaletteEntry)
                {
                    iMatrixIndex = pBoneComb[iAttrib].BoneId[iPaletteEntry];
                    if (iMatrixIndex != UINT_MAX)
                    {
                        D3DXMatrixMultiply(&matTemp, &pMeshContainer->pBoneOffsetMatrices[iMatrixIndex], pMeshContainer->ppBoneMatrixPtrs[iMatrixIndex]);
                        D3DXMatrixMultiply(&m_pBoneMatrices[iPaletteEntry], &matTemp, &m_matView);
                    }
                }
                m_pEffect->SetMatrixArray( "mWorldMatrixArray", m_pBoneMatrices, pMeshContainer->NumPaletteEntries);
 
                // Sum of all ambient and emissive contribution
                D3DXCOLOR color1(pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Ambient);
                D3DXCOLOR color2(.25, .25, .25, 1.0);
                D3DXCOLOR ambEmm;
                D3DXColorModulate(&ambEmm, &color1, &color2);
                ambEmm += D3DXCOLOR(pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Emissive);
 
                // set material color properties 
                m_pEffect->SetVector("MaterialDiffuse", (D3DXVECTOR4*)&(pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Diffuse));
                m_pEffect->SetVector("MaterialAmbient", (D3DXVECTOR4*)&ambEmm);
 
                // setup the material of the mesh subset - REMEMBER to use the original pre-skinning attribute id to get the correct material id
                m_pd3dDevice->SetTexture( 0, pMeshContainer->ppTextures[pBoneComb[iAttrib].AttribId] );
 
                // Set CurNumBones to select the correct vertex shader for the number of bones
                m_pEffect->SetInt( "CurNumBones", pMeshContainer->NumInfl -1);
 
                // Start the effect now all parameters have been updated
                UINT numPasses;
                m_pEffect->Begin( &numPasses, D3DXFX_DONOTSAVESTATE );
                for( UINT iPass = 0; iPass < numPasses; iPass++ )
                {
                    m_pEffect->Pass( iPass );
                    // draw the subset with the current world matrix palette and material state
                    pMeshContainer->MeshData.pMesh->DrawSubset( iAttrib );
                }
 
                m_pEffect->End();        
 
                m_pd3dDevice->SetVertexShader(NULL);
            }
 
            // remember to reset back to hw vertex processing if software was required
            if (pMeshContainer->UseSoftwareVP)
            {
                m_pd3dDevice->SetSoftwareVertexProcessing(FALSE);
            }
        }
        else if (m_SkinningMethod == SOFTWARE)
        {
            D3DXMATRIX  Identity;
            DWORD       cBones  = pMeshContainer->pSkinInfo->GetNumBones();
            DWORD       iBone;
            PBYTE       pbVerticesSrc;
            PBYTE       pbVerticesDest;
 
            // set up bone transforms
            for (iBone = 0; iBone < cBones; ++iBone)
            {
                D3DXMatrixMultiply
                (
                    &m_pBoneMatrices[iBone],                 // output
                    &pMeshContainer->pBoneOffsetMatrices[iBone], 
                    pMeshContainer->ppBoneMatrixPtrs[iBone]
                );
            }
 
            // set world transform
            D3DXMatrixIdentity(&Identity);
            m_pd3dDevice->SetTransform(D3DTS_WORLD, &Identity);
 
            pMeshContainer->pOrigMesh->LockVertexBuffer(D3DLOCK_READONLY, (LPVOID*)&pbVerticesSrc);
            pMeshContainer->MeshData.pMesh->LockVertexBuffer(0, (LPVOID*)&pbVerticesDest);
 
            // generate skinned mesh
            pMeshContainer->pSkinInfo->UpdateSkinnedMesh(m_pBoneMatrices, NULL, pbVerticesSrc, pbVerticesDest);
 
            pMeshContainer->pOrigMesh->UnlockVertexBuffer();
            pMeshContainer->MeshData.pMesh->UnlockVertexBuffer();
 
            for (iAttrib = 0; iAttrib < pMeshContainer->NumAttributeGroups; iAttrib++)
            {
                m_pd3dDevice->SetMaterial(&(pMeshContainer->pMaterials[pMeshContainer->pAttributeTable[iAttrib].AttribId].MatD3D));
                m_pd3dDevice->SetTexture(0, pMeshContainer->ppTextures[pMeshContainer->pAttributeTable[iAttrib].AttribId]);
                pMeshContainer->MeshData.pMesh->DrawSubset(pMeshContainer->pAttributeTable[iAttrib].AttribId);
            }
        }
        else // bug out as unsupported mode
        {
            return;
        }
    }
    else  // standard mesh, just draw it after setting material properties
    {
        m_pd3dDevice->SetTransform(D3DTS_WORLD, &pFrame->CombinedTransformationMatrix);
 
        for (iMaterial = 0; iMaterial < pMeshContainer->NumMaterials; iMaterial++)
        {
            m_pd3dDevice->SetMaterial( &pMeshContainer->pMaterials[iMaterial].MatD3D );
            m_pd3dDevice->SetTexture( 0, pMeshContainer->ppTextures[iMaterial] );
            pMeshContainer->MeshData.pMesh->DrawSubset(iMaterial);
        }
    }
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: DrawFrame()
// Desc: Called to render a frame in the hierarchy
//-----------------------------------------------------------------------------
void CD3DSkinMesh::DrawFrame(LPD3DXFRAME pFrame,
                    D3DCAPS9          m_d3dCaps,
                    LPDIRECT3DDEVICE9 m_pd3dDevice,
                    D3DXMATRIXA16     m_matView)
{
    LPD3DXMESHCONTAINER pMeshContainer;
 
    pMeshContainer = pFrame->pMeshContainer;
    while (pMeshContainer != NULL)
    {
        DrawMeshContainer(pMeshContainer, pFrame, 
                          m_d3dCaps, m_pd3dDevice, m_matView);
 
        pMeshContainer = pMeshContainer->pNextMeshContainer;
    }
 
    if (pFrame->pFrameSibling != NULL)
    {
        DrawFrame(pFrame->pFrameSibling, 
                          m_d3dCaps, m_pd3dDevice, m_matView);
    }
 
    if (pFrame->pFrameFirstChild != NULL)
    {
        DrawFrame(pFrame->pFrameFirstChild, 
                          m_d3dCaps, m_pd3dDevice, m_matView);
    }
}
//-----------------------------------------------------------------------------
// Name: SetupBoneMatrixPointersOnMesh()
// Desc: Called to setup the pointers for a given bone to its transformation matrix
//-----------------------------------------------------------------------------
HRESULT CD3DSkinMesh::SetupBoneMatrixPointersOnMesh(LPD3DXMESHCONTAINER pMeshContainerBase)
{
    UINT iBone, cBones;
    D3DXFRAME_DERIVED *pFrame;
 
    D3DXMESHCONTAINER_DERIVED *pMeshContainer = (D3DXMESHCONTAINER_DERIVED*)pMeshContainerBase;
 
    // if there is a skinmesh, then setup the bone matrices
    if (pMeshContainer->pSkinInfo != NULL)
    {
        cBones = pMeshContainer->pSkinInfo->GetNumBones();
 
        pMeshContainer->ppBoneMatrixPtrs = new D3DXMATRIX*[cBones];
        if (pMeshContainer->ppBoneMatrixPtrs == NULL)
            return E_OUTOFMEMORY;
 
        for (iBone = 0; iBone < cBones; iBone++)
        {
            pFrame = (D3DXFRAME_DERIVED*)D3DXFrameFind(m_pFrameRoot, pMeshContainer->pSkinInfo->GetBoneName(iBone));
            if (pFrame == NULL)
                return E_FAIL;
 
            pMeshContainer->ppBoneMatrixPtrs[iBone] = &pFrame->CombinedTransformationMatrix;
        }
    }
 
    return S_OK;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: SetupBoneMatrixPointers()
// Desc: Called to setup the pointers for a given bone to its transformation matrix
//-----------------------------------------------------------------------------
HRESULT CD3DSkinMesh::SetupBoneMatrixPointers(LPD3DXFRAME pFrame)
{
    HRESULT hr;
 
    if (pFrame->pMeshContainer != NULL)
    {
        hr = SetupBoneMatrixPointersOnMesh(pFrame->pMeshContainer);
        if (FAILED(hr))
            return hr;
    }
 
    if (pFrame->pFrameSibling != NULL)
    {
        hr = SetupBoneMatrixPointers(pFrame->pFrameSibling);
        if (FAILED(hr))
            return hr;
    }
 
    if (pFrame->pFrameFirstChild != NULL)
    {
        hr = SetupBoneMatrixPointers(pFrame->pFrameFirstChild);
        if (FAILED(hr))
            return hr;
    }
 
    return S_OK;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: DrawFrame()
// Desc: Called to render a frame in the hierarchy
//-----------------------------------------------------------------------------
void CD3DSkinMesh::UpdateFrameMatrices(LPD3DXFRAME pFrameBase, LPD3DXMATRIX pParentMatrix)
{
    D3DXFRAME_DERIVED *pFrame = (D3DXFRAME_DERIVED*)pFrameBase;
 
    if (pParentMatrix != NULL)
        D3DXMatrixMultiply(&pFrame->CombinedTransformationMatrix, &pFrame->TransformationMatrix, pParentMatrix);
    else
        pFrame->CombinedTransformationMatrix = pFrame->TransformationMatrix;
 
    if (pFrame->pFrameSibling != NULL)
    {
        UpdateFrameMatrices(pFrame->pFrameSibling, pParentMatrix);
    }
 
    if (pFrame->pFrameFirstChild != NULL)
    {
        UpdateFrameMatrices(pFrame->pFrameFirstChild, &pFrame->CombinedTransformationMatrix);
    }
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: DrawFrame()
// Desc: Called to render a frame in the hierarchy
//-----------------------------------------------------------------------------
void CD3DSkinMesh::UpdateSkinningMethod(LPD3DXFRAME pFrameBase,
                                        D3DCAPS9          m_d3dCaps,   
                                        LPDIRECT3DDEVICE9 m_pd3dDevice, 
                                        METHOD            m_SkinningMethod)
{
    D3DXFRAME_DERIVED *pFrame = (D3DXFRAME_DERIVED*)pFrameBase;
    D3DXMESHCONTAINER_DERIVED *pMeshContainer;
 
    pMeshContainer = (D3DXMESHCONTAINER_DERIVED *)pFrame->pMeshContainer;
 
    while (pMeshContainer != NULL)
    {
        GenerateSkinnedMesh(pMeshContainer, 
                            m_d3dCaps, m_pd3dDevice, m_SkinningMethod);
 
        pMeshContainer = (D3DXMESHCONTAINER_DERIVED *)pMeshContainer->pNextMeshContainer;
    }
 
    if (pFrame->pFrameSibling != NULL)
    {
        UpdateSkinningMethod(pFrame->pFrameSibling, 
                             m_d3dCaps, m_pd3dDevice, m_SkinningMethod);
    }
 
    if (pFrame->pFrameFirstChild != NULL)
    {
        UpdateSkinningMethod(pFrame->pFrameFirstChild, 
                             m_d3dCaps, m_pd3dDevice, m_SkinningMethod);
    }
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: OneTimeSceneInit()
// Desc: Called during initial app startup, this function performs all the
//       permanent initialization.
//-----------------------------------------------------------------------------
HRESULT CD3DSkinMesh::OneTimeSceneInit()
{
 
    return S_OK;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: InitDeviceObjects()
// Desc: This creates all device-dependent managed objects, such as managed
//       textures and managed vertex buffers.
//-----------------------------------------------------------------------------
HRESULT CD3DSkinMesh::InitDeviceObjects(TCHAR*            strMeshPath,
                                        TCHAR*            strSkinnedMeshFXPath,
                                        D3DCAPS9          m_d3dCaps,
                                        LPDIRECT3DDEVICE9 m_pd3dDevice,
                                        D3DXVECTOR3*      m_vObjectCenter,
                                        FLOAT*            m_fObjectRadius)
{
    HRESULT    hr;
    CAllocateHierarchy Alloc(this, m_d3dCaps);
 
    hr = D3DXLoadMeshHierarchyFromX(strMeshPath, D3DXMESH_MANAGED, m_pd3dDevice, &Alloc, NULL, &m_pFrameRoot, &m_pAnimController);
    if (FAILED(hr))
        return hr;
 
    hr = SetupBoneMatrixPointers(m_pFrameRoot);
    if (FAILED(hr))
        return hr;
 
    hr = D3DXFrameCalculateBoundingSphere(m_pFrameRoot, m_vObjectCenter, m_fObjectRadius);
    if (FAILED(hr))
        return hr;
 
    // Create Effect for HLSL skinning
    hr = D3DXCreateEffectFromFile( m_pd3dDevice, strSkinnedMeshFXPath, NULL,
                                       NULL, D3DXSHADER_DEBUG, NULL, &m_pEffect, NULL);
    if (FAILED(hr))
        return hr;
 
    return S_OK;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: RestoreDeviceObjects()
// Desc: Restore device-memory objects and state after a device is created or
//       resized.
//-----------------------------------------------------------------------------
HRESULT CD3DSkinMesh::RestoreDeviceObjects(LPDIRECT3DDEVICE9 m_pd3dDevice)
{
    HRESULT hr;
 
    // Restore Effect
    if ( m_pEffect )
        m_pEffect->OnResetDevice();
 
    // load the indexed vertex shaders
    for (DWORD iInfl = 0; iInfl < 4; ++iInfl)
    {
        LPD3DXBUFFER pCode;
 
        // Assemble the vertex shader file
        if( FAILED( hr = D3DXAssembleShaderFromResource(NULL, MAKEINTRESOURCE(IDD_SHADER1 + iInfl), NULL, NULL, 0, &pCode, NULL ) ) )
            return hr;
 
        // Create the vertex shader
        if( FAILED( hr = m_pd3dDevice->CreateVertexShader( (DWORD*)pCode->GetBufferPointer(),
                                                           &m_pIndexedVertexShader[iInfl] ) ) )
        {
            return hr;
        }
 
        pCode->Release();
    }
 
    return S_OK;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: FrameMove()
// Desc: Called once per frame, the call is the entry point for animating
//       the scene.
//-----------------------------------------------------------------------------
HRESULT CD3DSkinMesh::FrameMove(D3DXMATRIXA16 matWorld, float m_fElapsedTime)
{
    if (m_pAnimController != NULL)
        m_pAnimController->SetTime(m_pAnimController->GetTime() + m_fElapsedTime);
 
    UpdateFrameMatrices(m_pFrameRoot, &matWorld);
 
    return S_OK;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Called once per frame, the call is the entry point for 3d
//       rendering. This function sets up render states, clears the
//       viewport, and renders the scene.
//-----------------------------------------------------------------------------
HRESULT CD3DSkinMesh::Render(D3DCAPS9 m_d3dCaps,LPDIRECT3DDEVICE9 m_pd3dDevice,
                             D3DXMATRIXA16 m_matView, D3DXMATRIXA16 m_matProj,
                             D3DXVECTOR4 vLightDir)
{
    m_pEffect->SetMatrix( "mViewProj", &m_matProj);
    m_pEffect->SetVector( "lhtDir", &vLightDir);
 
    DrawFrame(m_pFrameRoot, m_d3dCaps, m_pd3dDevice, m_matView);
 
    return S_OK;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: InvalidateDeviceObjects()
// Desc: Called when the device-dependent objects are about to be lost.
//-----------------------------------------------------------------------------
HRESULT CD3DSkinMesh::InvalidateDeviceObjects()
{
 
    // release the vertex shaders
    for (DWORD iInfl = 0; iInfl < 4; ++iInfl)
    {
        SAFE_RELEASE(m_pIndexedVertexShader[iInfl]);
    }
 
    // Invalidate Effect
    if ( m_pEffect )
        m_pEffect->OnLostDevice();
 
    return S_OK;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: DeleteDeviceObjects()
// Desc: Called when the app is exiting, or the device is being changed,
//       this function deletes any device dependent objects.
//-----------------------------------------------------------------------------
HRESULT CD3DSkinMesh::DeleteDeviceObjects(D3DCAPS9 m_d3dCaps)
{
    CAllocateHierarchy Alloc(this, m_d3dCaps);
 
    D3DXFrameDestroy(m_pFrameRoot, &Alloc);
 
    SAFE_RELEASE(m_pAnimController);
 
    SAFE_RELEASE(m_pEffect);
 
    return S_OK;
}
 
 
 
 
//-----------------------------------------------------------------------------
// Name: FinalCleanup()
// Desc: Called during initial app startup, this function performs all the
//       permanent initialization.
//-----------------------------------------------------------------------------
HRESULT CD3DSkinMesh::FinalCleanup()
{
 
    return S_OK;
}
0
 Аватар для programina
2062 / 619 / 41
Регистрация: 23.10.2011
Сообщений: 4,468
Записей в блоге: 2
12.11.2011, 11:00
Не по теме:
Вы сами это читали прежде чем сюда кинуть?


По теме:
Я бы просто взяла несколько мешей и заставила бы их менятся, при быстрой смене будет эффект анимации.
0
10 / 10 / 0
Регистрация: 10.07.2011
Сообщений: 75
13.11.2011, 01:03  [ТС]
Я это не только читал, но и правил, ведь я выписывал из примера...ну я до этого выписывал из многих но ничего не выходило толи из за DXUT толи из за еще чего то...это самое понятное что я нашел но для понимания сложно иногда...потому то я тут и написал может кто то что то шарит или делал по похожему способу....

А взять несколько мешей это сколько? 100 для 1 анимации? на 100 кадров? не это не выход...а анимация щас позарез нужна а впечатление такое что никто в интернете не знает как ее закодить.
0
184 / 24 / 4
Регистрация: 18.01.2011
Сообщений: 359
17.11.2011, 15:24
Цитата Сообщение от programina Посмотреть сообщение
Не по теме:
Вы сами это читали прежде чем сюда кинуть?


По теме:
Я бы просто взяла несколько мешей и заставила бы их менятся, при быстрой смене будет эффект анимации.
-херя бы получилась. Нужна анимация по скелету. Я тоже бьюсь над подобной проблемой. Если решу - сообщу уважаемому Arkanoid. Помни, ты не одинок! )))))
0
184 / 24 / 4
Регистрация: 18.01.2011
Сообщений: 359
19.11.2011, 22:59
Вообще очень любопытный вопрос. Если разберетесь - обязательно отпишитесь на форуме.
0
10 / 10 / 0
Регистрация: 10.07.2011
Сообщений: 75
20.11.2011, 13:16  [ТС]
Всем желающим разобраться: нашел я один гуд пример как по мне
http://www.gamedev.net/page/re... x-90-r2079
советую пошарится...токо там вылазит пару ошибок, и из кода желательно вырезать заргузчик моделей, а так вроде понятно, у меня небыло времени пока разобратся, но обязательно разберусь в ближайшее время, еси че найду или заработает - напишу.

Да еси у кого то выйдет раньше - напишите плз тоже, буду оч благодарен
0
184 / 24 / 4
Регистрация: 18.01.2011
Сообщений: 359
21.11.2011, 11:54
о, Arkanoid, молодец. Как своб. время будет гляну. Вообще сам замучился с этой анимацией. Тоже кучу книг перечитал...и сайтов тьму излазил. Оч непросто все. В общем...если разберусь - выложу код обязательно. Надеюсь и с вашей стороны на подобный жест.
0
10 / 10 / 0
Регистрация: 10.07.2011
Сообщений: 75
23.11.2011, 21:52  [ТС]
я тут вот что попробовал - сам код не пахал совсем, НО я перекинул все из классо CModel в main и вышло что то с парой ошибок...вот выкладываю код, выдает в основном ошибки перевода из LPSWSTR в const char* и const void* ...и ругается кода создаю переменную класса...

C++
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
/////////////////////////////////////////////////
//
// File: "Main.cpp"
//
// Author: Jason Jurecka
//
// Creation Date: June 5, 2003
//
// Purpose: This is the main application for
//      viewing models
//
// Note: This was written for DirectX version 9
//
//  A lot of the code for the window was taken
//      from the directX SDK sample apps, but changed
//      to work with my model class
/////////////////////////////////////////////////
#pragma comment(lib, "d3d9")
//#pragma comment(lib, "d3dx9dt")
//#include <afxwin.h>
//#include <afxdlgs.h>
#include <d3d9.h>
#include <d3d9types.h>
#include <d3dx9math.h>
#include "CModel.h"
#include "Macros.h"
#include "DirectInput.h"
    #include <d3dx9.h>
#include <d3dx9anim.h>
#include "CAllocateHierarchy.cpp"
#include "DerivedStructs.h"
 
//Model Globals
    LPMESHCONTAINER     m_pFirstMesh;           // The first mesh in the hierarchy
    LPD3DXFRAME         m_pFrameRoot;           // Frame hierarchy of the model
    LPD3DXMATRIX        m_pBoneMatrices;        // Used when calculating the bone position
    D3DXVECTOR3         m_vecCenter;            // Center of bounding sphere of object
    float               m_fRadius;              // Radius of bounding sphere of object
    UINT                m_uMaxBones;            // The Max number of bones for the model
    //Animation
    DWORD               m_dwCurrentAnimation;   // The current animation
    DWORD               m_dwAnimationSetCount;  // Number of animation sets
    LPD3DXANIMATIONCONTROLLER   m_pAnimController;// Controller for the animations
 
//-----------------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------------
LPDIRECT3D9             g_pD3D           = NULL; // Used to create the D3DDevice
LPDIRECT3DDEVICE9       g_pd3dDevice     = NULL; // Our rendering device
D3DLIGHT9               g_dLight;                // A light for the App
//CModel*                   g_pModel         = NULL; // A model object to work with
//private:
    void DrawFrame(LPFRAME pFrame);
    void SetupBoneMatrices(LPFRAME pFrame, LPD3DXMATRIX pParentMatrix);
    void UpdateFrameMatrices(LPFRAME pFrame, LPD3DXMATRIX pParentMatrix);
//public:   
    inline LPD3DXVECTOR3 GetBoundingSphereCenter()
    { return &m_vecCenter; }
        inline float GetBoundingSphereRadius()
    { return m_fRadius; }
            inline DWORD GetCurrentAnimation()
    { return m_dwCurrentAnimation; }
            
            void SetCurrentAnimation(DWORD dwAnimationFlag);
            void Draw();
            void LoadXFile(char* strFileName);
            void Update(double dElapsedTime);
 
#define controllist "Escape = Exit\nRight Arrow = Rotate model right\nLeft Arrow = Rotate model left\nUp Arrow = Move model forward\nDown Arrow = Move model backward\nA = Move model up\nD = Move model down\nW = Rotate model up\nS = Rotate model down\nN = Play next animation\nM = Play previous animation\nT = Toggle Wireframe mode\nR = Toggle Culling\nO = Open an X file\nC = Bring up Controls list"
 
//-----------------------------------------------------------------------------
// Name: MsgProc()
// Desc: The window's message handler
//-----------------------------------------------------------------------------
LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch( msg )
    {
        case WM_DESTROY:
            PostQuitMessage( 0 );
            return 0;
    }
 
    return DefWindowProc( hWnd, msg, wParam, lParam );
}
 
void InitModel(LPDIRECT3DDEVICE9 pD3DDevice)
{
    g_pd3dDevice    = pD3DDevice;   
    m_pFrameRoot = NULL;            
    m_pBoneMatrices = NULL;         
    m_vecCenter = D3DXVECTOR3(0.0f,0.0f,0.0f);
    m_fRadius = 0.0f;               
    m_dwCurrentAnimation = -1;  
    m_dwAnimationSetCount = 0;  
    m_uMaxBones = 0;
    m_pAnimController = NULL;
    m_pFirstMesh = NULL;
}
void SetupBoneMatrices(LPFRAME pFrame, LPD3DXMATRIX pParentMatrix)
{
    LPMESHCONTAINER pMesh = (LPMESHCONTAINER)pFrame->pMeshContainer;
 
    //Set up the bones on the mesh
    if(pMesh)
    {
        if(!m_pFirstMesh)
            m_pFirstMesh = pMesh;
        
        // if there is a skinmesh, then setup the bone matrices
        if(pMesh->pSkinInfo)
        {
            //Create a copy of the mesh
            pMesh->MeshData.pMesh->CloneMeshFVF(D3DXMESH_MANAGED, 
                pMesh->MeshData.pMesh->GetFVF(), g_pd3dDevice, 
                &pMesh->pSkinMesh);
        
            if(m_uMaxBones < pMesh->pSkinInfo->GetNumBones())
            {
                //Get the number of bones
                m_uMaxBones = pMesh->pSkinInfo->GetNumBones();
            }
 
            LPFRAME pTempFrame = NULL;
 
            //For each bone 
            for (UINT i = 0; i < pMesh->pSkinInfo->GetNumBones(); i++)
            {   
                // Find the frame
                pTempFrame = (LPFRAME)D3DXFrameFind(m_pFrameRoot, 
                        pMesh->pSkinInfo->GetBoneName(i));
 
                //set the bone part
                pMesh->ppFrameMatrices[i] = &pTempFrame->matCombined;
            }
        }
    }
 
    //Check your Sister
    if(pFrame->pFrameSibling)
        SetupBoneMatrices((LPFRAME)pFrame->pFrameSibling, pParentMatrix);
 
    //Check your Son
    if(pFrame->pFrameFirstChild)
        SetupBoneMatrices((LPFRAME)pFrame->pFrameFirstChild, &pFrame->matCombined);
}
 
void LoadXFile(char* strFileName)
{
    //Allocation class
    CAllocateHierarchy Alloc;
 
    //Load the mesh
    if(FAILED(D3DXLoadMeshHierarchyFromX(L"tiny.x",     // File load
                                        D3DXMESH_MANAGED,   // Load Options
                                        g_pd3dDevice,       // D3D Device
                                        &Alloc,             // Hierarchy allocation class
                                        NULL,               // NO Effects
                                        &m_pFrameRoot,      // Frame hierarchy
                                        &m_pAnimController)))// Animation Controller
    {
        MessageBox(NULL, NULL, L"Model Load Error", MB_OK);
    }
 
    if(m_pAnimController)
        m_dwAnimationSetCount = m_pAnimController->GetMaxNumAnimationSets();
 
    if(m_pFrameRoot)
    {
        //Set the bones up
        SetupBoneMatrices((LPFRAME)m_pFrameRoot, NULL);
 
        //Setup the bone matrices array 
        m_pBoneMatrices  = new D3DXMATRIX[m_uMaxBones];
        ZeroMemory(m_pBoneMatrices, sizeof(D3DXMATRIX)*m_uMaxBones);
 
        //Calculate the Bounding Sphere
        D3DXFrameCalculateBoundingSphere(m_pFrameRoot, 
            &m_vecCenter, &m_fRadius);
    }
}
void SetCurrentAnimation(DWORD dwAnimationFlag)
{
    // If the animation is not one that we are already using
    //  and the passed in flag is not bigger than the number of animations
    if(dwAnimationFlag != m_dwCurrentAnimation && dwAnimationFlag < m_dwAnimationSetCount) 
    { 
        m_dwCurrentAnimation = dwAnimationFlag;
        LPD3DXANIMATIONSET AnimSet = NULL;
        m_pAnimController->GetAnimationSet(m_dwCurrentAnimation, &AnimSet);
        m_pAnimController->SetTrackAnimationSet(0, AnimSet);
        SAFE_RELEASE(AnimSet)
    }
}
 
//////////////////////////////////////////////////////////////////////////
// Draw Functions
//////////////////////////////////////////////////////////////////////////
 
void Draw()
{
 
    LPMESHCONTAINER pMesh = m_pFirstMesh;
 
    //While there is a mesh try to draw it
    while(pMesh)
    {
        //Select the mesh to draw
        LPD3DXMESH pDrawMesh = (pMesh->pSkinInfo)
            ? pMesh->pSkinMesh: pMesh->MeshData.pMesh;
        
        //Draw each mesh subset with correct materials and texture
        for (DWORD i = 0; i < pMesh->NumMaterials; ++i)
        {
            g_pd3dDevice->SetMaterial(&pMesh->pMaterials9[i]);
            g_pd3dDevice->SetTexture(0, pMesh->ppTextures[i]);
            pDrawMesh->DrawSubset(i);
        }
 
        //Go to the next one
        pMesh = (LPMESHCONTAINER)pMesh->pNextMeshContainer;
    }
}
void DrawFrame(LPFRAME pFrame)
{
    LPMESHCONTAINER pMesh = (LPMESHCONTAINER)pFrame->pMeshContainer;
 
    //While there is a mesh try to draw it
    while(pMesh)
    {
        //Select the mesh to draw
        LPD3DXMESH pDrawMesh = (pMesh->pSkinInfo)
            ? pMesh->pSkinMesh: pMesh->MeshData.pMesh;
        
        //Draw each mesh subset with correct materials and texture
        for (DWORD i = 0; i < pMesh->NumMaterials; ++i)
        {
            g_pd3dDevice->SetMaterial(&pMesh->pMaterials9[i]);
            g_pd3dDevice->SetTexture(0, pMesh->ppTextures[i]);
            pDrawMesh->DrawSubset(i);
        }
 
        //Go to the next one
        pMesh = (LPMESHCONTAINER)pMesh->pNextMeshContainer;
    }
 
    //Check your Sister
    if(pFrame->pFrameSibling)
        DrawFrame((LPFRAME)pFrame->pFrameSibling);
 
    //Check your Son
    if(pFrame->pFrameFirstChild)
        DrawFrame((LPFRAME)pFrame->pFrameFirstChild);
}
void Update(double dElapsedTime)
{
    //Set the time for animation
    if(m_pAnimController && m_dwCurrentAnimation != -1)
        m_pAnimController->SetTime(m_pAnimController->GetTime()+dElapsedTime);
 
    //Update the frame hierarchy
    if(m_pFrameRoot)
    {
        UpdateFrameMatrices((LPFRAME)m_pFrameRoot, NULL);
        
        LPMESHCONTAINER pMesh = m_pFirstMesh;
        if(pMesh)
        {
            if(pMesh->pSkinInfo)
            {
                UINT Bones = pMesh->pSkinInfo->GetNumBones();
                for (UINT i = 0; i < Bones; ++i)
                {   
                    D3DXMatrixMultiply
                    (
                        &m_pBoneMatrices[i],//out
                        &pMesh->pBoneOffsets[i], 
                        pMesh->ppFrameMatrices[i]
                    );
                }
 
                // Lock the meshes' vertex buffers
                void *SrcPtr, *DestPtr;
                pMesh->MeshData.pMesh->LockVertexBuffer(D3DLOCK_READONLY, (void**)&SrcPtr);
                pMesh->pSkinMesh->LockVertexBuffer(0, (void**)&DestPtr);
 
                // Update the skinned mesh using provided transformations
                pMesh->pSkinInfo->UpdateSkinnedMesh(m_pBoneMatrices, NULL, SrcPtr, DestPtr);
 
                // Unlock the meshes vertex buffers
                pMesh->pSkinMesh->UnlockVertexBuffer();
                pMesh->MeshData.pMesh->UnlockVertexBuffer();
            }
        }
    }
}
void UpdateFrameMatrices(LPFRAME pFrame, LPD3DXMATRIX pParentMatrix)
{   
    //Parent check
    if (pParentMatrix)
    {
        D3DXMatrixMultiply(&pFrame->matCombined, 
            &pFrame->TransformationMatrix, 
            pParentMatrix);
    }
    else
        pFrame->matCombined = pFrame->TransformationMatrix;
 
    //Do the kid too
    if (pFrame->pFrameSibling)
    {
        UpdateFrameMatrices((LPFRAME)pFrame->pFrameSibling, pParentMatrix);
    }
 
    //make sure you get the first kid
    if (pFrame->pFrameFirstChild)
    {
        UpdateFrameMatrices((LPFRAME)pFrame->pFrameFirstChild, 
                &pFrame->matCombined);
    }
}
 
//---------------------------------------и--------------------------------------
// Name: WinMain()
// Desc: The application's entry point
//-----------------------------------------------------------------------------
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow)
{
    // Register the window class
    WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, 
                      GetModuleHandle(NULL), NULL, LoadCursor(NULL, IDC_ARROW), NULL, NULL,
                      L"TestApp", NULL };
    RegisterClassEx( &wc );
    
    // Create the application's window
    HWND hWnd = CreateWindow( L"TestApp", L"X File Model Viewer - Press \'C\' to view the controls", 
                              WS_OVERLAPPEDWINDOW, 0, 0, 800, 600,
                              GetDesktopWindow(), NULL, wc.hInstance, NULL );
 
    // Initializes MFC so it will work
//  AfxWinInit(hInst, hPrevInstance, lpCmdLine, nCmdShow );
    
    //////////////////////////////////////////////////////////////////////////
    // Initialize Direct3D
    //////////////////////////////////////////////////////////////////////////
    // Create the D3D object.
    if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
        return E_FAIL;
 
    // Set up the structure used to create the D3DDevice. Since we are now
    // using more complex geometry, we will create a device with a zbuffer.
    D3DPRESENT_PARAMETERS d3dpp; 
    ZeroMemory( &d3dpp, sizeof(d3dpp) );
    d3dpp.Windowed = TRUE;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
    d3dpp.EnableAutoDepthStencil = TRUE;
    d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;
 
    // Create the D3DDevice
    if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                      D3DCREATE_HARDWARE_VERTEXPROCESSING,
                                      &d3dpp, &g_pd3dDevice ) ) )
    {
        return E_FAIL;
    }
 
    
 
    // Turn on the zbuffer
    g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
 
    BOOL bCulling = TRUE;
    // Culling
    g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
 
    //No lighting
    g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
 
    //BOOL bSimpleShadow = FALSE;
    //Do the alpha blending
    g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
    g_pd3dDevice->SetRenderState( D3DRS_SRCBLEND,   D3DBLEND_SRCALPHA );
    g_pd3dDevice->SetRenderState( D3DRS_DESTBLEND,  D3DBLEND_INVSRCALPHA );
            
    BOOL bComplexShadow = FALSE;
    // Show the window
    ShowWindow( hWnd, SW_SHOWDEFAULT );
    UpdateWindow( hWnd );
 
    D3DXMATRIXA16 matWorld, matYWorld, matXWorld, matTranslate, matUp, matView, matProj, matZWorld;
 
    D3DXVECTOR3 vLookatPt(0.0f, 0.0f, 0.0f);
    D3DXVECTOR3 vEyePt(0.0f, 0.0f, 0.0f);
    D3DXVECTOR3 vUpVec(0.0f, 1.0f, 0.0f);
 
    //Movement variables
    static float fAngle = 0.0f;
    static float fForward = 0.0f;
    static float fUp = 0.0f;
    static float fAngle2 = 0.0f;
    static float fAngle3 = 0.0f;
    static bool bWireframe = false;
 
    //From the DirectX SDK window for setting up projection matrices
    //
    // For the projection matrix, we set up a perspective transform (which
    // transforms geometry from 3D view space to 2D viewport space, with
    // a perspective divide making objects smaller in the distance). To build
    // a perpsective transform, we need the field of view (1/4 pi is common),
    // the aspect ratio, and the near and far clipping planes (which define at
    // what distances geometry should be no longer be rendered).
    D3DXMatrixPerspectiveFovLH(&matProj, D3DX_PI/4, (800.0f/600.0f), 1.0f, 2500.0f);
    g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &matProj); 
    
    //Set up the time stuff
    double starttime;
    LARGE_INTEGER nowtime;
    LONGLONG ticks;
 
    LARGE_INTEGER time;
    QueryPerformanceCounter(&time);
    starttime = (double)time.QuadPart;
 
    QueryPerformanceFrequency(&time);
    ticks = time.QuadPart;
    //load file
    LoadXFile("tiny.x");
 
                            //Make sure we can see it
                            float radius = GetBoundingSphereRadius();
                            vEyePt = D3DXVECTOR3(0.0f, radius*2, -(radius*2));
                            LPD3DXVECTOR3 ptemp = GetBoundingSphereCenter();
                            vLookatPt = D3DXVECTOR3(ptemp->x, ptemp->y, ptemp->z);
                            fAngle = 0.0f;
                            fForward = 0.0f;
                            fUp = 0.0f;
                            fAngle2 = 0.0f;
    // Enter the message loop
    MSG msg; 
    ZeroMemory( &msg, sizeof(msg) );
    while( msg.message!=WM_QUIT )
    {
        if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
        else
        {
            // Clear the backbuffer and the zbuffer
            g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL, 
                                 D3DCOLOR_XRGB(125,125,125), 1.0f, 0 );
        
            static int iFrames = 0;
            static double sttime = 0.0;
            iFrames++;
            if (iFrames == 100) 
            {
                QueryPerformanceCounter(&nowtime);
                float fps = float(iFrames/((nowtime.QuadPart - sttime)/ticks));
                char cBuff[32];
                
                SetWindowText(hWnd,LPCWSTR(cBuff));
                sttime = (double)nowtime.QuadPart;
                iFrames = 0;
            }
 
            
            //////////////////////////////////////////////////////////////////////////
            // Setup the world and view
            //////////////////////////////////////////////////////////////////////////
 
            D3DXMatrixIdentity(&matWorld);
            D3DXMatrixIdentity(&matYWorld);
            D3DXMatrixIdentity(&matXWorld);
            D3DXMatrixIdentity(&matZWorld);
            D3DXMatrixIdentity(&matTranslate);
            D3DXMatrixIdentity(&matUp);
            
            //This makes the model rotate Y
            D3DXMatrixRotationY( &matYWorld, D3DXToRadian(fAngle));
            //This makes the model rotate X
            D3DXMatrixRotationX( &matXWorld, D3DXToRadian(fAngle2));
            //This makes the model rotate Z
            D3DXMatrixRotationZ( &matZWorld, D3DXToRadian(fAngle3));
 
            //This moves the stuff around
            D3DXMatrixTranslation(&matTranslate, 0.0f, fUp, fForward);
            
            matWorld = (matYWorld * matXWorld * matZWorld * matTranslate);
 
            g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld);
 
            D3DXMatrixLookAtLH( &matView, &vEyePt, &vLookatPt, &vUpVec );
            g_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );
 
            // Begin the scene
            if(SUCCEEDED(g_pd3dDevice->BeginScene()))
            {
                //////////////////////////////////////////////////////////////////////////
                // Draw the stuff
                //////////////////////////////////////////////////////////////////////////
                
                
                    //find the time difference
                    QueryPerformanceCounter(&nowtime);
                    double dtime = ((nowtime.QuadPart - starttime)/ticks);
                                        
                    //Update the model
                    Update(dtime);
                    starttime = (double)nowtime.QuadPart;
                    Draw();
                
 
                // End the scene
                    g_pd3dDevice->EndScene();
            }
 
            // Present the backbuffer contents to the display
            g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
 
        
 
            //If we have focus handle the input stuff
            
                
            //  if(g_pModel)
                //{
                //  if (g_pDI->DIKeyboardHandler(DIK_N))
                //  {
                //      Sleep(200);
                //      g_pModel->SetCurrentAnimation(g_pModel->GetCurrentAnimation()+1);
                //  }
 
                //  if (g_pDI->DIKeyboardHandler(DIK_M))
                //  {
                //      Sleep(200);
                //      g_pModel->SetCurrentAnimation(g_pModel->GetCurrentAnimation()-1);
                //  }                   
                //}
                //Show the controls list
                /*if (g_pDI->DIKeyboardHandler(DIK_C))
                {
                    Sleep(200);
                    MessageBox(hWnd, LPCWSTR(controllist), L"Controls List", MB_OK);
                }*/
 
                //O is for open
                
                
                        
                            //make new
                            
                            //Load the new
                            
                        
                    
                }
            }
        
    
    
    
            g_pd3dDevice->Release();
            g_pD3D->Release();
 
    
    
    UnregisterClass( LPCWSTR("TestApp"), wc.hInstance );
    return 0;
}
Если вам не трудно попробуйте у себя этот код поставить в отдельном проэкте с хэдэрами из того что я кидал ранее...может у вас выйдет довести до конца исходник.Еще новости будут - напишу
1
10 / 10 / 0
Регистрация: 10.07.2011
Сообщений: 75
26.11.2011, 13:40  [ТС]
такс, посидел я еще чуть чуть и довел все это до 1 ошибки

Собственно я не оч понимаю что не так но походу класс
C++
1
class CAllocateHierarchy: public ID3DXAllocateHierarchy
считается абстрактным

я посмотрел обьявление ID3DXAllocateHierarchy, но вроде там ничего подобного в обьявлении нет...

Может кто знает в чем проблема? Просто походу в коде без этого класса никуда не деться...
0
184 / 24 / 4
Регистрация: 18.01.2011
Сообщений: 359
28.11.2011, 08:55
Мда. думаю, придется забыть о реализации данного кода.
в начале описанный хедер файлы кот. в проекте нет
#include "CModel.h"
#include "Macros.h"
#include "DirectInput.h" //ну этот может и есть
#include "CAllocateHierarchy.cpp"
#include "DerivedStructs.h"
- это авторские файлы. Если же их найти...то мало шансов потом "найти концы" уж больно их много.
0
10 / 10 / 0
Регистрация: 10.07.2011
Сообщений: 75
28.11.2011, 19:28  [ТС]


Все файлы есть! они прелагались к исходнику! я все переделал просто - из класа CModel все в простые функции в главном коде переделал, там в них все понятно!)))

остался только файл CAllocateHierarchy.cpp, и его абстрактный класс - еси б не это все было бы просто офигенно!


Цитата Сообщение от Андрей2011 Посмотреть сообщение
Мда. думаю, придется забыть о реализации данного кода.
не в коем случае! я завтра у препода поспрашиваю, еси че - все запахает! Как забить на код когда в нем только 1 ошибка осталась вы что! Нет так просто сдаватся почти у цели смысла нет...Я буду добивать этот исходник и еси выйдет - выложу.
0
184 / 24 / 4
Регистрация: 18.01.2011
Сообщений: 359
29.11.2011, 10:55
К стати, может имеет смысл вместо "L"TestApp"" - буквы L перед текстом просто
в настройках проекта указать кодировку не Unicode а , например, многобойтовую
0
10 / 10 / 0
Регистрация: 10.07.2011
Сообщений: 75
30.11.2011, 19:15  [ТС]
Может и имеет, а может и нет) еси веь код L ставил то менять все бестолку.

Я все еще бьюсь над исходником, завтра покажу его знакомым всем может кто то поможет...вроде остальных ошибок нет...так что напишу что из этого вышло.
0
184 / 24 / 4
Регистрация: 18.01.2011
Сообщений: 359
01.12.2011, 16:09
Давай. У меня есть 2 программы которые используют анимацию. Одна из них вполне рабочая. Я на VC++ 2010 пишу под DirectX 9. Вот. Я мог бы их выложить...если в этом есть смысл конечно. Т.к. там все очень муторно и я так и не смог разобраться в этом извратном коде.
0
10 / 10 / 0
Регистрация: 10.07.2011
Сообщений: 75
02.12.2011, 00:13  [ТС]
Цитата Сообщение от Андрей2011 Посмотреть сообщение
Давай. У меня есть 2 программы которые используют анимацию. Одна из них вполне рабочая. Я на VC++ 2010 пишу под DirectX 9.
Я тоже аналогично пишу но еси ты не о примерах из SDK - то выкладывай разберем!

А еси из SDK - то забудь, с DXUT нифига не разобрать

А про абстрактные классы пока не вышло ниче путнего узнать - выложи свое, я посмотрю, еси твое не подойдет буду дальше искать...
0
184 / 24 / 4
Регистрация: 18.01.2011
Сообщений: 359
03.12.2011, 10:18
Итак. Глянул одним глазом ссылку на сайт, которую дал уважаемый, Arkanoid. Вроде и сайт по теме и код описан внятно. Надо будет посмотреть но все руки не дойдут.
Тем не менее. Я учил DirectX по Алену Терну. Учил и учу. И буду учить. ))
В книге очень не просто добавить код чтоб работало. Есть пример его программы с использованием анимации, но! Он у меня не пошел. Зато более менее понятны функции стандартные по анимации...хотя тоже все запутано конечно:
Chapter 13.rar. https://www.cyberforum.ru/atta... 1322892717

А так же, на сколько я понял сайт еще одно автора книг по Directx...ну или как-то связанный с этим. Вот ссылка:
http://www.toymaker.info/Games... archy.html
и вот вполне рабочая программа анимации:
XFileAnimationCode.rar https://www.cyberforum.ru/atta... 1322892717

Проверил у себя, еще раз повторюсь на VC++ 2010. Все работает, но там код сложнее. оч сложно разобраться.
Надеюсь что смог помочь чем-то, т.к. информацию которую выложил, вобщем-то общедоступна вполне.
Вложения
Тип файла: rar XFileAnimationCode.rar (710.1 Кб, 125 просмотров)
Тип файла: rar Chapter 13.rar (5.69 Мб, 65 просмотров)
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
03.12.2011, 10:18
Помогаю со студенческими работами здесь

Как выполнить два трансформирования меша одновременно
Здравствуйте! Я столкнулся с такой проблемой: мне нужно уменьшить объект и передвинуть, но у меня почему то не получается. Вот код: ...

Анимация .Х-файла
Всем привет начал изучать анимацию .Х-файла по книге Джима Адамса - продвинутая анимация,и сталкнулся с проблемой,там в книге в примере...

Генерация меша
Доброго времени суток, подскажите пожалуйста, каким алгоритмом производится генерация меша? Необходимо сгенерировать плоский меш с заданным...

Координаты дочернего объекта (меша) в three JS
Объект состоит из двух геометрических фигур, основной и дочерних, следующим образом (цилиндр объявлен отдельным свойством, чтобы к нему был...

Не могу редактировать материалы меша
На днях установил Lightweight render pipeline что бы пользоваться Shader Graph'ом, но все материалы нужно перевести в нужные шейдеры. Но...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
Новые блоги и статьи
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
Управление камерой с помощью скрипта OrbitControls.js на Three.js: Вращение, зум и панорамирование
8Observer8 05.03.2026
Содержание блога Финальная демка в браузере работает на Desktop и мобильных браузерах. Итоговый код: orbit-controls-threejs-js. zip. Сканируйте QR-код на мобильном. Вращайте камеру одним пальцем,. . .
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
SDL3 для Web (WebAssembly): Идентификация объектов на Box2D v3 - использование userData и событий коллизий
8Observer8 02.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-collision-events-sdl3-c. zip Сканируйте QR-код на мобильном и вы увидите, что появится джойстик для управления главным героем. . . .
Реалии
Hrethgir 01.03.2026
Нет, я не закончил до сих пор симулятор. Эта задача сложнее. Не получилось уйти в плавсостав, но оно и к лучшему, возможно. Точнее получалось - но сварщиком в палубную команду, а это значит, в моём. . .
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка библиотек: SDL3, Box2D, FreeType, SDL3_ttf, SDL3_mixer и SDL3_image из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru