root/cafu/trunk/CaTools/CaSanity.cpp

Revision 455, 30.5 KB (checked in by Carsten, 4 months ago)

Updated copyright banners (in C++ files).

Line 
1/*
2=================================================================================
3This file is part of Cafu, the open-source game engine and graphics engine
4for multiplayer, cross-platform, real-time 3D action.
5Copyright (C) 2002-2012 Carsten Fuchs Software.
6
7Cafu is free software: you can redistribute it and/or modify it under the terms
8of the GNU General Public License as published by the Free Software Foundation,
9either version 3 of the License, or (at your option) any later version.
10
11Cafu is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
12without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
13PURPOSE. See the GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with Cafu. If not, see <http://www.gnu.org/licenses/>.
17
18For support and more information about Cafu, visit us at <http://www.cafu.de>.
19=================================================================================
20*/
21
22/*************************************/
23/***                               ***/
24/***    Cafu Map Debugging Tool    ***/
25/***                               ***/
26/*** Never touch a running system. ***/
27/*** Never change a winning  team. ***/
28/***                               ***/
29/*************************************/
30
31#ifdef _WIN32
32#include <conio.h>
33#endif
34
35#ifdef _WIN32
36    #if defined(_MSC_VER)
37        #define WIN32_LEAN_AND_MEAN
38        #include <windows.h>
39        #if (_MSC_VER<1300)
40        #define for if (false) ; else for
41    #endif
42    #endif
43#endif
44
45#include <stdio.h>
46#include <string.h>
47#include <GL/gl.h>
48#include <GL/glu.h>
49
50#include "Templates/Array.hpp"
51#include "ConsoleCommands/Console.hpp"
52#include "ConsoleCommands/ConsoleInterpreter.hpp"
53#include "ConsoleCommands/ConsoleStdout.hpp"
54#include "FileSys/FileManImpl.hpp"
55#include "FileSys/Password.hpp"
56#include "Math3D/Brush.hpp"
57#include "Bitmap/Bitmap.hpp"
58#include "OpenGL/OpenGLWindow.hpp"
59#include "Util/Util.hpp"
60#include "MaterialSystem/Material.hpp"
61#include "MaterialSystem/MaterialManager.hpp"
62#include "MaterialSystem/MaterialManagerImpl.hpp"
63#include "Models/ModelManager.hpp"
64#include "SceneGraph/BspTreeNode.hpp"
65#include "SceneGraph/FaceNode.hpp"
66#include "ClipSys/CollisionModelMan_impl.hpp"
67
68#include "../Common/World.hpp"
69
70
71static cf::ConsoleStdoutT ConsoleStdout;
72cf::ConsoleI* Console=&ConsoleStdout;
73
74static cf::FileSys::FileManImplT FileManImpl;
75cf::FileSys::FileManI* cf::FileSys::FileMan=&FileManImpl;
76
77static cf::ClipSys::CollModelManImplT CCM;
78cf::ClipSys::CollModelManI* cf::ClipSys::CollModelMan=&CCM;
79
80ConsoleInterpreterI* ConsoleInterpreter=NULL;
81MaterialManagerI*    MaterialManager   =NULL;
82
83
84WorldT* World=NULL;
85
86
87bool Visible(unsigned long L1, unsigned long L2)
88{
89    unsigned long PVSTotalBitNr=L1*World->BspTree->Leaves.Size()+L2;
90    unsigned long PVS_W32_Nr   =PVSTotalBitNr >> 5;
91
92    return bool((World->BspTree->PVS[PVS_W32_Nr] >> (PVSTotalBitNr & 31)) & 1);
93}
94
95
96void ExportLightMaps(const char* WorldPathName)
97{
98    char WorldName[256]="unknown";
99
100    // Strip path and extension from 'WorldPathName' first.
101    if (WorldPathName)
102    {
103        // Dateinamen abtrennen (mit Extension).
104        size_t i=strlen(WorldPathName);
105
106        while (i>0 && WorldPathName[i-1]!='/' && WorldPathName[i-1]!='\\') i--;
107        strncpy(WorldName, WorldPathName+i, 256);
108        WorldName[255]=0;
109
110        // Extension abtrennen.
111        i=strlen(WorldName);
112
113        while (i>0 && WorldName[i-1]!='.') i--;
114        if (i>0) WorldName[i-1]=0;
115    }
116
117    for (unsigned long LMNr=0; LMNr<World->LightMapMan.Bitmaps.Size(); LMNr++)
118    {
119        printf("LM_%s_%02lu\n", WorldName, LMNr);
120
121        char LMNamePNG[200];
122        sprintf(LMNamePNG, "LM_%s_%02lu.png", WorldName, LMNr);
123
124        World->LightMapMan.Bitmaps[LMNr]->SaveToDisk(LMNamePNG);
125    }
126}
127
128
129void ExportPVS()
130{
131    for (unsigned long Leaf1Nr=0; Leaf1Nr<World->BspTree->Leaves.Size(); Leaf1Nr++)
132    {
133        printf("%5lu: ", Leaf1Nr);
134
135        for (unsigned long Leaf2Nr=0; Leaf2Nr<World->BspTree->Leaves.Size(); Leaf2Nr++)
136        {
137            const unsigned long PVSTotalBitNr=Leaf1Nr*World->BspTree->Leaves.Size()+Leaf2Nr;
138
139            if ((World->BspTree->PVS[PVSTotalBitNr >> 5] >> (PVSTotalBitNr & 31)) & 1)
140            {
141                printf("%5lu", Leaf2Nr);
142                if (Leaf2Nr<World->BspTree->Leaves.Size()-1) printf(" ");
143            }
144        }
145
146        printf("\n");
147    }
148}
149
150
151void PrintMaterialCounts(int Mode)
152{
153    // Would be nice to implement this with a hash...
154    ArrayT<MaterialT*>    Materials;
155    ArrayT<unsigned long> Counts;
156    ArrayT<double>        Areas;
157
158    if (Mode & 1)
159    {
160        printf("Counts and areas for faces...\n");
161        for (unsigned long FaceNr=0; FaceNr<World->BspTree->FaceChildren.Size(); FaceNr++)
162        {
163            MaterialT* Mat  =World->BspTree->FaceChildren[FaceNr]->Material;
164            int        Index=Materials.Find(Mat);
165
166            if (Index>=0)
167            {
168                Counts[Index]++;
169                Areas [Index]+=World->BspTree->FaceChildren[FaceNr]->Polygon.GetArea()/1000000.0;
170            }
171            else
172            {
173                Materials.PushBack(Mat);
174                Counts.PushBack(1);
175                Areas .PushBack(World->BspTree->FaceChildren[FaceNr]->Polygon.GetArea()/1000000.0);
176            }
177        }
178    }
179
180
181    // Print out the results.
182    unsigned long TotalCount=0;
183
184    for (unsigned long MatNr=0; MatNr<Materials.Size(); MatNr++)
185    {
186        if (Mode==1) printf("%5lu %12.2f %s\n", Counts[MatNr], Areas[MatNr], Materials[MatNr]->Name.c_str());
187                else printf("%5lu %s\n", Counts[MatNr], Materials[MatNr]->Name.c_str());
188        TotalCount+=Counts[MatNr];
189    }
190    printf("Total: %lu\n\n", TotalCount);
191}
192
193
194void ViewWorld()
195{
196    VectorT Viewer   =World->InfoPlayerStarts[0].Origin;
197    float   Heading  =  0.0;
198    float   Pitch    =  0.0;
199    float   MoveSpeed=100.0;
200    float   RotSpeed =  5.0;
201
202    bool          r_pvs_enabled=true;
203    unsigned long DrawLeafNr   =831;
204
205    ArrayT<bool>          FaceIsInPVS;
206    ArrayT<unsigned long> OrderedFaces;
207
208    FaceIsInPVS .PushBackEmpty(World->BspTree->FaceChildren.Size());
209    OrderedFaces.PushBackEmpty(World->BspTree->FaceChildren.Size());
210
211
212    const char* ErrorMsg=SingleOpenGLWindow->Open("Simple World Viewer", 1024, 768, 16, false);
213
214    if (ErrorMsg)
215    {
216        printf("\nUnable to open OpenGL window: %s\n", ErrorMsg);
217        return;
218    }
219
220
221    while (true)
222    {
223        // Rufe die Nachrichten der Windows-Nachrichtenschlange ab.
224        if (SingleOpenGLWindow->HandleWindowMessages()) break;
225
226        // Draw the model
227        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
228        glLoadIdentity();
229
230        glRotatef(Pitch  , 1.0, 0.0, 0.0);
231        glRotatef(Heading, 0.0, 1.0, 0.0);
232        glTranslatef(float(-Viewer.x), float(-Viewer.z), float(Viewer.y));
233
234
235        static ArrayT<unsigned long> OrderedLeaves;
236        const unsigned long ViewerLeafNr=World->BspTree->WhatLeaf(Viewer);
237        World->BspTree->GetLeavesOrderedBackToFront(OrderedLeaves, Viewer);
238
239        for (unsigned long FaceNr=0; FaceNr<World->BspTree->FaceChildren.Size(); FaceNr++) FaceIsInPVS[FaceNr]=false;
240
241        for (unsigned long OrderNr=0; OrderNr<OrderedLeaves.Size(); OrderNr++)
242        {
243            const unsigned long LeafNr=OrderedLeaves[OrderNr];
244            const cf::SceneGraph::BspTreeNodeT::LeafT& L=World->BspTree->Leaves[LeafNr];
245
246            if (r_pvs_enabled && !World->BspTree->IsInPVS(LeafNr, ViewerLeafNr)) continue;
247
248            OrderedFaces.PushBack(L.FaceChildrenSet);
249
250            for (unsigned long SetNr=0; SetNr<L.FaceChildrenSet.Size(); SetNr++)
251                FaceIsInPVS[L.FaceChildrenSet[SetNr]]=true;
252        }
253
254
255        // if (r_style==SolidPolygons)
256        {
257            glEnable(GL_BLEND);
258            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
259
260            for (unsigned long OrderedFaceNr=0; OrderedFaceNr<OrderedFaces.Size(); OrderedFaceNr++)
261            {
262                const unsigned long FaceNr=OrderedFaces[OrderedFaceNr];
263                const Polygon3T<double>& F=World->BspTree->FaceChildren[FaceNr]->Polygon;
264                char                Alpha =255; // World->BspTree->FaceChildren[FaceNr]->TI.Alpha;
265
266                if (Alpha>80) Alpha-=40; else Alpha/=2;
267
268                glColor4ub(char(((FaceNr >> 0) & 3) << 6)+63,
269                           char(((FaceNr >> 2) & 3) << 6)+63,
270                           char(((FaceNr >> 4) & 3) << 6)+63, Alpha);
271
272                glBegin(GL_TRIANGLE_FAN);
273                    for (unsigned long VertexNr=0; VertexNr<F.Vertices.Size(); VertexNr++)
274                        glVertex3d(F.Vertices[VertexNr].x, F.Vertices[VertexNr].z, -F.Vertices[VertexNr].y);
275                glEnd();
276            }
277
278            glDisable(GL_BLEND);
279
280
281            // Spezielle Teile (Leaf 'DrawLeafNr') rendern.
282            {
283                glColor3f(0.5, 0.5, 1.0);
284                glDisable(GL_DEPTH_TEST);
285
286                if (DrawLeafNr<World->BspTree->Leaves.Size())
287                {
288                    for (unsigned long PortalNr=0; PortalNr<World->BspTree->Leaves[DrawLeafNr].Portals.Size(); PortalNr++)
289                    {
290                        const Polygon3T<double>& Portal=World->BspTree->Leaves[DrawLeafNr].Portals[PortalNr];
291
292                        glBegin(GL_LINE_LOOP);
293                            for (unsigned long VertexNr=0; VertexNr<Portal.Vertices.Size(); VertexNr++)
294                                glVertex3d(Portal.Vertices[VertexNr].x, Portal.Vertices[VertexNr].z, -Portal.Vertices[VertexNr].y);
295                        glEnd();
296                    }
297                }
298            }
299
300            glEnable(GL_DEPTH_TEST);
301        }
302
303        SingleOpenGLWindow->SwapBuffers();
304
305
306        CaKeyboardEventT KE;
307        bool QuitProgram=false;
308
309        while (SingleOpenGLWindow->GetNextKeyboardEvent(KE)>0)
310        {
311            if (KE.Type!=CaKeyboardEventT::CKE_KEYDOWN) continue;
312
313            if (KE.Key==CaKeyboardEventT::CK_ESCAPE) QuitProgram=true;
314
315            switch (KE.Key)
316            {
317                case CaKeyboardEventT::CK_ADD     : MoveSpeed*=2.0; printf("Movement speed doubled.\n"); break;
318                case CaKeyboardEventT::CK_SUBTRACT: MoveSpeed/=2.0; printf("Movement speed halved.\n"); break;
319                case CaKeyboardEventT::CK_L:
320                    if (SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_LSHIFT] || SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_RSHIFT])
321                    {
322                        // Großes 'L'.
323                        DrawLeafNr=World->BspTree->WhatLeaf(Viewer);
324                        printf("DrawLeafNr==%lu\n", DrawLeafNr);
325                        break;
326                    }
327                    else
328                    {
329                        // Kleines 'l'.
330                        unsigned long LeafNr=World->BspTree->WhatLeaf(Viewer);
331                        bool          InnerL=World->BspTree->Leaves[LeafNr].IsInnerLeaf;
332
333                        printf("WhatLeaf(Viewer)==%lu (\"%s\")\n", LeafNr, InnerL ? "inner" : "outer");
334                        printf("%5lu Faces: ", World->BspTree->Leaves[LeafNr].FaceChildrenSet.Size());
335                        for (unsigned long SetNr=0; SetNr<World->BspTree->Leaves[LeafNr].FaceChildrenSet.Size(); SetNr++) printf("%5lu", World->BspTree->Leaves[LeafNr].FaceChildrenSet[SetNr]);
336                        printf("\n");
337                        break;
338                    }
339                case CaKeyboardEventT::CK_O:
340                    if (SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_LSHIFT] || SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_RSHIFT])
341                    {
342                        // Großes 'O'.
343                        if (DrawLeafNr==0) DrawLeafNr=World->BspTree->Leaves.Size()-1;
344                                      else DrawLeafNr--;
345                        printf("DrawLeafNr==%lu\n", DrawLeafNr);
346                        break;
347                    }
348                    else
349                    {
350                        // Kleines 'o'.
351                        DrawLeafNr++;
352                        if (DrawLeafNr>=World->BspTree->Leaves.Size()) DrawLeafNr=0;
353                        printf("DrawLeafNr==%lu\n", DrawLeafNr);
354                        break;
355                    }
356                case CaKeyboardEventT::CK_P: printf("Position: (%.3f %.3f %.3f)\n", Viewer.x, Viewer.y, Viewer.z); break;
357                default: break;
358            }
359        }
360
361        const float vx=float(MoveSpeed*sin(Heading/180.0*3.1415926));
362        const float vy=float(MoveSpeed*cos(Heading/180.0*3.1415926));
363
364        if (SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_UP    ] || SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_W]) Viewer=Viewer+VectorT( vx,  vy, 0);
365        if (SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_DOWN  ] || SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_S]) Viewer=Viewer+VectorT(-vx, -vy, 0);
366        if (                                                                       SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_A]) Viewer=Viewer+VectorT(-vy,  vx, 0);
367        if (                                                                       SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_D]) Viewer=Viewer+VectorT( vy, -vx, 0);
368        if (SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_INSERT] || SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_R]) Viewer.z+=MoveSpeed;
369        if (SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_DELETE] || SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_F]) Viewer.z-=MoveSpeed;
370        if (SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_LEFT  ]                                                                  ) Heading-=RotSpeed;
371        if (SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_RIGHT ]                                                                  ) Heading+=RotSpeed;
372        if (SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_PGUP  ]                                                                  ) Pitch-=RotSpeed;
373        if (SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_PGDN  ]                                                                  ) Pitch+=RotSpeed;
374        if (SingleOpenGLWindow->GetKeyboardState()[CaKeyboardEventT::CK_END   ]                                                                  ) Pitch=0.0;
375
376        if (QuitProgram) break;
377    }
378
379    SingleOpenGLWindow->Close();
380}
381
382
383void PrintMapInfo()
384{
385    struct HelperT
386    {
387        const WorldT* HelperWorld;
388
389        unsigned long CurrentDepth;
390        unsigned long MinDepth;
391        unsigned long MaxDepth;
392        unsigned long TotalDepthSum;
393        unsigned long SeperateLeafCount;
394
395
396        HelperT(const WorldT* World_) : HelperWorld(World_)
397        {
398            CurrentDepth     =0;
399            MinDepth         =0xFFFFFFFF;
400            MaxDepth         =0;
401            TotalDepthSum    =0;
402            SeperateLeafCount=0;
403        }
404
405
406        void WalkDepthTree(unsigned long NodeNr)
407        {
408            CurrentDepth++;
409
410            if (HelperWorld->BspTree->Nodes[NodeNr].FrontIsLeaf)
411            {
412                if (MinDepth>CurrentDepth) MinDepth=CurrentDepth;
413                if (MaxDepth<CurrentDepth) MaxDepth=CurrentDepth;
414
415                TotalDepthSum+=CurrentDepth;
416                SeperateLeafCount++;
417            }
418            else WalkDepthTree(HelperWorld->BspTree->Nodes[NodeNr].FrontChild);
419
420            if (HelperWorld->BspTree->Nodes[NodeNr].BackIsLeaf)
421            {
422                if (MinDepth>CurrentDepth) MinDepth=CurrentDepth;
423                if (MaxDepth<CurrentDepth) MaxDepth=CurrentDepth;
424
425                TotalDepthSum+=CurrentDepth;
426                SeperateLeafCount++;
427            }
428            else WalkDepthTree(HelperWorld->BspTree->Nodes[NodeNr].BackChild);
429
430            CurrentDepth--;
431        }
432    } Helper(World);
433
434    printf("Map summary:\n");
435    printf("Faces         : %6lu\n", World->BspTree->FaceChildren.Size());
436    printf("Nodes         : %6lu\n", World->BspTree->Nodes.Size());
437    printf("Leaves        : %6lu\n", World->BspTree->Leaves.Size());
438
439    printf("\nBSP tree data:\n");
440    Helper.WalkDepthTree(0);
441    printf("Leaf count         : %6lu\n", Helper.SeperateLeafCount);
442    printf("Maximum tree depth : %6lu\n", Helper.MaxDepth);
443    printf("Minimum tree depth : %6lu\n", Helper.MinDepth);
444    printf("Average tree depth : %6lu\n", Helper.TotalDepthSum/Helper.SeperateLeafCount);
445
446    printf("\nPVS, LightMap, and SHL info:\n");
447    printf("PVS size (bytes)         : %12lu\n", World->BspTree->PVS.Size()*4);
448    unsigned long Checksum=0;
449    for (unsigned long Count=0; Count<World->BspTree->PVS.Size(); Count++)
450    {
451        Checksum+=(World->BspTree->PVS[Count] >> 24) & 0xFF;
452        Checksum+=(World->BspTree->PVS[Count] >> 16) & 0xFF;
453        Checksum+=(World->BspTree->PVS[Count] >>  8) & 0xFF;
454        Checksum+=(World->BspTree->PVS[Count]      ) & 0xFF;
455    }
456    printf("PVS checksum             : %12lu\n", Checksum);
457    printf("\n");
458    printf("LightMapMan.Bitmaps      : %12lu  (at %ux%u, PatchSize %.2f)\n", World->LightMapMan.Bitmaps.Size(), cf::SceneGraph::LightMapManT::SIZE_S, cf::SceneGraph::LightMapManT::SIZE_T, cf::SceneGraph::FaceNodeT::LightMapInfoT::PatchSize);
459    printf("LightMaps total size     : %12lu\n", World->LightMapMan.Bitmaps.Size()*(cf::SceneGraph::LightMapManT::SIZE_S*cf::SceneGraph::LightMapManT::SIZE_T*3+4));
460    printf("\n");
461    printf("SHL Bands                : %12u  (%u^2 == %u coefficients)\n", cf::SceneGraph::SHLMapManT::NrOfBands, cf::SceneGraph::SHLMapManT::NrOfBands, cf::SceneGraph::SHLMapManT::NrOfBands*cf::SceneGraph::SHLMapManT::NrOfBands);
462    printf("SHL Representatives      : %12u  %s\n", cf::SceneGraph::SHLMapManT::NrOfRepres, cf::SceneGraph::SHLMapManT::NrOfRepres>0 ? "" : "(NO compression)");
463    printf("SHL patch size           : %12.1f\n", cf::SceneGraph::FaceNodeT::SHLMapInfoT::PatchSize);
464    printf("SHLMaps                  : %12lu  (at %lux%lu)\n", World->SHLMapMan.SHLMaps.Size(), cf::SceneGraph::SHLMapManT::SIZE_S, cf::SceneGraph::SHLMapManT::SIZE_T);
465
466    if (cf::SceneGraph::SHLMapManT::NrOfRepres>0)
467    {
468        const unsigned long NR_OF_SH_COEFFS    =cf::SceneGraph::SHLMapManT::NrOfBands * cf::SceneGraph::SHLMapManT::NrOfBands;
469        const unsigned long NrOfColumns        =(cf::SceneGraph::SHLMapManT::NrOfRepres+255)/256;   // =ceil(double(cf::SceneGraph::SHLMapManT::NrOfRepres)/256);
470        const unsigned long NrOfPixelsPerVector=(NR_OF_SH_COEFFS+3)/4;
471
472        unsigned long Width=1; while (Width<NrOfColumns*NrOfPixelsPerVector) Width*=2;
473
474        printf("There are %u representatives with %lu SH coeffs each.\n", cf::SceneGraph::SHLMapManT::NrOfRepres, NR_OF_SH_COEFFS);
475        printf("They are stored in %lu columns (%lu pixels per column).\n", NrOfColumns, NrOfPixelsPerVector);
476        printf("The look-up texture thus has dimensions %lu x 256.\n", Width);
477    }
478
479    printf("\n\nDo you want to see the face details? (press 'y' to confirm)\n");
480    if (_getch()=='y')
481        for (unsigned long FaceNr=0; FaceNr<World->BspTree->FaceChildren.Size(); FaceNr++)
482        {
483            const cf::SceneGraph::FaceNodeT* FN=World->BspTree->FaceChildren[FaceNr];
484
485            printf("\n");
486            printf("Face%5lu, MatName '%s', LightMap %3u, Plane (%7.4f %7.4f %7.4f) %14.3f\n", FaceNr, FN->Material->Name.c_str(), FN->LightMapInfo.LightMapNr, FN->Polygon.Plane.Normal.x, FN->Polygon.Plane.Normal.y, FN->Polygon.Plane.Normal.z, FN->Polygon.Plane.Dist);
487
488            for (unsigned long VertexNr=0; VertexNr<FN->Polygon.Vertices.Size(); VertexNr++)
489                printf("    (%14.3f %14.3f %14.3f)\n", FN->Polygon.Vertices[VertexNr].x, FN->Polygon.Vertices[VertexNr].y, FN->Polygon.Vertices[VertexNr].z);
490        }
491}
492
493
494void TestValidityOfFacesAndPortals()
495{
496    for (unsigned long FaceNr=0; FaceNr<World->BspTree->FaceChildren.Size(); FaceNr++)
497        if (!World->BspTree->FaceChildren[FaceNr]->Polygon.IsValid(MapT::RoundEpsilon, MapT::MinVertexDist))
498            printf("Face   %4lu is INVALID!\n", FaceNr);
499
500    for (unsigned long LeafNr=0; LeafNr<World->BspTree->Leaves.Size(); LeafNr++)
501    {
502        const cf::SceneGraph::BspTreeNodeT::LeafT& L=World->BspTree->Leaves[LeafNr];
503
504        if (!L.IsInnerLeaf && L.FaceChildrenSet.Size()>0)
505        {
506            VectorT Near=World->BspTree->FaceChildren[L.FaceChildrenSet[0]]->Polygon.Vertices[0];
507
508            printf("Outer Leaf %4lu has a non-empty FaceChildrenSet!\n",   LeafNr);
509            printf("FaceChildrenSet of that leaf:\n");
510            for (unsigned long FaceNr=0; FaceNr<L.FaceChildrenSet.Size(); FaceNr++) printf("%lu ", L.FaceChildrenSet[FaceNr]);
511            printf("\nThe 1st vertex of the 1st face is at\n   (%14.3f %14.3f %14.3f).\n", Near.x, Near.y, Near.z);
512        }
513
514        if (!L.IsInnerLeaf && L.Portals.Size()>0) printf("Outer Leaf %4lu has a non-empty PortalSet!\n", LeafNr);
515
516        for (unsigned long PortalNr=0; PortalNr<L.Portals.Size(); PortalNr++)
517            if (!L.Portals[PortalNr].IsValid(MapT::RoundEpsilon, MapT::MinVertexDist))
518                printf("Portal %4lu (Leaf %4lu) is INVALID!\n", PortalNr, LeafNr);
519    }
520}
521
522
523void TestPVSIntegrity()
524{
525    unsigned long Leaf1Nr;
526
527    for (Leaf1Nr=0; Leaf1Nr<World->BspTree->Leaves.Size(); Leaf1Nr++)
528        for (unsigned long Leaf2Nr=0; Leaf2Nr<World->BspTree->Leaves.Size(); Leaf2Nr++)
529            if (Visible(Leaf1Nr, Leaf2Nr) && !Visible(Leaf2Nr, Leaf1Nr))
530                printf("WARNING: Can see from%5lu to%5lu, but not vice versa!\n", Leaf1Nr, Leaf2Nr);
531
532    for (Leaf1Nr=0; Leaf1Nr<World->BspTree->Leaves.Size(); Leaf1Nr++)
533        for (unsigned long Leaf2Nr=0; Leaf2Nr<World->BspTree->Leaves.Size(); Leaf2Nr++)
534            if (Visible(Leaf1Nr, Leaf2Nr) && (!World->BspTree->Leaves[Leaf1Nr].IsInnerLeaf || !World->BspTree->Leaves[Leaf2Nr].IsInnerLeaf))
535                printf("WARNING: Can see from%5lu to%5lu, but%5lu is \"%s\", and%5lu is \"%s\"!\n",
536                    Leaf1Nr, Leaf2Nr, Leaf1Nr, World->BspTree->Leaves[Leaf1Nr].IsInnerLeaf ? "inner" : "outer", Leaf2Nr, World->BspTree->Leaves[Leaf2Nr].IsInnerLeaf ? "inner" : "outer");
537}
538
539
540void Test10SmallestPortals()
541{
542    printf("   Note: If two or more portals have the same area, only ONE of them is listed!\n");
543
544    for (char Nr=0; Nr<10; Nr++)
545    {
546        static double LastWinnerArea=0;
547        unsigned long CurrentLNr    =World->BspTree->Leaves.Size();
548        unsigned long CurrentPNr    =0;
549        double        CurrentArea   =1000000.0;
550
551        for (unsigned long LeafNr=0; LeafNr<World->BspTree->Leaves.Size(); LeafNr++)
552        {
553            const cf::SceneGraph::BspTreeNodeT::LeafT& L=World->BspTree->Leaves[LeafNr];
554
555            for (unsigned long PortalNr=0; PortalNr<L.Portals.Size(); PortalNr++)
556            {
557                double PortalArea=L.Portals[PortalNr].GetArea();
558
559                if (PortalArea<CurrentArea && PortalArea>LastWinnerArea)
560                {
561                    CurrentLNr =LeafNr;
562                    CurrentPNr =PortalNr;
563                    CurrentArea=PortalArea;
564                }
565            }
566        }
567
568        if (CurrentLNr==World->BspTree->Leaves.Size()) { printf("WARNING: NOT SO MANY PORTALS!?!\n"); break; }
569
570        VectorT V=World->BspTree->Leaves[CurrentLNr].Portals[CurrentPNr].Vertices[0];
571        printf("%2u, L#%5lu, P#%3lu, Vertex0 (%9.2f %9.2f %9.2f), Area: %10.2f\n", Nr+1, CurrentLNr, CurrentPNr, V.x, V.y, V.z, CurrentArea);
572
573        LastWinnerArea=CurrentArea;
574    }
575}
576
577
578void Usage()
579{
580    printf("\nUSAGE:\n");
581    printf("CaSanity WorldName                    for normal operation\n");
582    printf("CaSanity WorldName -ListTexNames      list texture names  (OBSOLETE!!)\n");
583    printf("CaSanity WorldName -GetSkyName        print sky name      (OBSOLETE!!)\n");
584    printf("CaSanity WorldName -GetTerrainMaps    print terrain map names\n");
585    printf("CaSanity WorldName -ExportLightMaps   export lightmaps to BMP files\n");
586    printf("CaSanity WorldName -ExportPVS         export PVS (to stdout)\n");
587    printf("CaSanity WorldName -PrintMatCounts    print material usage counts\n");
588    printf("CaSanity WorldName -ViewWorld         simple OpenGL world viewer\n");
589    exit(0);
590}
591
592
593int main(int ArgC, char* ArgV[])
594{
595    if (ArgC>1 && std::string(ArgV[1])=="-p")
596    {
597        // Generate a password
598        if (ArgC!=4) { printf("CaSanity -p length seed\n"); exit(0); }
599
600        const unsigned long Length=atoi(ArgV[2]);
601        const unsigned long Seed  =atoi(ArgV[3]);
602
603        printf("OK, Length %lu, Seed %lu.\n", Length, Seed);
604
605        const ArrayT<unsigned char> Password=cf::Password::GenerateAsciiPassword(Length, Seed);
606        const ArrayT<unsigned char> ObfusStr=cf::Password::GenerateObfuscationString(Length);
607        const ArrayT<unsigned char> ObfusPwd=cf::Password::XOR(Password, ObfusStr);
608        const ArrayT<unsigned char> VerifyPw=cf::Password::XOR(ObfusPwd, ObfusStr);     // Must be identical to Password.
609
610        // The user should enter this into WinZip, 7-zip, InfoZip, ... to create the encrypted archive.
611        printf("Password: %s\n", cf::Password::ToString(Password).c_str());
612
613        // Output the obfuscated password as array of characters (C-Code).
614        printf("C array init code: %s\n", cf::Password::GenerateArrayCode(ObfusPwd).c_str());
615
616        // Make sure that VerifyPw==Password.
617        printf("Test de-obfuscation: %s\n", (Password.Size()==VerifyPw.Size() && cf::Password::ToString(Password)==cf::Password::ToString(VerifyPw)) ? "OK" : " !!! FAIL !!!");
618        exit(0);
619    }
620
621    if (ArgC<2 || ArgC>3) Usage();
622    if (ArgC==2) printf("\nCafu Map Debugging Tool, Version 02 (%s)\n\n", __DATE__);
623
624    // Initialize the FileMan by mounting the default file system.
625    // Note that specifying "./" (instead of "") as the file system description effectively prevents the use of
626    // absolute paths like "D:\abc\someDir\someFile.xy" or "/usr/bin/xy". This however should be fine for this application.
627    cf::FileSys::FileMan->MountFileSystem(cf::FileSys::FS_TYPE_LOCAL_PATH, "./", "");
628    cf::FileSys::FileMan->MountFileSystem(cf::FileSys::FS_TYPE_ZIP_ARCHIVE, "Games/DeathMatch/Textures/TechDemo.zip", "Games/DeathMatch/Textures/TechDemo/", "Ca3DE");
629    cf::FileSys::FileMan->MountFileSystem(cf::FileSys::FS_TYPE_ZIP_ARCHIVE, "Games/DeathMatch/Textures/SkyDomes.zip", "Games/DeathMatch/Textures/SkyDomes/", "Ca3DE");
630
631
632    std::string GameDirectory=ArgV[1];
633
634    // Determine the game directory, cleverly assuming that the destination file is in "Worlds".
635    {
636        // Strip the file name and extention off.
637        size_t i=GameDirectory.find_last_of("/\\");
638
639        GameDirectory=GameDirectory.substr(0, i==std::string::npos ? 0 : i)+"/..";
640    }
641
642
643    // Setup the global MaterialManager pointer.
644    static MaterialManagerImplT MatManImpl;
645
646    MaterialManager=&MatManImpl;
647
648    if (MaterialManager->RegisterMaterialScriptsInDir(GameDirectory+"/Materials", GameDirectory+"/").Size()==0)
649    {
650        printf("\nNo materials found in scripts in \"%s/Materials\".\n", GameDirectory.c_str());
651        printf("No materials found.\n\n");
652        Usage();
653    }
654
655
656    try
657    {
658        if (ArgC==2) printf("Loading world %s...\n\n", ArgV[1]);
659        ModelManagerT ModelMan;
660        World=new WorldT(ArgV[1], ModelMan);
661
662        // Gib ggf. nur die gewünschten Infos aus
663        if (ArgC==3)
664        {
665                 if (!_stricmp(ArgV[2], "-ListTexNames"   )) printf("%s\n", "NOT SUPPORTED!");
666            else if (!_stricmp(ArgV[2], "-GetSkyName"     )) printf("%s\n", "NOT SUPPORTED!");
667            else if (!_stricmp(ArgV[2], "-GetTerrainMaps" )) printf("%s\n", "NOT SUPPORTED!");
668            else if (!_stricmp(ArgV[2], "-ExportLightMaps")) ExportLightMaps(ArgV[1]);
669            else if (!_stricmp(ArgV[2], "-ExportPVS"      )) ExportPVS();
670            else if (!_stricmp(ArgV[2], "-PrintMatCounts" )) { PrintMaterialCounts(1); PrintMaterialCounts(2); PrintMaterialCounts(3); }
671            else if (!_stricmp(ArgV[2], "-ViewWorld"      )) ViewWorld();
672            else                                            Usage();
673
674            return 0;
675        }
676
677        PrintMapInfo();
678
679        printf("\n\n--- Now, several sanity checks will be performed on this map.  ---\n");
680        printf("--- Press any key after each test to begin with the next test. ---\n\n");
681        _getch();
682
683        printf("\n1. Validity of face and portal polygons:\n");  TestValidityOfFacesAndPortals(); printf("Done. Press any key for the next test.\n\n"); _getch();
684        printf("\n2. PVS integrity:\n");                         TestPVSIntegrity();              printf("Done. Press any key for the next test.\n\n"); _getch();
685        printf("\n3. The 10 portals with the smallest area:\n"); Test10SmallestPortals();         printf("Done. Press any key for the next test.\n\n"); _getch();
686     // printf("\n4. LightMap Patch ratios:\n");                 LightMapPatchRatios();           printf("Done. Press any key for the next test.\n\n"); _getch();
687
688        // TO DO: Hier mal MapT::FillTJunctions aufrufen,
689        //        und prüfen, daß keine Vertices in einer Face doppelt vorkommen (sollte generell ein Prüfpunkt sein!)
690        //        und zählen, wieviele Vertices es vorher und nachher sind, Erhöhung in % ausgeben.
691        // TO DO: Existieren Vertices, deren Abstand <GeometryEpsilon ist, die aber ungleich sind??
692        //        Mit anderen Worten: Vertices A und B mit VectorEqual(A, B)==true müssen BITWEISE gleich sein.
693        // TO DO: Prüfe, ob Vertices, die in einer Plane liegen, DOCH einen Abstand zur Plane haben.
694        // TO DO: Prüfe, ob Faces mit Sky-Texture wirklich LightMap.SizeS==LightMap.SizeT==LightMap.Data.Size()==0 haben!
695        // TO DO: Bestimme die maximale Lightmap.Size und prüfe, ob SizeS oder SizeT > 128 !
696
697        delete World;
698        printf("--- All tests are completed! Press any key to leave. ---\n");
699        _getch();
700    }
701    catch (const WorldT::LoadErrorT& E)
702    {
703        printf("\nFATAL ERROR: %s\n", E.Msg);
704        printf("Program aborted.\n\n");
705    }
706
707    return 0;
708}
Note: See TracBrowser for help on using the browser.