root/cafu/trunk/CaLight/CaLight.cpp

Revision 455, 72.0 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 Lighting Utility ***/
25/***                       ***/
26/*** Der Herr sprach       ***/
27/***   Es werde Licht!     ***/
28/*** Und es wurde Licht.   ***/
29/*** Genesis               ***/
30/***                       ***/
31/*****************************/
32
33// ALLGEMEINE BEMERKUNGEN ZU FACES, LIGHTMAPS UND PATCHES:
34// Wir definieren eine LightMap als ein Rechteck aus s*t quadratischen Patches, die jeweils eine Face "abdecken".
35// Das Rechteck sollte bei gegebener Seitenlänge der Patches und gegebener Orientierung (entlang des UV-Koordinatensystems,
36// welches man mit Plane3T<double>::GetSpanVectors() erhält) möglichst kleine s- und t-Abmessungen haben. D.h., daß der linke Rand
37// der LightMap mit der kleinsten U-Koordinate der Vertices der Face zusammenfallen soll und der obere Rand mit der kleinsten
38// V-Koordinate.
39// Außerdem ziehen wir noch einen 1 Patch breiten Rahmen drumherum. Damit soll dem OpenGL-Renderer Rechnung getragen werden,
40// der zu jeder (s,t)-Koordinate den Mittelwert des umliegenden 2x2-Quadrats bestimmt (bilinear Filtering).
41
42#if defined(_WIN32) && defined (_MSC_VER)
43    #if (_MSC_VER<1300)
44        #define for if (false) ; else for
45    #endif
46#endif
47#ifdef _WIN32
48#define WIN32_LEAN_AND_MEAN
49#include <windows.h>
50#include <conio.h>
51#else
52#include <stdarg.h>
53#include <unistd.h>
54#include <string.h>
55#define _stricmp strcasecmp
56#define _strnicmp strncasecmp
57#define _getch getchar
58#endif
59
60#include <time.h>
61#include <stdio.h>
62#include <cassert>
63
64#include "Templates/Array.hpp"
65#include "Math3D/Plane3.hpp"
66#include "Bitmap/Bitmap.hpp"
67#include "ConsoleCommands/Console.hpp"
68#include "ConsoleCommands/ConsoleInterpreter.hpp"
69#include "ConsoleCommands/ConsoleStdout.hpp"
70#include "FileSys/FileManImpl.hpp"
71#include "MaterialSystem/Material.hpp"
72#include "MaterialSystem/MaterialManager.hpp"
73#include "MaterialSystem/MaterialManagerImpl.hpp"
74#include "Models/ModelManager.hpp"
75#include "SceneGraph/Node.hpp"
76#include "SceneGraph/BspTreeNode.hpp"
77#include "SceneGraph/FaceNode.hpp"
78#include "ClipSys/CollisionModelMan_impl.hpp"
79
80#include "CaLightWorld.hpp"
81
82#if defined(_WIN32)
83    #if defined(_MSC_VER)
84        #define vsnprintf _vsnprintf
85    #endif
86#endif
87
88
89static cf::ConsoleStdoutT ConsoleStdout;
90cf::ConsoleI* Console=&ConsoleStdout;
91
92static cf::FileSys::FileManImplT FileManImpl;
93cf::FileSys::FileManI* cf::FileSys::FileMan=&FileManImpl;
94
95static cf::ClipSys::CollModelManImplT CCM;
96cf::ClipSys::CollModelManI* cf::ClipSys::CollModelMan=&CCM;
97
98ConsoleInterpreterI* ConsoleInterpreter=NULL;
99MaterialManagerI*    MaterialManager   =NULL;
100
101
102const time_t ProgramStartTime=time(NULL);
103
104// Returns a string with the elapsed time since program start.
105// The string is in the format "hh:mm:ss".
106static const char* GetTimeSinceProgramStart()
107{
108    const unsigned long TotalSec=(unsigned long)difftime(time(NULL), ProgramStartTime);
109    const unsigned long Sec     =TotalSec % 60;
110    const unsigned long Min     =(TotalSec/60) % 60;
111    const unsigned long Hour    =TotalSec/3600;
112
113    static char TimeString[16];
114    sprintf(TimeString, "%2lu:%2lu:%2lu", Hour, Min, Sec);
115
116    return TimeString;
117}
118
119
120static void Error(const char* ErrorText, ...)
121{
122    va_list ArgList;
123    char    ErrorString[256];
124
125    if (ErrorText!=NULL)
126    {
127        va_start(ArgList, ErrorText);
128            vsnprintf(ErrorString, 256, ErrorText, ArgList);
129        va_end(ArgList);
130
131        printf("\nFATAL ERROR: %s\n", ErrorString);
132    }
133
134    printf("Program aborted.\n\n");
135    exit(1);
136}
137
138
139/// This class implements a diagonally symmetric matrix for two-bit numbers,
140/// that is, the elements of the matrix can only be the numbers 0, 1, 2 or 3.
141///
142/// Implementation notes:
143/// - Only the lower left half of the matrix is physically stored.
144/// - Each matrix element is physically represented by two bits.
145/// - The elements in turn are stored in tuples of 16 in "unsigned long"s.
146/// - Assumes that the type "unsigned long" has (at least) 32 bits.
147class DiagMatrixT
148{
149    public:
150
151    /// Creates a DiagMatrixT of size 0.
152    DiagMatrixT()
153    {
154    }
155
156    /// (Re-)sets the size of this DiagMatrixT to n*n and initializes the elements with zeros.
157    void SetSize(unsigned long n)
158    {
159        const unsigned long NrOfElements=(n*(n+1))/2;
160
161        Data.Clear();
162        Data.PushBackEmpty((NrOfElements+15)/16);
163
164        for (unsigned long i=0; i<Data.Size(); i++) Data[i]=0;
165    }
166
167    /// Returns the value at (row, col).
168    char GetValue(unsigned long row, unsigned long col) const
169    {
170        if (col>row) return GetValue(col, row);
171
172        const unsigned long ElementIdx=(row*(row+1))/2 + col;
173        const unsigned long DataIdx   =ElementIdx / 16;     // The requested value is somewhere in Data[DataIdx],
174        const unsigned long DataOfs   =ElementIdx % 16;     // namely the DataOfs-th one.
175
176        return char((Data[DataIdx] >> (DataOfs*2)) & 3);
177    }
178
179    /// Sets the value at (row, col). Note that value must be 0, 1, 2 or 3.
180    void SetValue(unsigned long row, unsigned long col, char value)
181    {
182        if (col>row) { SetValue(col, row, value); return; }
183
184        const unsigned long ElementIdx=(row*(row+1))/2 + col;
185        const unsigned long DataIdx   =ElementIdx / 16;     // The requested value is somewhere in Data[DataIdx],
186        const unsigned long DataOfs   =ElementIdx % 16;     // namely the DataOfs-th one.
187
188        unsigned long ClearMask=~(3ul << (DataOfs*2));      // 1s everywhere, except for the two bits of our element data.
189        unsigned long Val      =value & 3;
190
191        Data[DataIdx]&=ClearMask;
192        Data[DataIdx]|=(Val << (DataOfs*2));
193    }
194
195    unsigned long GetBytesAlloced() const
196    {
197        return Data.Size()*sizeof(unsigned long);
198    }
199
200    /// Implements a simple test case for objects of this class. Returns true if all tests pass, false otherwise.
201    /// The contents of the matrix after the test is undefined.
202    bool Test();
203
204
205    private:
206
207    ArrayT<unsigned long> Data;
208};
209
210
211bool DiagMatrixT::Test()
212{
213    SetSize(3);
214    if (Data.Size()<1) return false;
215
216    // Test 1
217    {
218        // Note that a 5*5 matrix requires physical storage for 15 elements,
219        // and thus 30 bits, which in turn all fit into the first "unsigned long".
220        Data[0]=0;
221        unsigned long Val=0;
222        for (unsigned long r=0; r<=4; r++)
223            for (unsigned long c=0; c<=r; c++)
224            {
225                SetValue(r, c, char(Val % 4));
226                if (GetValue(r, c)!=Val % 4) return false;
227                if (GetValue(c, r)!=Val % 4) return false;
228                Val++;
229            }
230
231        if (Data[0]!=0x24E4E4E4) return false;
232    }
233
234    // Test 2
235    {
236        // Same as above, but with r and c in SetValue() reversed.
237        Data[0]=0;
238        unsigned long Val=0;
239        for (unsigned long r=0; r<=4; r++)
240            for (unsigned long c=0; c<=r; c++)
241            {
242                SetValue(c, r, char(Val % 4));
243                if (GetValue(r, c)!=Val % 4) return false;
244                if (GetValue(c, r)!=Val % 4) return false;
245                Val++;
246            }
247
248        if (Data[0]!=0x24E4E4E4) return false;
249    }
250
251    Data[0]=0;
252    return true;
253}
254
255
256static double Max3(const VectorT& V)
257{
258    double m=V.x;
259
260    if (V.y>m) m=V.y;
261    if (V.z>m) m=V.z;
262
263    return m;
264}
265
266
267const double REFLECTIVITY=0.3;  // Gleiche Reflektivität für alle Faces und für alle Wellenlängen
268
269
270ArrayT<cf::PatchMeshT> PatchMeshes; // The patch meshes that we should consider for radiosity lighting.
271
272#include "Init2.cpp"    // void InitializePatches      (const cf::SceneGraph::BspTreeNodeT& Map, const SkyDomeT& SkyDome) { ... }
273
274
275enum PatchMeshesMutualVisE { NO_VISIBILITY=0, PARTIAL_VISIBILITY=1/*, FULL_VISIBILITY=2*/ };
276
277std::map< const cf::SceneGraph::GenericNodeT*, ArrayT<unsigned long> > NodePtrToPMIndices;
278DiagMatrixT PatchMeshesPVS;     // The matrix that determines which patch meshes a patch mesh can see (see InitializePatchMeshesPVS() for a description!).
279
280#include "Init1.cpp"    // void InitializePatchMeshesPVS(const cf::SceneGraph::BspTreeNodeT& Map                         ) { ... }
281
282
283static unsigned long Count_AllCalls=0;
284static unsigned long Count_DivgWarnCalls=0;
285
286// Strahlt die Energie der Patches im n*n Quadrat ab, dessen linke obere Ecke bei (s_i, t_i) liegt
287void RadiateEnergy(const CaLightWorldT& CaLightWorld, unsigned long PM_i, unsigned long s_i, unsigned long t_i, char n)
288{
289    cf::PatchMeshT& PatchMesh_i=PatchMeshes[PM_i];
290
291    cf::PatchT    Big_P_i;
292    unsigned long Big_P_i_Count=0;
293
294    // A cf::PatchT has no explicit constructor. While its Vector3T<T> components are implicitly 0'ed,
295    // make sure that the Area members starts at 0, too.
296    Big_P_i.Area=0;
297
298    // Bilde den Positions-Durchschnitt bzw. die UnradiatedEnergy-Summe aller Patches im n*n Quadrat,
299    // wobei (s_i, t_i) die linke obere Ecke ist und nur Patches innerhalb des Patch Meshes (InsideFace) berücksichtigt werden.
300    for (char y=0; y<n; y++)
301        for (char x=0; x<n; x++)
302        {
303            unsigned long s_=s_i+x;
304            unsigned long t_=t_i+y;
305
306            if (PatchMesh_i.WrapsHorz && s_>=PatchMesh_i.Width ) s_-=PatchMesh_i.Width;
307            if (PatchMesh_i.WrapsVert && t_>=PatchMesh_i.Height) t_-=PatchMesh_i.Height;
308
309            if (s_>=PatchMesh_i.Width ) continue;
310            if (t_>=PatchMesh_i.Height) continue;
311
312            cf::PatchT& P_i=PatchMesh_i.GetPatch(s_, t_);
313            if (!P_i.InsideFace) continue;
314
315            Big_P_i_Count++;
316            Big_P_i.Coord           +=P_i.Coord;
317            Big_P_i.Normal          +=P_i.Normal;
318            Big_P_i.Area            +=P_i.Area;
319            Big_P_i.UnradiatedEnergy+=P_i.UnradiatedEnergy;
320
321            P_i.UnradiatedEnergy=VectorT(0, 0, 0);
322        }
323
324    if (!Big_P_i_Count) return;
325
326    const double NormalLen=length(Big_P_i.Normal);
327
328    // Before CaLight took the individual areas of the patches into account (it was assumed that they all had the same area PATCH_SIZE*PATCH_SIZE),
329    // the Big_P_i patch worked (and still does) by simply summing up the UnradiatedEnergy fields of its component P_i patches.
330    // This in turn naturally shows how to extend the code to also take patch areas into account, because thinking of Big_P_i as a patch of the
331    // same size as any patch at that time (namely PATCH_SIZE*PATCH_SIZE, or rather the average of the area of its component patches) but with
332    // a higher UnradiatedEnergy (the sum of all component patches) is equivalent to thinking of Big_P_i as having only the *average*
333    // UnradiatedEnergy but the sum of the *areas* of its component patches!
334    // This naturally leads to the conclusion that AreaRatio_ij=Big_P_i.Area/P_j.Area should enter the equation below.
335    // Note that independent of that, with Big_P_i we have the choice to either average its UnradiatedEnergy or its Area, thus thinking about
336    // it the one way or the other -- the net result in DeltaRadiosity below is the same. For historical reasons, I've chosen to keep the
337    // UnradiatedEnergy and average the Area.
338    Big_P_i.Coord*=1.0/Big_P_i_Count;   // TODO! Sollte   Big_P_i.Coord=P_i.Coord;   setzen, wobei P_i derjenige Patch ist der der Durchschnittsposition am nächsten kommt. Nur so kommen wir auch mit gekrümmten, twosided PatchMeshes wirklich klar!
339    Big_P_i.Normal=(NormalLen>0.000001) ? Big_P_i.Normal/NormalLen : Vector3dT(0, 0, 1);
340    Big_P_i.Area/=Big_P_i_Count;
341    // printf("%f %lu blocksize=%i^2 %f\n", Big_P_i.Area, Big_P_i_Count, n, PATCH_SIZE*PATCH_SIZE);
342
343    // It doesn't matter if we take the total or the average Big_P_i.Area here - the division cancels itself out below.
344    const double MinRayLength=sqrt(Big_P_i.Area);
345
346    // We keep here the maximum amount of energy that's left to be shot to other patches, or rather, as the value is premultiplied by REFLECTIVITY,
347    // the maximum amount of energy that all the other patches may have accumulated as UnradiatedEnergy when Big_P_i has finished shooting.
348    // This mechanism is used as a safety-guard against diverging behaviour below.
349    // Divergence should theoretically never occur, but practically is can arise when the RayLength below is too short in relation to the patch size.
350    // Note that the EnergyBudget code as well as the MinRayLength/SafeRayLength code both fight divergency problems, so it might be
351    // worthwhile to temporariliy disable one while you wish to examine the other.
352    // The factor DIVG_MARGIN is for rounding errors, and intentionally chosen big, because in the presence of translucent surfaces,
353    // we actually (and wrongly) shoot more energy than we normally should, namely that onto the first opaque surface as well
354    // as onto all translucent surfaces along the way. (That is, whenever faces that receive but DO NOT(!) block radiance are present.)
355    // Also see   svn log -r 287   point f) for some additional information.
356    // However, note that with   svn log -r 289   I largely disable this stuff again, because I feel that the "divergency case" triggers far
357    // too often at DIVG_MARGIN=1.6 (which in turn aborts the radiation of the current patch hard in mid-progress).
358    // As I don't seem to understand the nature of the frequent occurrences sufficiently, I rather collect only statistics about this approach
359    // for now instead of having hard aborts with unknown results on lighting quality, and rely on the "MinRayLength" as the sole divergency
360    // prevention technique.
361    const double DIVG_MARGIN=2.1;
362    VectorT EnergyBudget=Big_P_i.UnradiatedEnergy*(REFLECTIVITY*DIVG_MARGIN);
363
364    Count_AllCalls++;
365
366
367    // Betrachte alle Patches aller Patch Meshes im PVS des Patch Meshes PM_i.
368    for (unsigned long PM_j=0; PM_j<PatchMeshes.Size(); PM_j++)
369    {
370        // Vermeide alle unnötigen und evtl. rundungsfehlergefährdeten Berechnungen.
371        // Wenn PM_i und PM_j planar sind, fängt die folgende Zeile auch alle Fälle ab, in denen PM_j in der Ebene
372        // von PM_i liegt und insb. für die PM_i==PM_j gilt. Für nichtplanare PM muß all das aber nicht unbedingt gelten
373        // (z.B. Terrains und manche Bezier Patches beleuchten sich selbst)!
374        // Vgl. die Erstellung und Optimierung der PatchMeshesPVS-Matrix!
375        if (PatchMeshesPVS.GetValue(PM_i, PM_j)==NO_VISIBILITY) continue;
376
377        cf::PatchMeshT& PatchMesh_j=PatchMeshes[PM_j];
378
379#if 1
380        // It would be interesting to know how fast dynamic_cast really is.
381        // May it be faster to disable this "abbreviation" code after all??
382        const cf::SceneGraph::FaceNodeT* FaceNode_j=dynamic_cast<const cf::SceneGraph::FaceNodeT*>(PatchMesh_j.Node);
383        if (FaceNode_j && FaceNode_j->Polygon.Plane.GetDistance(Big_P_i.Coord)<0.1) continue;
384#endif
385
386        for (unsigned long Patch_j=0; Patch_j<PatchMesh_j.Patches.Size(); Patch_j++)
387        {
388            cf::PatchT& P_j=PatchMesh_j.Patches[Patch_j];
389            if (!P_j.InsideFace) continue;
390
391
392            const VectorT Ray      =P_j.Coord-Big_P_i.Coord;
393            const double  RayLength=length(Ray);
394
395            if (RayLength<0.5) continue;   // Kommt das jemals vor?
396
397            const VectorT Dir_ij=scale(Ray, 1.0/RayLength);
398            const double  cos1  = dot(Big_P_i.Normal, Dir_ij); if (cos1<=0) continue;
399            const double  cos2  =-dot(P_j.Normal,     Dir_ij); if (cos2<=0) continue;
400
401            if (CaLightWorld.TraceRay(Big_P_i.Coord, Ray)<1.0) continue;
402
403            // 'Alternative', einfache Herleitung des Form-Faktors:
404            // Betrachte die Halbkugel über dem Patch i mit Radius RayLength. RayLength soll groß genug sein,
405            // d.h. Patch j soll problemlos als ein Teil der Halbkugeloberfläche betrachtet werden können.
406            // Die prozentuale Sichtbarkeit erhalten wir also sofort aus P_j.Area/O, wobei O der Oberflächeninhalt der Halbkugel ist,
407            // O=0.5*4*pi*RayLength^2.
408            // cos1 und cos2 berücksichtigen dann noch die gegenseitige Verdrehung der Patches und wir sind fertig.
409            // Einziges Problem: Obige Herleitung enthält noch einen Faktor 1/2, für den ich leider keine Erklärung habe.
410            // Noch eine Alternative: Man muß RayLength ausdrücken in Patch-Längen, nicht in Millimetern!
411            const double SafeRayLength=(RayLength>MinRayLength) ? RayLength : MinRayLength;
412
413         // const double FormFactor_ij=P_j.Area/3.14159265359*cos1*cos2/(SafeRayLength*SafeRayLength);
414         // const double AreaRatio_ij =Big_P_i.Area/P_j.Area;
415         // const double Total_ij     =FormFactor_ij*AreaRatio_ij;
416            const double Total_ij     =Big_P_i.Area/3.14159265359*cos1*cos2/SafeRayLength/SafeRayLength;
417
418            // if (Total_ij>1.0) printf("WARNING: Total_ij==%f > 1.0\n", Total_ij);
419
420            // Beachte: Big_P_i.UnradiatedEnergy ist schon die Summe der Einzelpatches, nicht deren Durchschnitt!
421            // Clamp Total_ij to its natural maximum of 1.0 in order to avoid an increase of light energy in the system (even if REFLECTIVITY is at 100%).
422            const VectorT DeltaRadiosity=scale(Big_P_i.UnradiatedEnergy, (Total_ij<1.0) ? REFLECTIVITY*Total_ij : REFLECTIVITY);
423
424            EnergyBudget-=DeltaRadiosity;
425            if (EnergyBudget.x<0.0 || EnergyBudget.y<0.0 || EnergyBudget.z<0.0)
426            {
427                static unsigned long Count_LastWarn=0;
428
429                if (Count_LastWarn!=Count_AllCalls)
430                {
431                    Count_DivgWarnCalls++;
432                    // printf("\nDivergency warning for patch mesh %lu. Total divergency warning count: %lu.\n", PM_i, Count_DivgWarnCalls);
433                    Count_LastWarn=Count_AllCalls;      // The last divergency warning was generated in this call.
434                }
435
436                // return;      // Note that this *aborts* the radiation of the energy of this patch.
437            }
438
439            P_j.UnradiatedEnergy+=DeltaRadiosity;
440            P_j.TotalEnergy     +=DeltaRadiosity;
441            P_j.EnergyFromDir   -=Dir_ij*Max3(DeltaRadiosity);  // The -= instead of += is intentional, as we want the direction from j to i.
442        }
443    }
444}
445
446
447inline static double ComputePatchWeight(unsigned long i, unsigned long Width, double RangeWidth)
448{
449    const double PatchBegin=double()/Width;
450    const double PatchEnd  =double(i+1)/Width;
451
452    double RangeBegin=0.5-RangeWidth*0.5;
453    double RangeEnd  =0.5+RangeWidth*0.5;
454
455    assert(PatchBegin<=PatchEnd);
456    assert(RangeBegin<=RangeEnd);
457
458    // Clip the range against the patch (build the union of the two intervals).
459    if (PatchBegin>=RangeEnd  ) return 0;   // The union is empty.
460    if (PatchEnd  <=RangeBegin) return 0;   // The union is empty.
461
462    if (RangeBegin<PatchBegin) RangeBegin=PatchBegin;
463    if (RangeEnd  >PatchEnd  ) RangeEnd  =PatchEnd;
464
465    return (RangeEnd-RangeBegin)/(PatchEnd-PatchBegin);
466}
467
468
469void DirectLighting(const CaLightWorldT& CaLightWorld, const char BLOCK_SIZE)
470{
471    const cf::SceneGraph::BspTreeNodeT& Map=CaLightWorld.GetBspTree();
472
473    printf("\n%-50s %s\n", "*** PHASE I - performing direct lighting ***", GetTimeSinceProgramStart());
474
475
476    // 1. Area light sources
477    // *********************
478
479    // A patch mesh is an area light source if it has a material for which a radiant exitance value has been defined.
480    // Here we assign such patch meshes their initial radiating power and also make them radiate it off into the environment.
481    unsigned long LightSourceCount=0;
482
483    for (unsigned long PatchMeshNr=0; PatchMeshNr<PatchMeshes.Size(); PatchMeshNr++)
484    {
485        cf::PatchMeshT& PM     =PatchMeshes[PatchMeshNr];
486        const VectorT   RadExit=VectorT(PM.Material->meta_RadiantExitance_Values);
487
488        if (length(RadExit)<0.1) continue;
489
490        LightSourceCount++;
491        printf("%5.1f%%\r", (double)PatchMeshNr/PatchMeshes.Size()*100.0);
492        fflush(stdout);
493
494        double LongerSideRange =1.0;
495        double ShorterSideRange=1.0;
496
497        if (PM.Material->Name=="TechDemo/lights/reactor-light1")
498        {
499            LongerSideRange =0.77;
500            ShorterSideRange=0.49;
501        }
502        else if (PM.Material->Name=="TechDemo/lights/reactor-trimlight1")
503        {
504            LongerSideRange =0.25;
505            ShorterSideRange=0.55;
506        }
507
508        const double WidthRange =(PM.Width>=PM.Height) ? LongerSideRange : ShorterSideRange;
509        const double HeightRange=(PM.Width>=PM.Height) ? ShorterSideRange : LongerSideRange;
510
511        // Ordne den Patches den RadExit-Wert zu.
512        for (unsigned long t=0; t<PM.Height; t++)
513            for (unsigned long s=0; s<PM.Width; s++)
514            {
515                cf::PatchT& Patch=PM.Patches[t*PM.Width+s];
516
517                // Ein Patch darf zum Leuchten nicht komplett außerhalb seiner Face liegen!
518                if (!Patch.InsideFace) continue;
519
520                const double    Weight=ComputePatchWeight(s, PM.Width, WidthRange)*ComputePatchWeight(t, PM.Height, HeightRange);
521                const Vector3dT RadExitWeighted=RadExit*Weight;
522
523                Patch.UnradiatedEnergy+=RadExitWeighted;
524                Patch.TotalEnergy     +=RadExitWeighted;
525                Patch.EnergyFromDir   +=Patch.Normal*Max3(RadExitWeighted);
526            }
527
528        // Die Patches dürfen auch gleich einmal strahlen.
529        // Könnte man hier auch weglassen, aber so ist es eigentlich im Sinne von 'direct lighting'.
530        for (unsigned long t=0; t<PM.Height; t+=BLOCK_SIZE)
531            for (unsigned long s=0; s<PM.Width; s+=BLOCK_SIZE)
532                RadiateEnergy(CaLightWorld, PatchMeshNr, s, t, BLOCK_SIZE);
533    }
534    printf("1. # area  light sources: %6lu\n", LightSourceCount);
535
536
537    // 2. Point light sources
538    // **********************
539
540    ArrayT<bool> PatchMeshIsInPVS;
541    PatchMeshIsInPVS.PushBackEmpty(PatchMeshes.Size());
542
543    // Let point light sources radiate their energy into the environment.
544    // Subtlety: In comparison with the sunlight calculations, point light sources cast 'harder' shadows
545    // because we only consider one sample point for each patch (its Coord), instead of five as for the sunlight ray tests.
546    for (unsigned long PLNr=0; PLNr<CaLightWorld.GetPointLights().Size(); PLNr++)
547    {
548        const PointLightT&  PL        =CaLightWorld.GetPointLights()[PLNr];
549        const double        cosPLAngle=cos(PL.Angle);
550        const unsigned long PL_LeafNr =Map.WhatLeaf(PL.Origin);
551
552        if (PL.Intensity.x==0.0 && PL.Intensity.y==0.0 && PL.Intensity.z==0.0) continue;
553
554        printf("%5.1f%%\r", (double)PLNr/CaLightWorld.GetPointLights().Size()*100.0);
555        fflush(stdout);
556
557        for (unsigned long PatchMeshNr=0; PatchMeshNr<PatchMeshIsInPVS.Size(); PatchMeshNr++)
558            PatchMeshIsInPVS[PatchMeshNr]=false;
559
560        for (unsigned long LeafNr=0; LeafNr<Map.Leaves.Size(); LeafNr++)
561        {
562            const cf::SceneGraph::BspTreeNodeT::LeafT& L=Map.Leaves[LeafNr];
563
564            if (!Map.IsInPVS(LeafNr, PL_LeafNr)) continue;
565
566            for (unsigned long SetNr=0; SetNr<L.FaceChildrenSet.Size(); SetNr++)
567            {
568                const ArrayT<unsigned long>& PMIndices=NodePtrToPMIndices[Map.FaceChildren[L.FaceChildrenSet[SetNr]]];
569
570                for (unsigned long i=0; i<PMIndices.Size(); i++)
571                    PatchMeshIsInPVS[PMIndices[i]]=true;
572            }
573
574            for (unsigned long SetNr=0; SetNr<L.OtherChildrenSet.Size(); SetNr++)
575            {
576                const ArrayT<unsigned long>& PMIndices=NodePtrToPMIndices[Map.OtherChildren[L.OtherChildrenSet[SetNr]]];
577
578                for (unsigned long i=0; i<PMIndices.Size(); i++)
579                    PatchMeshIsInPVS[PMIndices[i]]=true;
580            }
581        }
582
583
584        for (unsigned long PatchMeshNr=0; PatchMeshNr<PatchMeshes.Size(); PatchMeshNr++)
585        {
586            if (!PatchMeshIsInPVS[PatchMeshNr]) continue;
587
588            cf::PatchMeshT& PM=PatchMeshes[PatchMeshNr];
589
590#if 1
591            // It would be interesting to know how fast dynamic_cast really is.
592            // May it be faster to disable this "abbreviation" code after all??
593            const cf::SceneGraph::FaceNodeT* FaceNode=dynamic_cast<const cf::SceneGraph::FaceNodeT*>(PM.Node);
594            if (FaceNode!=NULL && FaceNode->Polygon.Plane.GetDistance(PL.Origin)<0.1) continue;
595#endif
596
597            for (unsigned long t=0; t<PM.Height; t++)
598                for (unsigned long s=0; s<PM.Width; s++)
599                {
600                    cf::PatchT& Patch=PM.Patches[t*PM.Width+s];
601                    if (!Patch.InsideFace) continue;
602
603                    const VectorT  LightRay      =Patch.Coord-PL.Origin;    // Patch.Coord already includes a small safety distance to its plane.
604                    const double   LightRayLength=length(LightRay);
605                    const VectorT  LightRayDir   =scale(LightRay, 1.0/LightRayLength);
606                    const double   LightRayDot   =dot(LightRayDir, Patch.Normal);   // The cosine of the angle between the two vectors.
607
608                    // The LightRay must meet the patch from above (opposite to the direction of its normal).
609                    if (LightRayDot>0.0) continue;
610
611                    // Test if this ray is inside the defined cone.
612                    if (dot(LightRayDir, PL.Dir)<cosPLAngle) continue;
613
614                    if (CaLightWorld.TraceRay(PL.Origin, LightRay)<1.0) continue;
615
616                    if (LightRayLength>=cf::SceneGraph::FaceNodeT::LightMapInfoT::PatchSize)
617                    {
618                        // Let I be an abbreviation for PL.Intensity, which is specified in [W/sr]. Then, any sphere centered at PL.Origin with radius
619                        // r receives a total power of 4*pi*I [W] on its surface, which is equal to 4*pi*(r^2) [unit of r^2]. It follows immediately
620                        // that if we choose r=1m, I/(r^2) yields the 'irradiance' in [W/m^2] for the surface of the sphere with radius r=1m.
621                        // Note that 'irradiance' is a little misleading here, because we only deal with rays of light that meet at PL.Origin.
622                        // The sphere is not considered and can not be treated as an area light source!
623                        // Now choose r=LightRayLength. Because r is now specified in millimeters, the base unit of Cafu, we need to express it in
624                        // meters first in order to obtain [W/m^2] (and not [W/mm^2]).
625                        // Thus, I/((LightRayLength/1000)^2) gives us the 'irradiance' [W/m^2] for the surface of the sphere with radius LightRayLength.
626                        // This is especially true for the point where LightRay ends. Therefore, because LightRay ends in the center of the patch we
627                        // are interested in, we have calculated exactly what we need!
628                        // Note that we assumed that the patch is formed like a part of the sphere. Actually, that is not true -- patches are planar.
629                        // Fortunately, we can ignore that because the patch should be small enough compared to the radius of the sphere.
630                        // Related to that is the fact that every point inside the patch has a different LightRay. We ignore that, too, because
631                        // we consider the center of the patch and hope that by doing so, +/- errors cancel each other out.
632                        // Finally, we need to take the orientation of the patch into account by multiplying with the cosine of the relative angle:
633                        // -I*(1000/LightRayLength)^2*dot(VectorUnit(LightRay), F.Plane.Normal)
634                        // This assumes that LightRay is not the null vector, that PL.Origin is on front of F.Plane and that F.Normal is a unit vector!
635                        const double  c          =1000.0/LightRayLength;
636                        const VectorT DeltaEnergy=scale(PL.Intensity, -REFLECTIVITY*c*c*LightRayDot);
637
638                        Patch.UnradiatedEnergy+=DeltaEnergy;
639                        Patch.TotalEnergy     +=DeltaEnergy;
640                        Patch.EnergyFromDir   -=LightRayDir*Max3(DeltaEnergy);  // The -= is intentional, as we want the direction from the patch to the PL.
641                    }
642                    else
643                    {
644                        // Physikalisch korrekt wäre eine bis zur Unendlichkeit zunehmende Intensität, je kleiner LightRayLength.
645                        // Ist natürlich Blödsinn, da point light sources in der Realität nicht existieren.
646                        // Daher erzwingen wir hier einfach eine LightRayLength von cf::SceneGraph::FaceNodeT::LightMapInfoT::PatchSize und vernachlässigen
647                        // die Orientierung des Patches.
648                        const double  c          =1000.0/cf::SceneGraph::FaceNodeT::LightMapInfoT::PatchSize;
649                        const VectorT DeltaEnergy=scale(PL.Intensity, REFLECTIVITY*c*c);
650
651                        Patch.UnradiatedEnergy+=DeltaEnergy;
652                        Patch.TotalEnergy     +=DeltaEnergy;
653                        Patch.EnergyFromDir   -=LightRayDir*Max3(DeltaEnergy);  // The -= is intentional, as we want the direction from the patch to the PL.
654                    }
655                }
656        }
657    }
658    printf("2. # point light sources: %6lu\n", CaLightWorld.GetPointLights().Size());
659}
660
661
662#include "Ward97.cpp"   // void ToneReproduction(const cf::SceneGraph::BspTreeNodeT& Map) { ... }
663
664
665void PostProcessBorders(const CaLightWorldT& CaLightWorld)
666{
667    // An dieser Stelle haben wir nun quasi drei Sorten von Patches für eine Face:
668    // a) Patches, die 'InsideFace' liegen, und das vollständig.
669    // b) Patches, die 'InsideFace' liegen, aber nur teilweise (ihre Patch.Coord ist entsprechend verschoben!).
670    // c) Patches, die nicht 'InsideFace' liegen.
671    // Für Patch-Sorten a) und b) hat unser Algorithmus Patch.TotalEnergy-Werte berechnet.
672    // Unsere Aufgabe hier ist im wesentlichen das sinnvolle Ausfüllen der TotalEnergy-Werte von Patches der Sorte c).
673    // Dies ist notwendig, da die Patches von OpenGL beim Rendern bilinear interpoliert werden (2x2-Array Durchschnitt),
674    // und deswegen ohne weitere Maßnahmen schwarze Ränder bekämen.
675    printf("\n%-50s %s\n", "*** Post-Process Borders ***", GetTimeSinceProgramStart());
676
677
678    // ERSTER TEIL
679    // ***********
680
681    // Für alle Patches einer Face, die noch keine Energie abgekriegt haben (weil sie keinen SamplePoint innerhalb ihrer Face
682    // haben oder durch z.B. BezierPatches unglücklich "abgeschattet" wurden), ermittele ihren Wert aus dem
683    // Durchschnitt ihrer acht umliegenden Patches, sofern diese Energie abgekiegt haben (d.h. mit SamplePoints innerhalb
684    // der Face liegen und nicht komplett abgeschattet wurden).
685    // Diese Methode ist sehr einfach und schnell, da sie immer nur eine Face gleichzeitig betrachtet,
686    // die Nachbarumgebung hat keinen Einfluß.
687    // Dennoch ist diese Schleife ein guter Anfang, und war vorher sogar der *einzige* Nachbearbeitungsschritt!
688    for (unsigned long PatchMeshNr=0; PatchMeshNr<PatchMeshes.Size(); PatchMeshNr++)
689    {
690        cf::PatchMeshT& PM=PatchMeshes[PatchMeshNr];
691        ArrayT<bool>    InsideFaceEx;
692
693        for (unsigned long PatchNr=0; PatchNr<PM.Patches.Size(); PatchNr++)
694        {
695            const Vector3dT& TE=PM.Patches[PatchNr].TotalEnergy;
696
697            // In the extended meaning, a patch is *not* inside face if InsideFace==false or TE=(0, 0, 0).
698            InsideFaceEx.PushBack(PM.Patches[PatchNr].InsideFace && (TE.x>0.5/255.0 || TE.y>0.5/255.0 || TE.z>0.5/255.0));
699        }
700
701        for (unsigned long t=0; t<PM.Height; t++)
702            for (unsigned long s=0; s<PM.Width; s++)
703            {
704                cf::PatchT& Patch=PM.GetPatch(s, t);
705
706                if (InsideFaceEx[t*PM.Width+s]) continue;
707
708                Patch.TotalEnergy =VectorT(0, 0, 0);
709                Vector3dT AvgDir  =VectorT(0, 0, 0);    // Do NOT(!) build the average directly in Patch.EnergyFromDir, or else you may end with zero-vector dirs for patches in the midst of faces that have received no light at all!
710                double CoveredArea=0.0;
711
712                // Der Patch liegt in der Mitte eines 3x3-Feldes bei Koordinate (1,1).
713                for (char y=0; y<=2; y++)
714                    for (char x=0; x<=2; x++)
715                    {
716                        if (x==1 && y==1) continue;     // Nur die acht umliegenden Patches betrachten.
717
718                        int Nx=int(s+x)-1;
719                        int Ny=int(t+y)-1;
720
721                        if (PM.WrapsHorz)
722                        {
723                            // Patches that wrap do *not* duplicate the leftmost column at the right.
724                            if (Nx<             0) Nx+=PM.Width;
725                            if (Nx>=int(PM.Width)) Nx-=PM.Width;
726                        }
727
728                        if (PM.WrapsVert)
729                        {
730                            // Patches that wrap do *not* duplicate the topmost column at the bottom.
731                            if (Ny<              0) Ny+=PM.Height;
732                            if (Ny>=int(PM.Height)) Ny-=PM.Height;
733                        }
734
735                        if (Nx<              0) continue;   // Linken  Rand beachten.
736                        if (Nx>= int(PM.Width)) continue;   // Rechten Rand beachten.
737                        if (Ny<              0) continue;   // Oberen  Rand beachten.
738                        if (Ny>=int(PM.Height)) continue;   // Unteren Rand beachten.
739
740                        if (!InsideFaceEx[Ny*PM.Width+Nx]) continue;
741
742                        const double      RelevantArea=(x!=1 && y!=1) ? 0.25 : 0.5;
743                        const cf::PatchT& Neighb      =PM.GetPatch(Nx, Ny);
744
745                        Patch.TotalEnergy+=Neighb.TotalEnergy  *RelevantArea;
746                        AvgDir           +=Neighb.EnergyFromDir*RelevantArea;
747                        CoveredArea      +=RelevantArea;
748                    }
749
750                if (CoveredArea>0.0001)
751                {
752                    Patch.TotalEnergy  /=CoveredArea;
753                    Patch.EnergyFromDir+=AvgDir/CoveredArea;
754                }
755            }
756    }
757
758
759    // ZWEITER TEIL
760    // ************
761
762    // Betrachte im nächsten Schritt Faces, die in einer gemeinsamen Ebene nahe beieinander liegen, und versuche,
763    // den "Übergang" zu verbessern. Der vorangegangene erste Schritt eliminiert zwar Fehlfarben an den Rändern,
764    // die OpenGL's bilinear Filtering ansonsten ins Spiel gebracht hätte, an Stellen mit hohen Kontrasten
765    // ("scharfe" Schatten usw.) sieht man aber unbeabsichtigte, harte Übergänge an den Kanten solcher Faces.
766    // Der folgende Code eliminiert solche Sprünge nun größtenteils, indem er auch die Patches der anderen Faces betrachtet.
767    // Damit werden für die Ränder die "realen" Berechnungsergebnisse eingebracht, nicht einfach nur eigene Mittelwerte.
768    // Der folgende Code könnte algorithmisch effizienter geschrieben sein (z.B. Vorausberechnen von wiederkehrenden
769    // Werten, statt diese jedesmal in einer Schleife neu zu berechnen), aber die praktische Laufzeit ist akzeptabel.
770    // Außerdem ist der Code z.T. "experimentell" oder zumindest mathematisch nicht komplett durchdacht und die zugrunde-
771    // liegende Theorie ist evtl. sogar unvollständig oder falsch. Die Ergebnisse sind aber trotzdem ein voller Erfolg!
772    // Es besser zu machen ist jedenfalls SEHR schwierig. Bsp: Gewichtung und Art und Weise bei den Mittelwertbildungen usw.
773    // Bzgl. des "Light Bleeding" Problems scheint es sogar ÜBERHAUPT KEINE befriedigende, korrekte Lösung zu geben:
774    // Selbst mit Ausführung des folgenden Codes lassen sich nicht alle "Sprünge" zwischen Faces eliminieren,
775    // insbesondere an "Ecken" nicht. Der Grund liegt in der Natur der Patches, OpenGLs bilinear Filtering und dem
776    // Konflikt mit dem "Light Bleeding" Problem. Eine korrekte Lösung ist somit *unmöglich*!
777    // WICHTIG: Im Gegensatz z.B. zum Filtern des Sonnenlichts ist es in diesem Algorithmus *nicht* notwendig,
778    // erstmal ein Backup aller TotalEnergy-Werte der Patches aller Faces anzulegen, um korrekt Mittelwerte bilden zu
779    // können. Der Grund ist, daß wir nur *äußere* Patches einer Face mit *inneren* Patches der anderen Faces modifizieren!
780    // Es kommt also niemals zu Überschneidungen: (*) Kein Patch wird gesetzt/modifiziert, und später nochmal für das Setzen
781    // bzw. die Modifikation eines anderen Patches herangezogen! Dieses Ideal wird allerdings aufgeweicht durch die
782    // Existenz von inneren Patches, die nur teilweise innerhalb ihrer Face liegen: Hier wäre eine Verletzung der Eigenschaft
783    // (*) durchaus möglich. In einigen wenigen Spezialfällen kann dies durch die Eigenschaften der Plane3T<double>::GetSpanVectors()
784    // Funktion geheilt werden (ohne weitere Begründung), im Allgemeinfall jedoch nicht!
785    const double  PATCH_SIZE          =cf::SceneGraph::FaceNodeT::LightMapInfoT::PatchSize;
786    unsigned long PatchesWorkedOnCount=0;
787
788    for (unsigned long PatchMesh1Nr=0; PatchMesh1Nr<PatchMeshes.Size(); PatchMesh1Nr++)
789    {
790        cf::PatchMeshT&                  PM1      =PatchMeshes[PatchMesh1Nr];
791        const cf::SceneGraph::FaceNodeT* FaceNode1=dynamic_cast<const cf::SceneGraph::FaceNodeT*>(PM1.Node);
792
793        if (FaceNode1==NULL) continue;
794
795        const Polygon3T<double>& Face1=FaceNode1->Polygon;
796        ArrayT<unsigned long>    NearPatchMeshes;
797
798        printf("%5.1f%%\r", (double)PatchMesh1Nr/PatchMeshes.Size()*100.0);
799        fflush(stdout);
800
801        // Bilde zuerst eine Liste (von Indizes) von Faces, die Face1 "nahe" sind.
802        for (unsigned long PatchMesh2Nr=0; PatchMesh2Nr<PatchMeshes.Size(); PatchMesh2Nr++)
803        {
804            cf::PatchMeshT&                  PM2      =PatchMeshes[PatchMesh2Nr];
805            const cf::SceneGraph::FaceNodeT* FaceNode2=dynamic_cast<const cf::SceneGraph::FaceNodeT*>(PM2.Node);
806
807            if (FaceNode2==NULL) continue;
808
809            const Polygon3T<double>& Face2=FaceNode2->Polygon;
810
811            // Wir wollen nicht gegen uns selbst testen!
812            if (PatchMesh1Nr==PatchMesh2Nr) continue;
813
814            // Nur Faces in der gleichen Ebene mit gleicher Orientierung durchgehen lassen!
815            if (Face1.WhatSide(Face2.Plane, MapT::RoundEpsilon)!=Polygon3T<double>::InIdentical) continue;
816
817            // Faces, die zu weit voneinander entfernt liegen, brauchen nicht weiter betrachtet zu werden!
818            const VectorT BorderPadding(PATCH_SIZE, PATCH_SIZE, PATCH_SIZE);
819
820            BoundingBox3T<double> BB1(Face1.Vertices); BB1.Min=BB1.Min-BorderPadding; BB1.Max=BB1.Max+BorderPadding;
821            BoundingBox3T<double> BB2(Face2.Vertices); BB2.Min=BB2.Min-BorderPadding; BB2.Max=BB2.Max+BorderPadding;
822
823            if (!BB1.Intersects(BB2)) continue;
824
825            // Diese Face kommt in Betracht, speichere ihre Nummer.
826            NearPatchMeshes.PushBack(PatchMesh2Nr);
827        }
828
829        // Bereite nun das Patch1Poly vor. Unten werden dann nur noch die 4 Vertices ausgefüllt.
830        // Der folgende Code ist SEHR ähnlich zu dem Code in cf::SceneGraph::FaceNodeT::CreatePatchMeshes()!
831
832        // Bestimme die Spannvektoren.
833        VectorT Face1_U;
834        VectorT Face1_V;
835
836        Face1.Plane.GetSpanVectors(Face1_U, Face1_V);
837
838        // Finde SmallestU und SmallestV.
839        double Face1_SmallestU=dot(Face1.Vertices[0], Face1_U);
840        double Face1_SmallestV=dot(Face1.Vertices[0], Face1_V);
841
842        for (unsigned long VertexNr=1; VertexNr<Face1.Vertices.Size(); VertexNr++)
843        {
844            double u=dot(Face1.Vertices[VertexNr], Face1_U);
845            double v=dot(Face1.Vertices[VertexNr], Face1_V);
846
847            if (u<Face1_SmallestU) Face1_SmallestU=u;
848            if (v<Face1_SmallestV) Face1_SmallestV=v;
849        }
850
851        const VectorT Face1_UV_Origin=scale(Face1.Plane.Normal, Face1.Plane.Dist);
852        const VectorT Face1_Safety   =scale(Face1.Plane.Normal, 0.1);
853
854        Polygon3T<double> Patch1Poly;
855
856        Patch1Poly.Plane=dot(Face1.Plane.Normal, cross(Face1_U, Face1_V))<0 ? Face1.Plane : Face1.Plane.GetMirror();
857        Patch1Poly.Vertices.PushBackEmpty(4);
858
859        // Betrachte nun alle Patches von Face1
860        for (unsigned long t1=0; t1<PM1.Height; t1++)
861            for (unsigned long s1=0; s1<PM1.Width; s1++)
862            {
863                cf::PatchT&     Patch1=PM1.Patches[t1*PM1.Width+s1];
864                ArrayT<double>  Patch1_OverlapRatios;
865                ArrayT<VectorT> Patch1_OverlapTotalEnergies;
866                ArrayT<VectorT> Patch1_OverlapEnergyFromDirs;
867
868                // Rekonstruiere das Polygon zu Patch1
869                double s_=s1;
870                double t_=t1;
871
872                Patch1Poly.Vertices[0]=Face1_UV_Origin+scale(Face1_U, Face1_SmallestU+(s_-1.0)*PATCH_SIZE)+scale(Face1_V, Face1_SmallestV+(t_-1.0)*PATCH_SIZE);
873                Patch1Poly.Vertices[1]=Face1_UV_Origin+scale(Face1_U, Face1_SmallestU+ s_     *PATCH_SIZE)+scale(Face1_V, Face1_SmallestV+(t_-1.0)*PATCH_SIZE);
874                Patch1Poly.Vertices[2]=Face1_UV_Origin+scale(Face1_U, Face1_SmallestU+ s_     *PATCH_SIZE)+scale(Face1_V, Face1_SmallestV+ t_     *PATCH_SIZE);
875                Patch1Poly.Vertices[3]=Face1_UV_Origin+scale(Face1_U, Face1_SmallestU+(s_-1.0)*PATCH_SIZE)+scale(Face1_V, Face1_SmallestV+ t_     *PATCH_SIZE);
876
877                // WICHTIG: Falls Patch1 *vollständig in* seiner Face liegt, haben wir für dessen TotalEnergy einen
878                // einwandfreien Berechnungswert, und wir wollen daran nicht rumfummeln!
879                // Die anderen beiden Fälle für Patch1 sind:
880                // 1) 'InsideFace', aber nicht vollständig, d.h. Patch1Poly ragt etwas aus seiner Face heraus.
881                // 2) Nicht 'InsideFace', der Patch hat bestenfalls oben im ersten Teil einen Wert zugewiesen bekommen.
882                // Diese beiden Fälle wollen wir also nachbearbeiten, und zwar durch Mittelwertbildung mit überlappenden,
883                // INNEREN Patches von benachbarten Faces. Mehr dazu unten. Lasse also 1) und 2) passieren
884                // (die alte Bed. "if (Patch1.InsideFace) continue;" hätte nur 2) durchgehen lassen).
885                if (Face1.Encloses(Patch1Poly, true, MapT::RoundEpsilon)) continue;
886
887                // Den Mittelpunkt des Patch1Poly bestimmen, inkl. "Safety", sowie den Flächeninhalt
888                VectorT Patch1Poly_Center=scale(Patch1Poly.Vertices[0]+Patch1Poly.Vertices[1]+Patch1Poly.Vertices[2]+Patch1Poly.Vertices[3], 0.25)+Face1_Safety;
889                double  Patch1Poly_Area  =Patch1Poly.GetArea();
890
891                // Suche einen Punkt *IN* Face1 heraus, der "nahe" bei Patch1 liegt. Wird unten benötigt.
892                double  MinDistance=3.0*PATCH_SIZE;
893                VectorT InnerPointCloseToPatch1;
894
895                for (unsigned long PatchNr=0; PatchNr<PM1.Patches.Size(); PatchNr++)
896                {
897                    const cf::PatchT& TempPatch=PM1.Patches[PatchNr];
898
899                    // 'TempPatch' darf auch ruhig 'Patch1' sein, da 'Patch1.Coord' durchaus ein Punkt in Face1 ist,
900                    // der "nahe" bei Patch1 liegt!
901                    if (!TempPatch.InsideFace) continue;
902
903                    double Distance=length(TempPatch.Coord-Patch1Poly_Center);
904
905                    if (Distance<MinDistance)
906                    {
907                        MinDistance            =Distance;
908                        InnerPointCloseToPatch1=TempPatch.Coord;
909                    }
910                }
911
912                // Wurde auch etwas in der Nähe gefunden?
913                if (MinDistance==3.0*PATCH_SIZE) continue;
914
915                // Betrachte nun die umliegenden Faces
916                for (unsigned long NearNr=0; NearNr<NearPatchMeshes.Size(); NearNr++)
917                {
918                    cf::PatchMeshT&                  PM2      =PatchMeshes[NearPatchMeshes[NearNr]];
919                    const cf::SceneGraph::FaceNodeT* FaceNode2=dynamic_cast<const cf::SceneGraph::FaceNodeT*>(PM2.Node);
920
921                    assert(FaceNode2!=NULL);
922
923                    const Polygon3T<double>& Face2=FaceNode2->Polygon;
924
925                    // Bereite nun das Patch2Poly vor. Unten werden dann nur noch die 4 Vertices ausgefüllt.
926                    // Der folgende Code ist SEHR ähnlich zu dem Code in InitializePatches() (Init2.cpp)!
927                    VectorT Face2_U;
928                    VectorT Face2_V;
929
930                    Face2.Plane.GetSpanVectors(Face2_U, Face2_V);
931
932                    double Face2_SmallestU=dot(Face2.Vertices[0], Face2_U);   // Finde SmallestU und SmallestV
933                    double Face2_SmallestV=dot(Face2.Vertices[0], Face2_V);
934
935                    unsigned long VertexNr;
936
937                    for (VertexNr=1; VertexNr<Face2.Vertices.Size(); VertexNr++)
938                    {
939                        double u=dot(Face2.Vertices[VertexNr], Face2_U);
940                        double v=dot(Face2.Vertices[VertexNr], Face2_V);
941
942                        if (u<Face2_SmallestU) Face2_SmallestU=u;
943                        if (v<Face2_SmallestV) Face2_SmallestV=v;
944                    }
945
946                    const VectorT Face2_UV_Origin=scale(Face2.Plane.Normal, Face2.Plane.Dist);
947
948                    Polygon3T<double> Patch2Poly;
949
950                    Patch2Poly.Plane=dot(Face2.Plane.Normal, cross(Face2_U, Face2_V))<0 ? Face2.Plane : Face2.Plane.GetMirror();
951                    Patch2Poly.Vertices.PushBackEmpty(4);
952
953                    // Gehe die Patches von Face2 durch
954                    for (unsigned long t2=0; t2<PM2.Height; t2++)
955                        for (unsigned long s2=0; s2<PM2.Width; s2++)
956                        {
957                            const cf::PatchT& Patch2=PM2.Patches[t2*PM2.Width+s2];
958
959                            // Nur "äußere" Patches von Face1 mit "inneren" Patches von Face1 korrigieren!
960                            if (!Patch2.InsideFace) continue;
961
962                            // Rekonstruiere das Polygon zu Patch2
963                            double s_=s2;
964                            double t_=t2;
965
966                            Patch2Poly.Vertices[0]=Face2_UV_Origin+scale(Face2_U, Face2_SmallestU+(s_-1.0)*PATCH_SIZE)+scale(Face2_V, Face2_SmallestV+(t_-1.0)*PATCH_SIZE);
967                            Patch2Poly.Vertices[1]=Face2_UV_Origin+scale(Face2_U, Face2_SmallestU+ s_     *PATCH_SIZE)+scale(Face2_V, Face2_SmallestV+(t_-1.0)*PATCH_SIZE);
968                            Patch2Poly.Vertices[2]=Face2_UV_Origin+scale(Face2_U, Face2_SmallestU+ s_     *PATCH_SIZE)+scale(Face2_V, Face2_SmallestV+ t_     *PATCH_SIZE);
969                            Patch2Poly.Vertices[3]=Face2_UV_Origin+scale(Face2_U, Face2_SmallestU+(s_-1.0)*PATCH_SIZE)+scale(Face2_V, Face2_SmallestV+ t_     *PATCH_SIZE);
970
971                            // Überlappen sich PatchPoly1 und PatchPoly2?
972                            if (!Patch1Poly.Overlaps(Patch2Poly, false, MapT::RoundEpsilon)) continue;
973
974                            // Zerschneide Patch2Poly entlang Patch1Poly, und behalte nur das Stück, das "in" Patch1Poly liegt:
975                            ArrayT< Polygon3T<double> > NewPolygons;
976
977                            Patch2Poly.GetChoppedUpAlong(Patch1Poly, MapT::RoundEpsilon, NewPolygons);
978                            if (NewPolygons.Size()==0) Error("PolygonChopUp failed in PostProcessBorders().");
979
980                            // Bestimme den Mittelpunkt des überlappenden Stücks in Patch1Poly (inkl. "Safety") und prüfe,
981                            // ob von dort aus der nahe Punkt in Face1 erreichbar ist.
982                            const Polygon3T<double>& OverlapPoly      =NewPolygons[NewPolygons.Size()-1];
983                            VectorT                  OverlapPolyCenter=OverlapPoly.Vertices[0];
984
985                            for (VertexNr=1; VertexNr<OverlapPoly.Vertices.Size(); VertexNr++)
986                                OverlapPolyCenter=OverlapPolyCenter+OverlapPoly.Vertices[VertexNr];
987
988                            OverlapPolyCenter=scale(OverlapPolyCenter, 1.0/double(OverlapPoly.Vertices.Size()))+Face1_Safety;
989
990                            // Begründung für den folgenden Test:
991                            // Es besteht die Gefahr, daß wir an dieser Stelle unerwünschtes "Light Bleeding" erzeugen.
992                            // "Light Bleeding" ist die Beeinflussung von Patches durch andere Patches, deren Faces sich
993                            // zwar nahe sind, aber in Wirklichkeit z.B. durch eine dünne "Wand" getrennt,
994                            // oder die Patches liegen "um die Ecke".
995                            // Um das "Light Bleeding" Problem zu minimieren, erlauben wir die Beeinflussung von Patch1
996                            // durch Patch2 nur dann, wenn das 'OverlapPolyCenter' vom 'InnerPointCloseToPatch1' aus
997                            // sichtbar ist.
998                            // All dies ist analytisch nicht wirklich befriedigend -- eine bessere Lösung scheint es
999                            // aber auch nicht zu geben: Zu groß ist der Konflikt bzw. die gestellten Ansprüche.
1000                            // Das praktische Ergebnis ist allerdings sehr wohl brauchbar, denn das Ziel wird,
1001                            // abgesehen von kleineren "Ausreißern", erreicht.
1002                            if (CaLightWorld.TraceRay(InnerPointCloseToPatch1, OverlapPolyCenter-InnerPointCloseToPatch1)<1.0) continue;
1003
1004                            // Zu wieviel Prozent überlappt das verbleibende Stück PatchPoly1?
1005                            double OverlapRatio=OverlapPoly.GetArea()/Patch1Poly_Area;
1006
1007                            // 'OverlapRatio*=0.5;', falls 'Patch1.InsideFace==true' ist!?
1008                            // Merke das Ergebnis zur späteren Durchschnittsbildung.
1009                            Patch1_OverlapRatios        .PushBack(OverlapRatio        );
1010                            Patch1_OverlapTotalEnergies .PushBack(Patch2.TotalEnergy  );
1011                            Patch1_OverlapEnergyFromDirs.PushBack(Patch2.EnergyFromDir);
1012                        }
1013                }
1014
1015
1016                // Die folgende Zeile ist nicht wirklich nötig. Der 'PatchesWorkedOnCount' wird dadurch aber sinnvoller.
1017                if (Patch1_OverlapRatios.Size()==0) continue;
1018
1019                double OverlapRatioSum=0.0;
1020
1021                for (unsigned long OverlapNr=0; OverlapNr<Patch1_OverlapRatios.Size(); OverlapNr++)
1022                {
1023                    if (Patch1_OverlapRatios[OverlapNr]<0.000) Error("Negative overlap percentage!");
1024                    if (Patch1_OverlapRatios[OverlapNr]>1.001) Error("Overlap is greater than 100%%!");
1025
1026                    OverlapRatioSum+=Patch1_OverlapRatios[OverlapNr];
1027                }
1028
1029                if (OverlapRatioSum>1.0)
1030                {
1031                    // Da eine Face an einem Vertice mit beliebig vielen anderen Faces "zusammenstoßen" kann,
1032                    // kann ein Patch dieser Face dort von beliebig vielen anderen Patches überlagert werden,
1033                    // die sich dann z.T. wieder unter sich überlappen.
1034                    // So kann eine Abdeckung mit Patches über 100% entstehen.
1035                    // Wir skalieren dann einfach wieder auf 100% zurück.
1036                    for (unsigned long OverlapNr=0; OverlapNr<Patch1_OverlapRatios.Size(); OverlapNr++)
1037                        Patch1_OverlapRatios[OverlapNr]/=OverlapRatioSum;
1038                }
1039                else
1040                {
1041                    // Patch1 war nicht ganz von anderen Patches bedeckt.
1042                    // Fülle daher den Rest mit dem eigenen, alten Wert auf!
1043                    Patch1_OverlapRatios        .PushBack(1.0-OverlapRatioSum);
1044                    Patch1_OverlapTotalEnergies .PushBack(Patch1.TotalEnergy);
1045                    Patch1_OverlapEnergyFromDirs.PushBack(Patch1.EnergyFromDir);
1046                }
1047
1048                Patch1.TotalEnergy  =VectorT(0,0,0);
1049                Patch1.EnergyFromDir=VectorT(0,0,0);
1050
1051                for (unsigned long OverlapNr=0; OverlapNr<Patch1_OverlapRatios.Size(); OverlapNr++)
1052                {
1053                    Patch1.TotalEnergy  +=scale(Patch1_OverlapTotalEnergies [OverlapNr], Patch1_OverlapRatios[OverlapNr]);
1054                    Patch1.EnergyFromDir+=scale(Patch1_OverlapEnergyFromDirs[OverlapNr], Patch1_OverlapRatios[OverlapNr]);
1055                }
1056
1057                PatchesWorkedOnCount++;
1058            }
1059    }
1060
1061    printf("Borders completed. %lu patches modified in 2nd part.\n", PatchesWorkedOnCount);
1062}
1063
1064
1065unsigned long BounceLighting(const CaLightWorldT& CaLightWorld, const char BLOCK_SIZE, double& StopUE, const bool AskForMore, const char* WorldName)
1066{
1067    printf("\n%-50s %s\n", "*** PHASE II - performing bounce lighting ***", GetTimeSinceProgramStart());
1068
1069    unsigned long IterationCount =0;
1070    unsigned long FullSearchCount=0;
1071
1072    while (true)
1073    {
1074        unsigned long PM_i  =0;
1075        unsigned long s_i   =0;
1076        unsigned long t_i   =0;
1077        double        BestUE=0;     // Best unradiated energy amount found
1078
1079        // Finde ein PatchMesh mit einem Patch mit einer großen UnradiatedEnergy (nicht notwendigerweise die größte, damit es schnell geht).
1080        for (unsigned long PatchMeshNr=0; PatchMeshNr<PatchMeshes.Size(); PatchMeshNr++)
1081        {
1082            // Achtung: PM.Patches.Size() kann auch 0 sein!
1083            const cf::PatchMeshT& PM         =PatchMeshes[PatchMeshNr];
1084            unsigned long         NrOfSamples=PM.Patches.Size()<10 ? PM.Patches.Size()/2 : 10;
1085
1086            for (unsigned long SampleNr=0; SampleNr<NrOfSamples; SampleNr++)
1087            {
1088                unsigned long s=rand() % PM.Width;      // Funktioniert nicht mehr gut wenn PM.Width >RAND_MAX
1089                unsigned long t=rand() % PM.Height;     // Funktioniert nicht mehr gut wenn PM.Height>RAND_MAX
1090
1091                s=(s/BLOCK_SIZE)*BLOCK_SIZE;
1092                t=(t/BLOCK_SIZE)*BLOCK_SIZE;
1093
1094                unsigned long Count =0;
1095                double        ThisUE=0;
1096
1097                for (char y=0; y<BLOCK_SIZE; y++)
1098                    for (char x=0; x<BLOCK_SIZE; x++)
1099                    {
1100                        unsigned long s_=s+x;
1101                        unsigned long t_=t+y;
1102
1103                        if (PM.WrapsHorz && s_>=PM.Width ) s_-=PM.Width;
1104                        if (PM.WrapsVert && t_>=PM.Height) t_-=PM.Height;
1105
1106                        if (s_>=PM.Width ) continue;
1107                        if (t_>=PM.Height) continue;
1108
1109                        const cf::PatchT& P_i=PM.Patches[t_*PM.Width+s_];
1110                        if (!P_i.InsideFace) continue;
1111
1112                        ThisUE+=P_i.UnradiatedEnergy.x+P_i.UnradiatedEnergy.y+P_i.UnradiatedEnergy.z;
1113                        Count++;
1114                    }
1115
1116                if (!Count) continue;
1117                ThisUE/=double(Count);
1118
1119                if (ThisUE>BestUE)
1120                {
1121                    PM_i  =PatchMeshNr;
1122                    s_i   =s;
1123                    t_i   =t;
1124                    BestUE=ThisUE;
1125                }
1126            }
1127        }
1128
1129        // Sollte die BestUE unter StopUE sein, wird hier nach einem besseren Wert gesucht.
1130        // Beim erstbesseren Wert wird dieser genommen und abgebrochen, ansonsten gesucht bis zum Schluß.
1131        // Wenn alle Faces nach dem besten Wert durchsucht werden sollen, muß "&& BestUE<StopUE" auskommentiert werden.
1132        if (BestUE<StopUE)
1133        {
1134            FullSearchCount++;      // Zähle, wie oft wir alles abgesucht haben!
1135
1136            for (unsigned long PatchMeshNr=0; PatchMeshNr<PatchMeshes.Size() && BestUE<StopUE; PatchMeshNr++)
1137            {
1138                const cf::PatchMeshT& PM=PatchMeshes[PatchMeshNr];
1139
1140                for (unsigned long s=0; s<PM.Width; s++)
1141                    for (unsigned long t=0; t<PM.Height; t++)
1142                    {
1143                        const VectorT& E     =PM.Patches[t*PM.Width+s].UnradiatedEnergy;
1144                        double         ThisUE=E.x+E.y+E.z;
1145
1146                        if (ThisUE>BestUE)
1147                        {
1148                            PM_i  =PatchMeshNr;
1149                            s_i   =s;
1150                            t_i   =t;
1151                            BestUE=ThisUE;
1152                        }
1153                    }
1154            }
1155        }
1156
1157        printf("Iteration%6lu, BestUE %6.2f, PM_i%6lu, FullSearch%4lu (%5.1f%%)\r", IterationCount, BestUE, PM_i, FullSearchCount, 100.0*float(FullSearchCount)/float(IterationCount+1));
1158        fflush(stdout);
1159
1160        if (BestUE<StopUE)  // Es gab keinen besseren Wert mehr -- wir können also abbrechen!
1161        {
1162            printf("\n");
1163            if (!AskForMore) break;
1164
1165            time_t StartTime=time(NULL);
1166
1167            printf("\nStopUE value %10.7f has been reached.\n", StopUE);
1168            printf("Press 'y' to confirm exit and save current result,\n");
1169            printf("or any other key to divide StopUE by 10 and continue lighting!\n");
1170
1171            char Key=_getch(); if (Key==0) _getch();
1172
1173            unsigned long TotalSec=(unsigned long)difftime(time(NULL), StartTime);
1174            unsigned long Sec     =TotalSec % 60;
1175            unsigned long Min     =(TotalSec/60) % 60;
1176            unsigned long Hour    =TotalSec/3600;
1177            printf("Length of break (waiting for your decision) was %2lu:%2lu:%2lu.\n", Hour, Min, Sec);
1178
1179            if (Key=='y') break;
1180            StopUE/=10.0;
1181        }
1182
1183        RadiateEnergy(CaLightWorld, PM_i, s_i, t_i, BLOCK_SIZE);
1184        IterationCount++;
1185
1186#ifdef _WIN32
1187        // TODO: Ein (sinnvolles!) 'kbhit()' Äquivalent für Linux muß erst noch gefunden werden...
1188        if (_kbhit())
1189        {
1190            char Key=_getch(); if (Key==0) _getch();
1191
1192            if (Key==' ')
1193            {
1194                printf("\nINTERRUPTED BY USER!\n");
1195                printf("Enter 'Y' to confirm exit and save current result,\n");
1196                printf("Enter 'S' to save the intermediate result, then continue,\n");
1197                printf("or press any other key to continue lighting!\n");
1198
1199                Key=_getch(); if (Key==0) _getch();
1200
1201                if (Key=='Y') break;
1202                if (Key=='S')
1203                {
1204                    printf("\n%-50s %s\n", "*** START Saving of Intermediate Results ***", GetTimeSinceProgramStart());
1205                    ArrayT<cf::PatchMeshT> SafePMs=PatchMeshes;
1206
1207
1208                    ToneReproduction(CaLightWorld);
1209                    PostProcessBorders(CaLightWorld);
1210
1211                    printf("\n%-50s %s\n", "*** Write Patch values back into LightMaps ***", GetTimeSinceProgramStart());
1212                    for (unsigned long PatchMeshNr=0; PatchMeshNr<PatchMeshes.Size(); PatchMeshNr++)
1213                    {
1214                        cf::PatchMeshT&               PM     =PatchMeshes[PatchMeshNr];
1215                        cf::SceneGraph::GenericNodeT* PM_Node=const_cast<cf::SceneGraph::GenericNodeT*>(PM.Node);
1216
1217                        // Need a non-const pointer to the "source" NodeT of the patch mesh here.
1218                        PM_Node->BackToLightMap(PM);
1219                    }
1220
1221                    printf("\n%-50s %s\n", "*** Saving World ***", GetTimeSinceProgramStart());
1222                    std::string SaveName=std::string(WorldName)+"_";
1223                    printf("%s\n", SaveName.c_str());
1224                    CaLightWorld.SaveToDisk(SaveName.c_str());
1225
1226
1227                    // Restore the state as it was before the saving.
1228                    PatchMeshes=SafePMs;
1229                    printf("\n%-50s %s\n", "*** END Saving of Intermediate Results ***", GetTimeSinceProgramStart());
1230                }
1231            }
1232        }
1233#endif
1234    }
1235
1236    return IterationCount;
1237}
1238
1239
1240void Usage()
1241{
1242    printf("\n");
1243    printf("USAGE: CaLight WorldName [OPTIONS]\n");
1244    printf("\n");
1245    printf("-gd=somePath   Specifies the game directory of the world. Try for example\n");
1246    printf("               \"Games/DeathMatch\" or whatever fits on your system.\n");
1247    printf("-BlockSize n   Radiative block size for faster bounce lighting.\n");
1248    printf("               n must be in range 1..8, default is 3.\n");
1249    printf("-StopUE f      Stop value for unradiated energy. 0 < f <= 10, default is 1.0.\n");
1250    printf("-AskForMore    Asks for a new StopUE value when the old one has been reached.\n");
1251    printf("-UseBS4DL      Normally, direct area lighting uses a 'BlockSize' value of 1.\n");
1252    printf("               Use this to use the same value as for bounce lighting.\n");
1253    printf("-onlyEnts      Process entities only (not the world).\n");
1254    printf("-fast          Same as \"-BlockSize 5 -UseBS4DL\".\n");
1255    printf("\n");
1256    printf("\n");
1257    printf("EXAMPLES:\n");
1258    printf("\n");
1259    printf("CaLight WorldName -AskForMore -gd=Games/DeathMatch\n");
1260    printf("    I'll start with the default parameters, show you the 'Options' dialog box,\n");
1261    printf("    light the world WorldName and finally ask you what to do when the\n");
1262    printf("    StopUE value has been reached.\n");
1263    printf("    \"Games/DeathMatch\" is searched for this worlds game related stuff.\n");
1264    printf("\n");
1265    printf("CaLight WorldName -StopUE 0.1\n");
1266    printf("    Most worlds of the Cafu demo release are lit with these switches.\n");
1267    printf("    \".\" (the default directory for -gd) is searched for game related stuff.\n");
1268    printf("\n");
1269    printf("CaLight WorldName -BlockSize 1 -StopUE 0.1\n");
1270    printf("    This is ideal for batch file processing: WorldName is lit without further\n");
1271    printf("    user questioning and I'll terminate as soon as StopUE has been reached.\n");
1272    printf("    Note that BlockSize and StopUE are set for high-quality lighting here.\n");
1273    printf("\n");
1274    printf("CaLight WorldName -fast\n");
1275    printf("CaLight WorldName -BlockSize 5 -UseBS4DL\n");
1276    printf("    Fast and ugly lighting, intended for quick tests during world development.\n");
1277    exit(1);
1278}
1279
1280
1281static void WriteLogFileEntry(const char* WorldPathName, double StopUE, char BlockSize, unsigned long IterationCount)
1282{
1283    char          DateTime [256]="unknown";
1284    char          HostName [256]="unknown";
1285    char          WorldName[256]="unknown";
1286    time_t        Time          =time(NULL);
1287    unsigned long RunningSec    =(unsigned long)difftime(Time, ProgramStartTime);
1288    FILE*         LogFile       =fopen("CaLight.log", "a");
1289
1290    if (!LogFile) return;
1291
1292    strftime(DateTime, 256, "%d.%m.%Y %H:%M", localtime(&Time));
1293    DateTime[255]=0;
1294
1295#ifdef _WIN32
1296    unsigned long Dummy=256;
1297    if (!GetComputerName(HostName, &Dummy)) sprintf(HostName, "unknown (look-up failed).");
1298#else
1299    // This function also works on Windows, but sadly requires calls to 'WSAStartup()' and 'WSACleanup()'.
1300    if (gethostname(HostName, 256)) sprintf(HostName, "unknown (look-up failed).");
1301#endif
1302    HostName[255]=0;
1303
1304    if (WorldPathName)
1305    {
1306        // Dateinamen abtrennen (mit Extension).
1307        size_t i=strlen(WorldPathName);
1308
1309        while (i>0 && WorldPathName[i-1]!='/' && WorldPathName[i-1]!='\\') i--;
1310        strncpy(WorldName, WorldPathName+i, 256);
1311        WorldName[255]=0;
1312
1313        // Extension abtrennen.
1314        i=strlen(WorldName);
1315
1316        while (i>0 && WorldName[i-1]!='.') i--;
1317        if (i>0) WorldName[i-1]=0;
1318    }
1319
1320    // Date, Time, WorldName, TimeForCompletion on [HostName]
1321    fprintf(LogFile, "%-16s %-16s%3lu:%02lu:%02lu [%-16s]%8.5f %ux%u%8lu\n", DateTime, WorldName, RunningSec/3600, (RunningSec/60) % 60, RunningSec % 60, HostName, StopUE, BlockSize, BlockSize, IterationCount);
1322    fclose(LogFile);
1323}
1324
1325
1326int main(int ArgC, const char* ArgV[])
1327{
1328    struct CaLightOptionsT
1329    {
1330        std::string GameDirName;
1331        char        BlockSize;
1332        double      StopUE;
1333        bool        AskForMore;
1334        bool        UseBlockSizeForDirectL;
1335        bool        EntitiesOnly;
1336
1337        CaLightOptionsT() : GameDirName("."), BlockSize(3), StopUE(1.0), AskForMore(false), UseBlockSizeForDirectL(false), EntitiesOnly(false) {}
1338    } CaLightOptions;
1339
1340
1341    // Init screen
1342    printf("\n*** Cafu Lighting Utility, Version 3 (%s) ***\n\n\n", __DATE__);
1343
1344#ifndef _WIN32
1345    printf("Reminder:\n");
1346    printf("The Linux version of CaLight is equivalent to the Win32 version, except that\n");
1347    printf("the 2nd phase (bounce lighting) cannot manually be terminated\n");
1348    printf("by the user ahead of time.\n\n");
1349#endif
1350
1351    // Run the testcase of the new matrix code.
1352    { DiagMatrixT TestM; if (!TestM.Test()) Error("DiagMatrixT::Test() failed."); }
1353
1354    if (ArgC<2) Usage();
1355
1356    // Initialize the FileMan by mounting the default file system.
1357    // Note that specifying "./" (instead of "") as the file system description effectively prevents the use of
1358    // absolute paths like "D:\abc\someDir\someFile.xy" or "/usr/bin/xy". This however should be fine for this application.
1359    cf::FileSys::FileMan->MountFileSystem(cf::FileSys::FS_TYPE_LOCAL_PATH, "./", "");
1360    cf::FileSys::FileMan->MountFileSystem(cf::FileSys::FS_TYPE_ZIP_ARCHIVE, "Games/DeathMatch/Textures/TechDemo.zip", "Games/DeathMatch/Textures/TechDemo/", "Ca3DE");
1361    cf::FileSys::FileMan->MountFileSystem(cf::FileSys::FS_TYPE_ZIP_ARCHIVE, "Games/DeathMatch/Textures/SkyDomes.zip", "Games/DeathMatch/Textures/SkyDomes/", "Ca3DE");
1362
1363    // Process command line
1364    for (int CurrentArg=2; CurrentArg<ArgC; CurrentArg++)
1365    {
1366        if (_strnicmp(ArgV[CurrentArg], "-gd=", 4)==0)
1367        {
1368            CaLightOptions.GameDirName=ArgV[CurrentArg]+4;
1369        }
1370        else if (!_stricmp(ArgV[CurrentArg], "-BlockSize"))
1371        {
1372            if (CurrentArg+1==ArgC) Error("I can't find a number after \"-BlockSize\"!");
1373            CurrentArg++;
1374            CaLightOptions.BlockSize=atoi(ArgV[CurrentArg]);
1375            if (CaLightOptions.BlockSize<1 || CaLightOptions.BlockSize>8) Error("BlockSize must be in range 1..8.");
1376        }
1377        else if (!_stricmp(ArgV[CurrentArg], "-StopUE"))
1378        {
1379            if (CurrentArg+1==ArgC) Error("I can't find a number after \"-StopUE\"!");
1380            CurrentArg++;
1381            CaLightOptions.StopUE=atof(ArgV[CurrentArg]);
1382            if (CaLightOptions.StopUE<=0.0 || CaLightOptions.StopUE>10.0) Error("StopUE must be in ]0, 10].");
1383        }
1384        else if (!_stricmp(ArgV[CurrentArg], "-AskForMore"))
1385        {
1386            CaLightOptions.AskForMore=true;
1387        }
1388        else if (!_stricmp(ArgV[CurrentArg], "-UseBS4DL"))
1389        {
1390            CaLightOptions.UseBlockSizeForDirectL=true;
1391        }
1392        else if (!_stricmp(ArgV[CurrentArg], "-onlyEnts"))
1393        {
1394            CaLightOptions.EntitiesOnly=true;
1395        }
1396        else if (!_stricmp(ArgV[CurrentArg], "-fast"))
1397        {
1398            CaLightOptions.BlockSize=5;
1399            CaLightOptions.UseBlockSizeForDirectL=true;
1400        }
1401        else if (ArgV[CurrentArg][0]==0)
1402        {
1403            // The argument is "", the empty string.
1404            // This can happen under Linux, when CaLight is called via wxExecute() with white-space trailing the command string.
1405        }
1406        else
1407        {
1408            printf("\nSorry, I don't know what \"%s\" means.\n", ArgV[CurrentArg]);
1409            Usage();
1410        }
1411    }
1412
1413
1414    // Setup the global MaterialManager pointer.
1415    static MaterialManagerImplT MatManImpl;
1416
1417    MaterialManager=&MatManImpl;
1418
1419    if (MaterialManager->RegisterMaterialScriptsInDir(CaLightOptions.GameDirName+"/Materials", CaLightOptions.GameDirName+"/").Size()==0)
1420    {
1421        printf("\nNo materials found in scripts in \"%s/Materials\".\n", CaLightOptions.GameDirName.c_str());
1422        printf("Please use the -gd=... option in order to specify the game directory name,\n");
1423        printf("or run CaLight without any parameters for more help.\n");
1424        Error("No materials found.");
1425    }
1426
1427
1428    try
1429    {
1430        printf("Loading World '%s'.\n", ArgV[1]);
1431        ModelManagerT ModelMan;
1432        CaLightWorldT CaLightWorld(ArgV[1], ModelMan);
1433
1434        unsigned long IterationCount=0;
1435
1436        if (!CaLightOptions.EntitiesOnly)
1437        {
1438            // Print out options summary
1439            const char BlockSize4DirectLighting=CaLightOptions.UseBlockSizeForDirectL ? CaLightOptions.BlockSize : 1;
1440
1441            printf("\n");
1442            printf("- BlockSize is %ux%u.\n", CaLightOptions.BlockSize, CaLightOptions.BlockSize);
1443            printf("- StopUE    is %.3f.\n", CaLightOptions.StopUE);
1444            printf("- I will %s you for more.\n", CaLightOptions.AskForMore ? "ASK" : "NOT ask");
1445            printf("- BlockSize for direct lighting is %ux%u.\n", BlockSize4DirectLighting, BlockSize4DirectLighting);
1446
1447            // Initialize
1448            InitializePatches(CaLightWorld);                // Init2.cpp
1449
1450            // Create a mapping from NodeTs to their patch meshes, with the patch meshes being given as a list of indices into the PatchMeshes array.
1451            for (unsigned long PatchMeshNr=0; PatchMeshNr<PatchMeshes.Size(); PatchMeshNr++)
1452                NodePtrToPMIndices[PatchMeshes[PatchMeshNr].Node].PushBack(PatchMeshNr);
1453
1454            InitializePatchMeshesPVSMatrix(CaLightWorld);   // Init1.cpp
1455
1456            // Perform lighting
1457            DirectLighting(CaLightWorld, BlockSize4DirectLighting);
1458            IterationCount=BounceLighting(CaLightWorld, CaLightOptions.BlockSize, CaLightOptions.StopUE, CaLightOptions.AskForMore, ArgV[1]);
1459
1460            printf("Info: %lu calls to RadiateEnergy() caused %lu potential divergency events.\n", Count_AllCalls, Count_DivgWarnCalls);
1461
1462
1463            ToneReproduction(CaLightWorld);                                     // Ward97.cpp
1464            PostProcessBorders(CaLightWorld);
1465
1466            printf("\n%-50s %s\n", "*** Write Patch values back into LightMaps ***", GetTimeSinceProgramStart());
1467            for (unsigned long PatchMeshNr=0; PatchMeshNr<PatchMeshes.Size(); PatchMeshNr++)
1468            {
1469                cf::PatchMeshT&               PM     =PatchMeshes[PatchMeshNr];
1470                cf::SceneGraph::GenericNodeT* PM_Node=const_cast<cf::SceneGraph::GenericNodeT*>(PM.Node);
1471
1472                // Need a non-const pointer to the "source" NodeT of the patch mesh here.
1473                PM_Node->BackToLightMap(PM);
1474            }
1475        }
1476
1477        // Create (fake) lightmaps for (brush or bezier patch based) entities.
1478        printf("\n%-50s %s\n", "*** Creating entity lightmaps ***", GetTimeSinceProgramStart());
1479        CaLightWorld.CreateLightMapsForEnts();
1480
1481        printf("\n%-50s %s\n", "*** Saving World ***", GetTimeSinceProgramStart());
1482        printf("%s\n", ArgV[1]);
1483        CaLightWorld.SaveToDisk(ArgV[1]);
1484
1485
1486        WriteLogFileEntry(ArgV[1], CaLightOptions.StopUE, CaLightOptions.BlockSize, IterationCount);
1487        printf("\n%-50s %s\n", "COMPLETED.", GetTimeSinceProgramStart());
1488    }
1489    catch (const WorldT::LoadErrorT& E)
1490    {
1491        printf("\nType \"CaLight\" (without any parameters) for help.\n");
1492        Error(E.Msg);
1493    }
1494    catch (const WorldT::SaveErrorT& E)
1495    {
1496        printf("\nType \"CaLight\" (without any parameters) for help.\n");
1497        Error(E.Msg);
1498    }
1499
1500    return 0;
1501}
Note: See TracBrowser for help on using the browser.