]> icculus.org git repositories - icculus/iodoom3.git/blob - neo/renderer/tr_local.h
hello world
[icculus/iodoom3.git] / neo / renderer / tr_local.h
1 /*
2 ===========================================================================
3
4 Doom 3 GPL Source Code
5 Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. 
6
7 This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).  
8
9 Doom 3 Source Code is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 Doom 3 Source Code is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with Doom 3 Source Code.  If not, see <http://www.gnu.org/licenses/>.
21
22 In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code.  If not, please request a copy in writing from id Software at the address below.
23
24 If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
25
26 ===========================================================================
27 */
28
29 #ifndef __TR_LOCAL_H__
30 #define __TR_LOCAL_H__
31
32 #include "Image.h"
33 #include "MegaTexture.h"
34
35 class idRenderWorldLocal;
36
37 // everything that is needed by the backend needs
38 // to be double buffered to allow it to run in
39 // parallel on a dual cpu machine
40 const int SMP_FRAMES = 1;
41
42 const int FALLOFF_TEXTURE_SIZE =        64;
43
44 const float     DEFAULT_FOG_DISTANCE = 500.0f;
45
46 const int FOG_ENTER_SIZE = 64;
47 const float FOG_ENTER = (FOG_ENTER_SIZE+1.0f)/(FOG_ENTER_SIZE*2);
48 // picky to get the bilerp correct at terminator
49
50
51 // idScreenRect gets carried around with each drawSurf, so it makes sense
52 // to keep it compact, instead of just using the idBounds class
53 class idScreenRect {
54 public:
55         short           x1, y1, x2, y2;                                                 // inclusive pixel bounds inside viewport
56     float       zmin, zmax;                                                             // for depth bounds test
57
58         void            Clear();                                                                // clear to backwards values
59         void            AddPoint( float x, float y );                   // adds a point
60         void            Expand();                                                               // expand by one pixel each way to fix roundoffs
61         void            Intersect( const idScreenRect &rect );
62         void            Union( const idScreenRect &rect );
63         bool            Equals( const idScreenRect &rect ) const;
64         bool            IsEmpty() const;
65 };
66
67 idScreenRect R_ScreenRectFromViewFrustumBounds( const idBounds &bounds );
68 void R_ShowColoredScreenRect( const idScreenRect &rect, int colorIndex );
69
70 typedef enum {
71         DC_BAD,
72         DC_RENDERVIEW,
73         DC_UPDATE_ENTITYDEF,
74         DC_DELETE_ENTITYDEF,
75         DC_UPDATE_LIGHTDEF,
76         DC_DELETE_LIGHTDEF,
77         DC_LOADMAP,
78         DC_CROP_RENDER,
79         DC_UNCROP_RENDER,
80         DC_CAPTURE_RENDER,
81         DC_END_FRAME,
82         DC_DEFINE_MODEL,
83         DC_SET_PORTAL_STATE,
84         DC_UPDATE_SOUNDOCCLUSION,
85         DC_GUI_MODEL
86 } demoCommand_t;
87
88 /*
89 ==============================================================================
90
91 SURFACES
92
93 ==============================================================================
94 */
95
96 #include "ModelDecal.h"
97 #include "ModelOverlay.h"
98 #include "Interaction.h"
99
100
101 // drawSurf_t structures command the back end to render surfaces
102 // a given srfTriangles_t may be used with multiple viewEntity_t,
103 // as when viewed in a subview or multiple viewport render, or
104 // with multiple shaders when skinned, or, possibly with multiple
105 // lights, although currently each lighting interaction creates
106 // unique srfTriangles_t
107
108 // drawSurf_t are always allocated and freed every frame, they are never cached
109 static const int        DSF_VIEW_INSIDE_SHADOW  = 1;
110
111 typedef struct drawSurf_s {
112         const srfTriangles_t    *geo;
113         const struct viewEntity_s *space;
114         const idMaterial                *material;      // may be NULL for shadow volumes
115         float                                   sort;           // material->sort, modified by gui / entity sort offsets
116         const float                             *shaderRegisters;       // evaluated and adjusted for referenceShaders
117         const struct drawSurf_s *nextOnLight;   // viewLight chains
118         idScreenRect                    scissorRect;    // for scissor clipping, local inside renderView viewport
119         int                                             dsFlags;                        // DSF_VIEW_INSIDE_SHADOW, etc
120         struct vertCache_s              *dynamicTexCoords;      // float * in vertex cache memory
121         // specular directions for non vertex program cards, skybox texcoords, etc
122 } drawSurf_t;
123
124
125 typedef struct {
126         int             numPlanes;              // this is always 6 for now
127         idPlane planes[6];
128         // positive sides facing inward
129         // plane 5 is always the plane the projection is going to, the
130         // other planes are just clip planes
131         // all planes are in global coordinates
132
133         bool    makeClippedPlanes;
134         // a projected light with a single frustum needs to make sil planes
135         // from triangles that clip against side planes, but a point light
136         // that has adjacent frustums doesn't need to
137 } shadowFrustum_t;
138
139
140 // areas have references to hold all the lights and entities in them
141 typedef struct areaReference_s {
142         struct areaReference_s *areaNext;                               // chain in the area
143         struct areaReference_s *areaPrev;
144         struct areaReference_s *ownerNext;                              // chain on either the entityDef or lightDef
145         idRenderEntityLocal *   entity;                                 // only one of entity / light will be non-NULL
146         idRenderLightLocal *    light;                                  // only one of entity / light will be non-NULL
147         struct portalArea_s     *       area;                                   // so owners can find all the areas they are in
148 } areaReference_t;
149
150
151 // idRenderLight should become the new public interface replacing the qhandle_t to light defs in the idRenderWorld interface
152 class idRenderLight {
153 public:
154         virtual                                 ~idRenderLight() {}
155
156         virtual void                    FreeRenderLight() = 0;
157         virtual void                    UpdateRenderLight( const renderLight_t *re, bool forceUpdate = false ) = 0;
158         virtual void                    GetRenderLight( renderLight_t *re ) = 0;
159         virtual void                    ForceUpdate() = 0;
160         virtual int                             GetIndex() = 0;
161 };
162
163
164 // idRenderEntity should become the new public interface replacing the qhandle_t to entity defs in the idRenderWorld interface
165 class idRenderEntity {
166 public:
167         virtual                                 ~idRenderEntity() {}
168
169         virtual void                    FreeRenderEntity() = 0;
170         virtual void                    UpdateRenderEntity( const renderEntity_t *re, bool forceUpdate = false ) = 0;
171         virtual void                    GetRenderEntity( renderEntity_t *re ) = 0;
172         virtual void                    ForceUpdate() = 0;
173         virtual int                             GetIndex() = 0;
174
175         // overlays are extra polygons that deform with animating models for blood and damage marks
176         virtual void                    ProjectOverlay( const idPlane localTextureAxis[2], const idMaterial *material ) = 0;
177         virtual void                    RemoveDecals() = 0;
178 };
179
180
181 class idRenderLightLocal : public idRenderLight {
182 public:
183                                                         idRenderLightLocal();
184
185         virtual void                    FreeRenderLight();
186         virtual void                    UpdateRenderLight( const renderLight_t *re, bool forceUpdate = false );
187         virtual void                    GetRenderLight( renderLight_t *re );
188         virtual void                    ForceUpdate();
189         virtual int                             GetIndex();
190
191         renderLight_t                   parms;                                  // specification
192
193         bool                                    lightHasMoved;                  // the light has changed its position since it was
194                                                                                                         // first added, so the prelight model is not valid
195
196         float                                   modelMatrix[16];                // this is just a rearrangement of parms.axis and parms.origin
197
198         idRenderWorldLocal *    world;
199         int                                             index;                                  // in world lightdefs
200
201         int                                             areaNum;                                // if not -1, we may be able to cull all the light's
202                                                                                                         // interactions if !viewDef->connectedAreas[areaNum]
203
204         int                                             lastModifiedFrameNum;   // to determine if it is constantly changing,
205                                                                                                         // and should go in the dynamic frame memory, or kept
206                                                                                                         // in the cached memory
207         bool                                    archived;                               // for demo writing
208
209
210         // derived information
211         idPlane                                 lightProject[4];
212
213         const idMaterial *              lightShader;                    // guaranteed to be valid, even if parms.shader isn't
214         idImage *                               falloffImage;
215
216         idVec3                                  globalLightOrigin;              // accounting for lightCenter and parallel
217
218
219         idPlane                                 frustum[6];                             // in global space, positive side facing out, last two are front/back
220         idWinding *                             frustumWindings[6];             // used for culling
221         srfTriangles_t *                frustumTris;                    // triangulated frustumWindings[]
222
223         int                                             numShadowFrustums;              // one for projected lights, usually six for point lights
224         shadowFrustum_t                 shadowFrustums[6];
225
226         int                                             viewCount;                              // if == tr.viewCount, the light is on the viewDef->viewLights list
227         struct viewLight_s *    viewLight;
228
229         areaReference_t *               references;                             // each area the light is present in will have a lightRef
230         idInteraction *                 firstInteraction;               // doubly linked list
231         idInteraction *                 lastInteraction;
232
233         struct doublePortal_s * foggedPortals;
234 };
235
236
237 class idRenderEntityLocal : public idRenderEntity {
238 public:
239                                                         idRenderEntityLocal();
240
241         virtual void                    FreeRenderEntity();
242         virtual void                    UpdateRenderEntity( const renderEntity_t *re, bool forceUpdate = false );
243         virtual void                    GetRenderEntity( renderEntity_t *re );
244         virtual void                    ForceUpdate();
245         virtual int                             GetIndex();
246
247         // overlays are extra polygons that deform with animating models for blood and damage marks
248         virtual void                    ProjectOverlay( const idPlane localTextureAxis[2], const idMaterial *material );
249         virtual void                    RemoveDecals();
250
251         renderEntity_t                  parms;
252
253         float                                   modelMatrix[16];                // this is just a rearrangement of parms.axis and parms.origin
254
255         idRenderWorldLocal *    world;
256         int                                             index;                                  // in world entityDefs
257
258         int                                             lastModifiedFrameNum;   // to determine if it is constantly changing,
259                                                                                                         // and should go in the dynamic frame memory, or kept
260                                                                                                         // in the cached memory
261         bool                                    archived;                               // for demo writing
262
263         idRenderModel *                 dynamicModel;                   // if parms.model->IsDynamicModel(), this is the generated data
264         int                                             dynamicModelFrameCount; // continuously animating dynamic models will recreate
265                                                                                                         // dynamicModel if this doesn't == tr.viewCount
266         idRenderModel *                 cachedDynamicModel;
267
268         idBounds                                referenceBounds;                // the local bounds used to place entityRefs, either from parms or a model
269
270         // a viewEntity_t is created whenever a idRenderEntityLocal is considered for inclusion
271         // in a given view, even if it turns out to not be visible
272         int                                             viewCount;                              // if tr.viewCount == viewCount, viewEntity is valid,
273                                                                                                         // but the entity may still be off screen
274         struct viewEntity_s *   viewEntity;                             // in frame temporary memory
275
276         int                                             visibleCount;
277         // if tr.viewCount == visibleCount, at least one ambient
278         // surface has actually been added by R_AddAmbientDrawsurfs
279         // note that an entity could still be in the view frustum and not be visible due
280         // to portal passing
281
282         idRenderModelDecal *    decals;                                 // chain of decals that have been projected on this model
283         idRenderModelOverlay *  overlay;                                // blood overlays on animated models
284
285         areaReference_t *               entityRefs;                             // chain of all references
286         idInteraction *                 firstInteraction;               // doubly linked list
287         idInteraction *                 lastInteraction;
288
289         bool                                    needsPortalSky;
290 };
291
292
293 // viewLights are allocated on the frame temporary stack memory
294 // a viewLight contains everything that the back end needs out of an idRenderLightLocal,
295 // which the front end may be modifying simultaniously if running in SMP mode.
296 // a viewLight may exist even without any surfaces, and may be relevent for fogging,
297 // but should never exist if its volume does not intersect the view frustum
298 typedef struct viewLight_s {
299         struct viewLight_s *    next;
300
301         // back end should NOT reference the lightDef, because it can change when running SMP
302         idRenderLightLocal *    lightDef;
303
304         // for scissor clipping, local inside renderView viewport
305         // scissorRect.Empty() is true if the viewEntity_t was never actually
306         // seen through any portals
307         idScreenRect                    scissorRect;
308
309         // if the view isn't inside the light, we can use the non-reversed
310         // shadow drawing, avoiding the draws of the front and rear caps
311         bool                                    viewInsideLight;
312
313         // true if globalLightOrigin is inside the view frustum, even if it may
314         // be obscured by geometry.  This allows us to skip shadows from non-visible objects
315         bool                                    viewSeesGlobalLightOrigin;      
316
317         // if !viewInsideLight, the corresponding bit for each of the shadowFrustum
318         // projection planes that the view is on the negative side of will be set,
319         // allowing us to skip drawing the projected caps of shadows if we can't see the face
320         int                                             viewSeesShadowPlaneBits;
321
322         idVec3                                  globalLightOrigin;                      // global light origin used by backend
323         idPlane                                 lightProject[4];                        // light project used by backend
324         idPlane                                 fogPlane;                                       // fog plane for backend fog volume rendering
325         const srfTriangles_t *  frustumTris;                            // light frustum for backend fog volume rendering
326         const idMaterial *              lightShader;                            // light shader used by backend
327         const float     *                       shaderRegisters;                        // shader registers used by backend
328         idImage *                               falloffImage;                           // falloff image used by backend
329
330         const struct drawSurf_s *globalShadows;                         // shadow everything
331         const struct drawSurf_s *localInteractions;                     // don't get local shadows
332         const struct drawSurf_s *localShadows;                          // don't shadow local Surfaces
333         const struct drawSurf_s *globalInteractions;            // get shadows from everything
334         const struct drawSurf_s *translucentInteractions;       // get shadows from everything
335 } viewLight_t;
336
337
338 // a viewEntity is created whenever a idRenderEntityLocal is considered for inclusion
339 // in the current view, but it may still turn out to be culled.
340 // viewEntity are allocated on the frame temporary stack memory
341 // a viewEntity contains everything that the back end needs out of a idRenderEntityLocal,
342 // which the front end may be modifying simultaniously if running in SMP mode.
343 // A single entityDef can generate multiple viewEntity_t in a single frame, as when seen in a mirror
344 typedef struct viewEntity_s {
345         struct viewEntity_s     *next;
346
347         // back end should NOT reference the entityDef, because it can change when running SMP
348         idRenderEntityLocal     *entityDef;
349
350         // for scissor clipping, local inside renderView viewport
351         // scissorRect.Empty() is true if the viewEntity_t was never actually
352         // seen through any portals, but was created for shadow casting.
353         // a viewEntity can have a non-empty scissorRect, meaning that an area
354         // that it is in is visible, and still not be visible.
355         idScreenRect            scissorRect;
356
357         bool                            weaponDepthHack;
358         float                           modelDepthHack;
359
360         float                           modelMatrix[16];                // local coords to global coords
361         float                           modelViewMatrix[16];    // local coords to eye coords
362 } viewEntity_t;
363
364
365 const int       MAX_CLIP_PLANES = 1;                            // we may expand this to six for some subview issues
366
367 // viewDefs are allocated on the frame temporary stack memory
368 typedef struct viewDef_s {
369         // specified in the call to DrawScene()
370         renderView_t            renderView;
371
372         float                           projectionMatrix[16];
373         viewEntity_t            worldSpace;
374
375         idRenderWorldLocal *renderWorld;
376
377         float                           floatTime;
378
379         idVec3                          initialViewAreaOrigin;
380         // Used to find the portalArea that view flooding will take place from.
381         // for a normal view, the initialViewOrigin will be renderView.viewOrg,
382         // but a mirror may put the projection origin outside
383         // of any valid area, or in an unconnected area of the map, so the view
384         // area must be based on a point just off the surface of the mirror / subview.
385         // It may be possible to get a failed portal pass if the plane of the
386         // mirror intersects a portal, and the initialViewAreaOrigin is on
387         // a different side than the renderView.viewOrg is.
388
389         bool                            isSubview;                              // true if this view is not the main view
390         bool                            isMirror;                               // the portal is a mirror, invert the face culling
391         bool                            isXraySubview;
392
393         bool                            isEditor;
394
395         int                                     numClipPlanes;                  // mirrors will often use a single clip plane
396         idPlane                         clipPlanes[MAX_CLIP_PLANES];            // in world space, the positive side
397                                                                                                 // of the plane is the visible side
398         idScreenRect            viewport;                               // in real pixels and proper Y flip
399
400         idScreenRect            scissor;
401         // for scissor clipping, local inside renderView viewport
402         // subviews may only be rendering part of the main view
403         // these are real physical pixel values, possibly scaled and offset from the
404         // renderView x/y/width/height
405
406         struct viewDef_s *      superView;                              // never go into an infinite subview loop 
407         struct drawSurf_s *     subviewSurface;
408
409         // drawSurfs are the visible surfaces of the viewEntities, sorted
410         // by the material sort parameter
411         drawSurf_t **           drawSurfs;                              // we don't use an idList for this, because
412         int                                     numDrawSurfs;                   // it is allocated in frame temporary memory
413         int                                     maxDrawSurfs;                   // may be resized
414
415         struct viewLight_s      *viewLights;                    // chain of all viewLights effecting view
416         struct viewEntity_s     *viewEntitys;                   // chain of all viewEntities effecting view, including off screen ones casting shadows
417         // we use viewEntities as a check to see if a given view consists solely
418         // of 2D rendering, which we can optimize in certain ways.  A 2D view will
419         // not have any viewEntities
420
421         idPlane                         frustum[5];                             // positive sides face outward, [4] is the front clip plane
422         idFrustum                       viewFrustum;
423
424         int                                     areaNum;                                // -1 = not in a valid area
425
426         bool *                          connectedAreas;
427         // An array in frame temporary memory that lists if an area can be reached without
428         // crossing a closed door.  This is used to avoid drawing interactions
429         // when the light is behind a closed door.
430
431 } viewDef_t;
432
433
434 // complex light / surface interactions are broken up into multiple passes of a
435 // simple interaction shader
436 typedef struct {
437         const drawSurf_t *      surf;
438
439         idImage *                       lightImage;
440         idImage *                       lightFalloffImage;
441         idImage *                       bumpImage;
442         idImage *                       diffuseImage;
443         idImage *                       specularImage;
444
445         idVec4                          diffuseColor;   // may have a light color baked into it, will be < tr.backEndRendererMaxLight
446         idVec4                          specularColor;  // may have a light color baked into it, will be < tr.backEndRendererMaxLight
447         stageVertexColor_t      vertexColor;    // applies to both diffuse and specular
448
449         int                                     ambientLight;   // use tr.ambientNormalMap instead of normalization cube map 
450         // (not a bool just to avoid an uninitialized memory check of the pad region by valgrind)
451
452         // these are loaded into the vertex program
453         idVec4                          localLightOrigin;
454         idVec4                          localViewOrigin;
455         idVec4                          lightProjection[4];     // in local coordinates, possibly with a texture matrix baked in
456         idVec4                          bumpMatrix[2];
457         idVec4                          diffuseMatrix[2];
458         idVec4                          specularMatrix[2];
459 } drawInteraction_t;
460
461
462 /*
463 =============================================================
464
465 RENDERER BACK END COMMAND QUEUE
466
467 TR_CMDS
468
469 =============================================================
470 */
471
472 typedef enum {
473         RC_NOP,
474         RC_DRAW_VIEW,
475         RC_SET_BUFFER,
476         RC_COPY_RENDER,
477         RC_SWAP_BUFFERS         // can't just assume swap at end of list because
478                                                 // of forced list submission before syncs
479 } renderCommand_t;
480
481 typedef struct {
482         renderCommand_t         commandId, *next;
483 } emptyCommand_t;
484
485 typedef struct {
486         renderCommand_t         commandId, *next;
487         GLenum  buffer;
488         int             frameCount;
489 } setBufferCommand_t;
490
491 typedef struct {
492         renderCommand_t         commandId, *next;
493         viewDef_t       *viewDef;
494 } drawSurfsCommand_t;
495
496 typedef struct {
497         renderCommand_t         commandId, *next;
498         int             x, y, imageWidth, imageHeight;
499         idImage *image;
500         int             cubeFace;                                       // when copying to a cubeMap
501 } copyRenderCommand_t;
502
503
504 //=======================================================================
505
506 // this is the inital allocation for max number of drawsurfs
507 // in a given view, but it will automatically grow if needed
508 const int       INITIAL_DRAWSURFS =                     0x4000;
509
510 // a request for frame memory will never fail
511 // (until malloc fails), but it may force the
512 // allocation of a new memory block that will
513 // be discontinuous with the existing memory
514 typedef struct frameMemoryBlock_s {
515         struct frameMemoryBlock_s *next;
516         int             size;
517         int             used;
518         int             poop;                   // so that base is 16 byte aligned
519         byte    base[4];        // dynamically allocated as [size]
520 } frameMemoryBlock_t;
521
522 // all of the information needed by the back end must be
523 // contained in a frameData_t.  This entire structure is
524 // duplicated so the front and back end can run in parallel
525 // on an SMP machine (OBSOLETE: this capability has been removed)
526 typedef struct {
527         // one or more blocks of memory for all frame
528         // temporary allocations
529         frameMemoryBlock_t      *memory;
530
531         // alloc will point somewhere into the memory chain
532         frameMemoryBlock_t      *alloc;
533
534         srfTriangles_t *        firstDeferredFreeTriSurf;
535         srfTriangles_t *        lastDeferredFreeTriSurf;
536
537         int                                     memoryHighwater;        // max used on any frame
538
539         // the currently building command list 
540         // commands can be inserted at the front if needed, as for required
541         // dynamically generated textures
542         emptyCommand_t  *cmdHead, *cmdTail;             // may be of other command type based on commandId
543 } frameData_t;
544
545 extern  frameData_t     *frameData;
546
547 //=======================================================================
548
549 void R_LockSurfaceScene( viewDef_t *parms );
550 void R_ClearCommandChain( void );
551 void R_AddDrawViewCmd( viewDef_t *parms );
552
553 void R_ReloadGuis_f( const idCmdArgs &args );
554 void R_ListGuis_f( const idCmdArgs &args );
555
556 void *R_GetCommandBuffer( int bytes );
557
558 // this allows a global override of all materials
559 bool R_GlobalShaderOverride( const idMaterial **shader );
560
561 // this does various checks before calling the idDeclSkin
562 const idMaterial *R_RemapShaderBySkin( const idMaterial *shader, const idDeclSkin *customSkin, const idMaterial *customShader );
563
564
565 //====================================================
566
567
568 /*
569 ** performanceCounters_t
570 */
571 typedef struct {
572         int             c_sphere_cull_in, c_sphere_cull_clip, c_sphere_cull_out;
573         int             c_box_cull_in, c_box_cull_out;
574         int             c_createInteractions;   // number of calls to idInteraction::CreateInteraction
575         int             c_createLightTris;
576         int             c_createShadowVolumes;
577         int             c_generateMd5;
578         int             c_entityDefCallbacks;
579         int             c_alloc, c_free;        // counts for R_StaticAllc/R_StaticFree
580         int             c_visibleViewEntities;
581         int             c_shadowViewEntities;
582         int             c_viewLights;
583         int             c_numViews;                     // number of total views rendered
584         int             c_deformedSurfaces;     // idMD5Mesh::GenerateSurface
585         int             c_deformedVerts;        // idMD5Mesh::GenerateSurface
586         int             c_deformedIndexes;      // idMD5Mesh::GenerateSurface
587         int             c_tangentIndexes;       // R_DeriveTangents()
588         int             c_entityUpdates, c_lightUpdates, c_entityReferences, c_lightReferences;
589         int             c_guiSurfs;
590         int             frontEndMsec;           // sum of time in all RE_RenderScene's in a frame
591 } performanceCounters_t;
592
593
594 typedef struct {
595         int             current2DMap;
596         int             current3DMap;
597         int             currentCubeMap;
598         int             texEnv;
599         textureType_t   textureType;
600 } tmu_t;
601
602 const int MAX_MULTITEXTURE_UNITS =      8;
603 typedef struct {
604         tmu_t           tmu[MAX_MULTITEXTURE_UNITS];
605         int                     currenttmu;
606
607         int                     faceCulling;
608         int                     glStateBits;
609         bool            forceGlState;           // the next GL_State will ignore glStateBits and set everything
610 } glstate_t;
611
612
613 typedef struct {
614         int             c_surfaces;
615         int             c_shaders;
616         int             c_vertexes;
617         int             c_indexes;              // one set per pass
618         int             c_totalIndexes; // counting all passes
619
620         int             c_drawElements;
621         int             c_drawIndexes;
622         int             c_drawVertexes;
623         int             c_drawRefIndexes;
624         int             c_drawRefVertexes;
625
626         int             c_shadowElements;
627         int             c_shadowIndexes;
628         int             c_shadowVertexes;
629
630         int             c_vboIndexes;
631         float   c_overDraw;     
632
633         float   maxLightValue;  // for light scale
634         int             msec;                   // total msec for backend run
635 } backEndCounters_t;
636
637 // all state modified by the back end is separated
638 // from the front end state
639 typedef struct {
640         int                                     frameCount;             // used to track all images used in a frame
641         const viewDef_t *       viewDef;
642         backEndCounters_t       pc;
643
644         const viewEntity_t *currentSpace;               // for detecting when a matrix must change
645         idScreenRect            currentScissor;
646         // for scissor clipping, local inside renderView viewport
647
648         viewLight_t *           vLight;
649         int                                     depthFunc;                      // GLS_DEPTHFUNC_EQUAL, or GLS_DEPTHFUNC_LESS for translucent
650         float                           lightTextureMatrix[16]; // only if lightStage->texture.hasMatrix
651         float                           lightColor[4];          // evaluation of current light's color stage
652
653         float                           lightScale;                     // Every light color calaculation will be multiplied by this,
654                                                                                         // which will guarantee that the result is < tr.backEndRendererMaxLight
655                                                                                         // A card with high dynamic range will have this set to 1.0
656         float                           overBright;                     // The amount that all light interactions must be multiplied by
657                                                                                         // with post processing to get the desired total light level.
658                                                                                         // A high dynamic range card will have this set to 1.0.
659
660         bool                            currentRenderCopied;    // true if any material has already referenced _currentRender
661
662         // our OpenGL state deltas
663         glstate_t                       glState;
664
665         int                                     c_copyFrameBuffer;
666 } backEndState_t;
667
668
669 const int MAX_GUI_SURFACES      = 1024;         // default size of the drawSurfs list for guis, will
670                                                                                 // be automatically expanded as needed
671
672 typedef enum {
673         BE_ARB,
674         BE_NV10,
675         BE_NV20,
676         BE_R200,
677         BE_ARB2,
678         BE_BAD
679 } backEndName_t;
680
681 typedef struct {
682         int             x, y, width, height;    // these are in physical, OpenGL Y-at-bottom pixels
683 } renderCrop_t;
684 static const int        MAX_RENDER_CROPS = 8;
685
686 /*
687 ** Most renderer globals are defined here.
688 ** backend functions should never modify any of these fields,
689 ** but may read fields that aren't dynamically modified
690 ** by the frontend.
691 */
692 class idRenderSystemLocal : public idRenderSystem {
693 public:
694         // external functions
695         virtual void                    Init( void );
696         virtual void                    Shutdown( void );
697         virtual void                    InitOpenGL( void );
698         virtual void                    ShutdownOpenGL( void );
699         virtual bool                    IsOpenGLRunning( void ) const;
700         virtual bool                    IsFullScreen( void ) const;
701         virtual int                             GetScreenWidth( void ) const;
702         virtual int                             GetScreenHeight( void ) const;
703         virtual idRenderWorld * AllocRenderWorld( void );
704         virtual void                    FreeRenderWorld( idRenderWorld *rw );
705         virtual void                    BeginLevelLoad( void );
706         virtual void                    EndLevelLoad( void );
707         virtual bool                    RegisterFont( const char *fontName, fontInfoEx_t &font );
708         virtual void                    SetColor( const idVec4 &rgba );
709         virtual void                    SetColor4( float r, float g, float b, float a );
710         virtual void                    DrawStretchPic ( const idDrawVert *verts, const glIndex_t *indexes, int vertCount, int indexCount, const idMaterial *material,
711                                                                                         bool clip = true, float x = 0.0f, float y = 0.0f, float w = 640.0f, float h = 0.0f );
712         virtual void                    DrawStretchPic ( float x, float y, float w, float h, float s1, float t1, float s2, float t2, const idMaterial *material );
713
714         virtual void                    DrawStretchTri ( idVec2 p1, idVec2 p2, idVec2 p3, idVec2 t1, idVec2 t2, idVec2 t3, const idMaterial *material );
715         virtual void                    GlobalToNormalizedDeviceCoordinates( const idVec3 &global, idVec3 &ndc );
716         virtual void                    GetGLSettings( int& width, int& height );
717         virtual void                    PrintMemInfo( MemInfo_t *mi );
718
719         virtual void                    DrawSmallChar( int x, int y, int ch, const idMaterial *material );
720         virtual void                    DrawSmallStringExt( int x, int y, const char *string, const idVec4 &setColor, bool forceColor, const idMaterial *material );
721         virtual void                    DrawBigChar( int x, int y, int ch, const idMaterial *material );
722         virtual void                    DrawBigStringExt( int x, int y, const char *string, const idVec4 &setColor, bool forceColor, const idMaterial *material );
723         virtual void                    WriteDemoPics();
724         virtual void                    DrawDemoPics();
725         virtual void                    BeginFrame( int windowWidth, int windowHeight );
726         virtual void                    EndFrame( int *frontEndMsec, int *backEndMsec );
727         virtual void                    TakeScreenshot( int width, int height, const char *fileName, int downSample, renderView_t *ref );
728         virtual void                    CropRenderSize( int width, int height, bool makePowerOfTwo = false, bool forceDimensions = false );
729         virtual void                    CaptureRenderToImage( const char *imageName );
730         virtual void                    CaptureRenderToFile( const char *fileName, bool fixAlpha );
731         virtual void                    UnCrop();
732         virtual void                    GetCardCaps( bool &oldCard, bool &nv10or20 );
733         virtual bool                    UploadImage( const char *imageName, const byte *data, int width, int height );
734
735 public:
736         // internal functions
737                                                         idRenderSystemLocal( void );
738                                                         ~idRenderSystemLocal( void );
739
740         void                                    Clear( void );
741         void                                    SetBackEndRenderer();                   // sets tr.backEndRenderer based on cvars
742         void                                    RenderViewToViewport( const renderView_t *renderView, idScreenRect *viewport );
743
744 public:
745         // renderer globals
746         bool                                    registered;             // cleared at shutdown, set at InitOpenGL
747
748         bool                                    takingScreenshot;
749
750         int                                             frameCount;             // incremented every frame
751         int                                             viewCount;              // incremented every view (twice a scene if subviewed)
752                                                                                         // and every R_MarkFragments call
753
754         int                                             staticAllocCount;       // running total of bytes allocated
755
756         float                                   frameShaderTime;        // shader time for all non-world 2D rendering
757
758         int                                             viewportOffset[2];      // for doing larger-than-window tiled renderings
759         int                                             tiledViewport[2];
760
761         // determines which back end to use, and if vertex programs are in use
762         backEndName_t                   backEndRenderer;
763         bool                                    backEndRendererHasVertexPrograms;
764         float                                   backEndRendererMaxLight;        // 1.0 for standard, unlimited for floats
765                                                                                                                 // determines how much overbrighting needs
766                                                                                                                 // to be done post-process
767
768         idVec4                                  ambientLightVector;     // used for "ambient bump mapping"
769
770         float                                   sortOffset;                             // for determinist sorting of equal sort materials
771
772         idList<idRenderWorldLocal*>worlds;
773
774         idRenderWorldLocal *    primaryWorld;
775         renderView_t                    primaryRenderView;
776         viewDef_t *                             primaryView;
777         // many console commands need to know which world they should operate on
778
779         const idMaterial *              defaultMaterial;
780         idImage *                               testImage;
781         idCinematic *                   testVideo;
782         float                                   testVideoStartTime;
783
784         idImage *                               ambientCubeImage;       // hack for testing dependent ambient lighting
785
786         viewDef_t *                             viewDef;
787
788         performanceCounters_t   pc;                                     // performance counters
789
790         drawSurfsCommand_t              lockSurfacesCmd;        // use this when r_lockSurfaces = 1
791
792         viewEntity_t                    identitySpace;          // can use if we don't know viewDef->worldSpace is valid
793         FILE *                                  logFile;                        // for logging GL calls and frame breaks
794
795         int                                             stencilIncr, stencilDecr;       // GL_INCR / INCR_WRAP_EXT, GL_DECR / GL_DECR_EXT
796
797         renderCrop_t                    renderCrops[MAX_RENDER_CROPS];
798         int                                             currentRenderCrop;
799
800         // GUI drawing variables for surface creation
801         int                                             guiRecursionLevel;              // to prevent infinite overruns
802         class idGuiModel *              guiModel;
803         class idGuiModel *              demoGuiModel;
804
805         unsigned short                  gammaTable[256];        // brightness / gamma modify this
806 };
807
808 extern backEndState_t           backEnd;
809 extern idRenderSystemLocal      tr;
810 extern glconfig_t                       glConfig;               // outside of TR since it shouldn't be cleared during ref re-init
811
812
813 //
814 // cvars
815 //
816 extern idCVar r_ext_vertex_array_range;
817
818 extern idCVar r_glDriver;                               // "opengl32", etc
819 extern idCVar r_mode;                                   // video mode number
820 extern idCVar r_displayRefresh;                 // optional display refresh rate option for vid mode
821 extern idCVar r_fullscreen;                             // 0 = windowed, 1 = full screen
822 extern idCVar r_multiSamples;                   // number of antialiasing samples
823
824 extern idCVar r_ignore;                                 // used for random debugging without defining new vars
825 extern idCVar r_ignore2;                                // used for random debugging without defining new vars
826 extern idCVar r_znear;                                  // near Z clip plane
827
828 extern idCVar r_finish;                                 // force a call to glFinish() every frame
829 extern idCVar r_frontBuffer;                    // draw to front buffer for debugging
830 extern idCVar r_swapInterval;                   // changes wglSwapIntarval
831 extern idCVar r_offsetFactor;                   // polygon offset parameter
832 extern idCVar r_offsetUnits;                    // polygon offset parameter
833 extern idCVar r_singleTriangle;                 // only draw a single triangle per primitive
834 extern idCVar r_logFile;                                // number of frames to emit GL logs
835 extern idCVar r_clear;                                  // force screen clear every frame
836 extern idCVar r_shadows;                                // enable shadows
837 extern idCVar r_subviewOnly;                    // 1 = don't render main view, allowing subviews to be debugged
838 extern idCVar r_lightScale;                             // all light intensities are multiplied by this, which is normally 2
839 extern idCVar r_flareSize;                              // scale the flare deforms from the material def
840
841 extern idCVar r_gamma;                                  // changes gamma tables
842 extern idCVar r_brightness;                             // changes gamma tables
843
844 extern idCVar r_renderer;                               // arb, nv10, nv20, r200, gl2, etc
845
846 extern idCVar r_cgVertexProfile;                // arbvp1, vp20, vp30
847 extern idCVar r_cgFragmentProfile;              // arbfp1, fp30
848
849 extern idCVar r_checkBounds;                    // compare all surface bounds with precalculated ones
850
851 extern idCVar r_useNV20MonoLights;              // 1 = allow an interaction pass optimization
852 extern idCVar r_useLightPortalFlow;             // 1 = do a more precise area reference determination
853 extern idCVar r_useTripleTextureARB;    // 1 = cards with 3+ texture units do a two pass instead of three pass
854 extern idCVar r_useShadowSurfaceScissor;// 1 = scissor shadows by the scissor rect of the interaction surfaces
855 extern idCVar r_useConstantMaterials;   // 1 = use pre-calculated material registers if possible
856 extern idCVar r_useInteractionTable;    // create a full entityDefs * lightDefs table to make finding interactions faster
857 extern idCVar r_useNodeCommonChildren;  // stop pushing reference bounds early when possible
858 extern idCVar r_useSilRemap;                    // 1 = consider verts with the same XYZ, but different ST the same for shadows
859 extern idCVar r_useCulling;                             // 0 = none, 1 = sphere, 2 = sphere + box
860 extern idCVar r_useLightCulling;                // 0 = none, 1 = box, 2 = exact clip of polyhedron faces
861 extern idCVar r_useLightScissors;               // 1 = use custom scissor rectangle for each light
862 extern idCVar r_useClippedLightScissors;// 0 = full screen when near clipped, 1 = exact when near clipped, 2 = exact always
863 extern idCVar r_useEntityCulling;               // 0 = none, 1 = box
864 extern idCVar r_useEntityScissors;              // 1 = use custom scissor rectangle for each entity
865 extern idCVar r_useInteractionCulling;  // 1 = cull interactions
866 extern idCVar r_useInteractionScissors; // 1 = use a custom scissor rectangle for each interaction
867 extern idCVar r_useFrustumFarDistance;  // if != 0 force the view frustum far distance to this distance
868 extern idCVar r_useShadowCulling;               // try to cull shadows from partially visible lights
869 extern idCVar r_usePreciseTriangleInteractions; // 1 = do winding clipping to determine if each ambiguous tri should be lit
870 extern idCVar r_useTurboShadow;                 // 1 = use the infinite projection with W technique for dynamic shadows
871 extern idCVar r_useExternalShadows;             // 1 = skip drawing caps when outside the light volume
872 extern idCVar r_useOptimizedShadows;    // 1 = use the dmap generated static shadow volumes
873 extern idCVar r_useShadowVertexProgram; // 1 = do the shadow projection in the vertex program on capable cards
874 extern idCVar r_useShadowProjectedCull; // 1 = discard triangles outside light volume before shadowing
875 extern idCVar r_useDeferredTangents;    // 1 = don't always calc tangents after deform
876 extern idCVar r_useCachedDynamicModels; // 1 = cache snapshots of dynamic models
877 extern idCVar r_useTwoSidedStencil;             // 1 = do stencil shadows in one pass with different ops on each side
878 extern idCVar r_useInfiniteFarZ;                // 1 = use the no-far-clip-plane trick
879 extern idCVar r_useScissor;                             // 1 = scissor clip as portals and lights are processed
880 extern idCVar r_usePortals;                             // 1 = use portals to perform area culling, otherwise draw everything
881 extern idCVar r_useStateCaching;                // avoid redundant state changes in GL_*() calls
882 extern idCVar r_useCombinerDisplayLists;// if 1, put all nvidia register combiner programming in display lists
883 extern idCVar r_useVertexBuffers;               // if 0, don't use ARB_vertex_buffer_object for vertexes
884 extern idCVar r_useIndexBuffers;                // if 0, don't use ARB_vertex_buffer_object for indexes
885 extern idCVar r_useEntityCallbacks;             // if 0, issue the callback immediately at update time, rather than defering
886 extern idCVar r_lightAllBackFaces;              // light all the back faces, even when they would be shadowed
887 extern idCVar r_useDepthBoundsTest;     // use depth bounds test to reduce shadow fill
888
889 extern idCVar r_skipPostProcess;                // skip all post-process renderings
890 extern idCVar r_skipSuppress;                   // ignore the per-view suppressions
891 extern idCVar r_skipInteractions;               // skip all light/surface interaction drawing
892 extern idCVar r_skipFrontEnd;                   // bypasses all front end work, but 2D gui rendering still draws
893 extern idCVar r_skipBackEnd;                    // don't draw anything
894 extern idCVar r_skipCopyTexture;                // do all rendering, but don't actually copyTexSubImage2D
895 extern idCVar r_skipRender;                             // skip 3D rendering, but pass 2D
896 extern idCVar r_skipRenderContext;              // NULL the rendering context during backend 3D rendering
897 extern idCVar r_skipTranslucent;                // skip the translucent interaction rendering
898 extern idCVar r_skipAmbient;                    // bypasses all non-interaction drawing
899 extern idCVar r_skipNewAmbient;                 // bypasses all vertex/fragment program ambients
900 extern idCVar r_skipBlendLights;                // skip all blend lights
901 extern idCVar r_skipFogLights;                  // skip all fog lights
902 extern idCVar r_skipSubviews;                   // 1 = don't render any mirrors / cameras / etc
903 extern idCVar r_skipGuiShaders;                 // 1 = don't render any gui elements on surfaces
904 extern idCVar r_skipParticles;                  // 1 = don't render any particles
905 extern idCVar r_skipUpdates;                    // 1 = don't accept any entity or light updates, making everything static
906 extern idCVar r_skipDeforms;                    // leave all deform materials in their original state
907 extern idCVar r_skipDynamicTextures;    // don't dynamically create textures
908 extern idCVar r_skipLightScale;                 // don't do any post-interaction light scaling, makes things dim on low-dynamic range cards
909 extern idCVar r_skipBump;                               // uses a flat surface instead of the bump map
910 extern idCVar r_skipSpecular;                   // use black for specular
911 extern idCVar r_skipDiffuse;                    // use black for diffuse
912 extern idCVar r_skipOverlays;                   // skip overlay surfaces
913 extern idCVar r_skipROQ;
914
915 extern idCVar r_ignoreGLErrors;
916
917 extern idCVar r_forceLoadImages;                // draw all images to screen after registration
918 extern idCVar r_demonstrateBug;                 // used during development to show IHV's their problems
919 extern idCVar r_screenFraction;                 // for testing fill rate, the resolution of the entire screen can be changed
920
921 extern idCVar r_showUnsmoothedTangents; // highlight geometry rendered with unsmoothed tangents
922 extern idCVar r_showSilhouette;                 // highlight edges that are casting shadow planes
923 extern idCVar r_showVertexColor;                // draws all triangles with the solid vertex color
924 extern idCVar r_showUpdates;                    // report entity and light updates and ref counts
925 extern idCVar r_showDemo;                               // report reads and writes to the demo file
926 extern idCVar r_showDynamic;                    // report stats on dynamic surface generation
927 extern idCVar r_showLightScale;                 // report the scale factor applied to drawing for overbrights
928 extern idCVar r_showIntensity;                  // draw the screen colors based on intensity, red = 0, green = 128, blue = 255
929 extern idCVar r_showDefs;                               // report the number of modeDefs and lightDefs in view
930 extern idCVar r_showTrace;                              // show the intersection of an eye trace with the world
931 extern idCVar r_showSmp;                                // show which end (front or back) is blocking
932 extern idCVar r_showDepth;                              // display the contents of the depth buffer and the depth range
933 extern idCVar r_showImages;                             // draw all images to screen instead of rendering
934 extern idCVar r_showTris;                               // enables wireframe rendering of the world
935 extern idCVar r_showSurfaceInfo;                // show surface material name under crosshair
936 extern idCVar r_showNormals;                    // draws wireframe normals
937 extern idCVar r_showEdges;                              // draw the sil edges
938 extern idCVar r_showViewEntitys;                // displays the bounding boxes of all view models and optionally the index
939 extern idCVar r_showTexturePolarity;    // shade triangles by texture area polarity
940 extern idCVar r_showTangentSpace;               // shade triangles by tangent space
941 extern idCVar r_showDominantTri;                // draw lines from vertexes to center of dominant triangles
942 extern idCVar r_showTextureVectors;             // draw each triangles texture (tangent) vectors
943 extern idCVar r_showLights;                             // 1 = print light info, 2 = also draw volumes
944 extern idCVar r_showLightCount;                 // colors surfaces based on light count
945 extern idCVar r_showShadows;                    // visualize the stencil shadow volumes
946 extern idCVar r_showShadowCount;                // colors screen based on shadow volume depth complexity
947 extern idCVar r_showLightScissors;              // show light scissor rectangles
948 extern idCVar r_showEntityScissors;             // show entity scissor rectangles
949 extern idCVar r_showInteractionFrustums;// show a frustum for each interaction
950 extern idCVar r_showInteractionScissors;// show screen rectangle which contains the interaction frustum
951 extern idCVar r_showMemory;                             // print frame memory utilization
952 extern idCVar r_showCull;                               // report sphere and box culling stats
953 extern idCVar r_showInteractions;               // report interaction generation activity
954 extern idCVar r_showSurfaces;                   // report surface/light/shadow counts
955 extern idCVar r_showPrimitives;                 // report vertex/index/draw counts
956 extern idCVar r_showPortals;                    // draw portal outlines in color based on passed / not passed
957 extern idCVar r_showAlloc;                              // report alloc/free counts
958 extern idCVar r_showSkel;                               // draw the skeleton when model animates
959 extern idCVar r_showOverDraw;                   // show overdraw
960 extern idCVar r_jointNameScale;                 // size of joint names when r_showskel is set to 1
961 extern idCVar r_jointNameOffset;                // offset of joint names when r_showskel is set to 1
962
963 extern idCVar r_testGamma;                              // draw a grid pattern to test gamma levels
964 extern idCVar r_testStepGamma;                  // draw a grid pattern to test gamma levels
965 extern idCVar r_testGammaBias;                  // draw a grid pattern to test gamma levels
966
967 extern idCVar r_testARBProgram;                 // experiment with vertex/fragment programs
968
969 extern idCVar r_singleLight;                    // suppress all but one light
970 extern idCVar r_singleEntity;                   // suppress all but one entity
971 extern idCVar r_singleArea;                             // only draw the portal area the view is actually in
972 extern idCVar r_singleSurface;                  // suppress all but one surface on each entity
973 extern idCVar r_shadowPolygonOffset;    // bias value added to depth test for stencil shadow drawing
974 extern idCVar r_shadowPolygonFactor;    // scale value for stencil shadow drawing
975
976 extern idCVar r_jitter;                                 // randomly subpixel jitter the projection matrix
977 extern idCVar r_lightSourceRadius;              // for soft-shadow sampling
978 extern idCVar r_lockSurfaces;
979 extern idCVar r_orderIndexes;                   // perform index reorganization to optimize vertex use
980
981 extern idCVar r_debugLineDepthTest;             // perform depth test on debug lines
982 extern idCVar r_debugLineWidth;                 // width of debug lines
983 extern idCVar r_debugArrowStep;                 // step size of arrow cone line rotation in degrees
984 extern idCVar r_debugPolygonFilled;
985
986 extern idCVar r_materialOverride;               // override all materials
987
988 extern idCVar r_debugRenderToTexture;
989
990 /*
991 ====================================================================
992
993 GL wrapper/helper functions
994
995 ====================================================================
996 */
997
998 void    GL_SelectTexture( int unit );
999 void    GL_CheckErrors( void );
1000 void    GL_ClearStateDelta( void );
1001 void    GL_State( int stateVector );
1002 void    GL_TexEnv( int env );
1003 void    GL_Cull( int cullType );
1004
1005 const int GLS_SRCBLEND_ZERO                                             = 0x00000001;
1006 const int GLS_SRCBLEND_ONE                                              = 0x0;
1007 const int GLS_SRCBLEND_DST_COLOR                                = 0x00000003;
1008 const int GLS_SRCBLEND_ONE_MINUS_DST_COLOR              = 0x00000004;
1009 const int GLS_SRCBLEND_SRC_ALPHA                                = 0x00000005;
1010 const int GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA              = 0x00000006;
1011 const int GLS_SRCBLEND_DST_ALPHA                                = 0x00000007;
1012 const int GLS_SRCBLEND_ONE_MINUS_DST_ALPHA              = 0x00000008;
1013 const int GLS_SRCBLEND_ALPHA_SATURATE                   = 0x00000009;
1014 const int GLS_SRCBLEND_BITS                                             = 0x0000000f;
1015
1016 const int GLS_DSTBLEND_ZERO                                             = 0x0;
1017 const int GLS_DSTBLEND_ONE                                              = 0x00000020;
1018 const int GLS_DSTBLEND_SRC_COLOR                                = 0x00000030;
1019 const int GLS_DSTBLEND_ONE_MINUS_SRC_COLOR              = 0x00000040;
1020 const int GLS_DSTBLEND_SRC_ALPHA                                = 0x00000050;
1021 const int GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA              = 0x00000060;
1022 const int GLS_DSTBLEND_DST_ALPHA                                = 0x00000070;
1023 const int GLS_DSTBLEND_ONE_MINUS_DST_ALPHA              = 0x00000080;
1024 const int GLS_DSTBLEND_BITS                                             = 0x000000f0;
1025
1026
1027 // these masks are the inverse, meaning when set the glColorMask value will be 0,
1028 // preventing that channel from being written
1029 const int GLS_DEPTHMASK                                                 = 0x00000100;
1030 const int GLS_REDMASK                                                   = 0x00000200;
1031 const int GLS_GREENMASK                                                 = 0x00000400;
1032 const int GLS_BLUEMASK                                                  = 0x00000800;
1033 const int GLS_ALPHAMASK                                                 = 0x00001000;
1034 const int GLS_COLORMASK                                                 = (GLS_REDMASK|GLS_GREENMASK|GLS_BLUEMASK);
1035
1036 const int GLS_POLYMODE_LINE                                             = 0x00002000;
1037
1038 const int GLS_DEPTHFUNC_ALWAYS                                  = 0x00010000;
1039 const int GLS_DEPTHFUNC_EQUAL                                   = 0x00020000;
1040 const int GLS_DEPTHFUNC_LESS                                    = 0x0;
1041
1042 const int GLS_ATEST_EQ_255                                              = 0x10000000;
1043 const int GLS_ATEST_LT_128                                              = 0x20000000;
1044 const int GLS_ATEST_GE_128                                              = 0x40000000;
1045 const int GLS_ATEST_BITS                                                = 0x70000000;
1046
1047 const int GLS_DEFAULT                                                   = GLS_DEPTHFUNC_ALWAYS;
1048
1049 void R_Init( void );
1050 void R_InitOpenGL( void );
1051
1052 void R_DoneFreeType( void );
1053
1054 void R_SetColorMappings( void );
1055
1056 void R_ScreenShot_f( const idCmdArgs &args );
1057 void R_StencilShot( void );
1058
1059 bool R_CheckExtension( char *name );
1060
1061
1062 /*
1063 ====================================================================
1064
1065 IMPLEMENTATION SPECIFIC FUNCTIONS
1066
1067 ====================================================================
1068 */
1069
1070 typedef struct {
1071         int                     width;
1072         int                     height;
1073         bool            fullScreen;
1074         bool            stereo;
1075         int                     displayHz;
1076         int                     multiSamples;
1077 } glimpParms_t;
1078
1079 bool            GLimp_Init( glimpParms_t parms );
1080 // If the desired mode can't be set satisfactorily, false will be returned.
1081 // The renderer will then reset the glimpParms to "safe mode" of 640x480
1082 // fullscreen and try again.  If that also fails, the error will be fatal.
1083
1084 bool            GLimp_SetScreenParms( glimpParms_t parms );
1085 // will set up gl up with the new parms
1086
1087 void            GLimp_Shutdown( void );
1088 // Destroys the rendering context, closes the window, resets the resolution,
1089 // and resets the gamma ramps.
1090
1091 void            GLimp_SwapBuffers( void );
1092 // Calls the system specific swapbuffers routine, and may also perform
1093 // other system specific cvar checks that happen every frame.
1094 // This will not be called if 'r_drawBuffer GL_FRONT'
1095
1096 void            GLimp_SetGamma( unsigned short red[256], 
1097                                                     unsigned short green[256],
1098                                                         unsigned short blue[256] );
1099 // Sets the hardware gamma ramps for gamma and brightness adjustment.
1100 // These are now taken as 16 bit values, so we can take full advantage
1101 // of dacs with >8 bits of precision
1102
1103
1104 bool            GLimp_SpawnRenderThread( void (*function)( void ) );
1105 // Returns false if the system only has a single processor
1106
1107 void *          GLimp_BackEndSleep( void );
1108 void            GLimp_FrontEndSleep( void );
1109 void            GLimp_WakeBackEnd( void *data );
1110 // these functions implement the dual processor syncronization
1111
1112 void            GLimp_ActivateContext( void );
1113 void            GLimp_DeactivateContext( void );
1114 // These are used for managing SMP handoffs of the OpenGL context
1115 // between threads, and as a performance tunining aid.  Setting
1116 // 'r_skipRenderContext 1' will call GLimp_DeactivateContext() before
1117 // the 3D rendering code, and GLimp_ActivateContext() afterwards.  On
1118 // most OpenGL implementations, this will result in all OpenGL calls
1119 // being immediate returns, which lets us guage how much time is
1120 // being spent inside OpenGL.
1121
1122 void            GLimp_EnableLogging( bool enable );
1123
1124
1125 /*
1126 ====================================================================
1127
1128 MAIN
1129
1130 ====================================================================
1131 */
1132
1133 void R_RenderView( viewDef_t *parms );
1134
1135 // performs radius cull first, then corner cull
1136 bool R_CullLocalBox( const idBounds &bounds, const float modelMatrix[16], int numPlanes, const idPlane *planes );
1137 bool R_RadiusCullLocalBox( const idBounds &bounds, const float modelMatrix[16], int numPlanes, const idPlane *planes );
1138 bool R_CornerCullLocalBox( const idBounds &bounds, const float modelMatrix[16], int numPlanes, const idPlane *planes );
1139
1140 void R_AxisToModelMatrix( const idMat3 &axis, const idVec3 &origin, float modelMatrix[16] );
1141
1142 // note that many of these assume a normalized matrix, and will not work with scaled axis
1143 void R_GlobalPointToLocal( const float modelMatrix[16], const idVec3 &in, idVec3 &out );
1144 void R_GlobalVectorToLocal( const float modelMatrix[16], const idVec3 &in, idVec3 &out );
1145 void R_GlobalPlaneToLocal( const float modelMatrix[16], const idPlane &in, idPlane &out );
1146 void R_PointTimesMatrix( const float modelMatrix[16], const idVec4 &in, idVec4 &out );
1147 void R_LocalPointToGlobal( const float modelMatrix[16], const idVec3 &in, idVec3 &out );
1148 void R_LocalVectorToGlobal( const float modelMatrix[16], const idVec3 &in, idVec3 &out );
1149 void R_LocalPlaneToGlobal( const float modelMatrix[16], const idPlane &in, idPlane &out );
1150 void R_TransformEyeZToWin( float src_z, const float *projectionMatrix, float &dst_z );
1151
1152 void R_GlobalToNormalizedDeviceCoordinates( const idVec3 &global, idVec3 &ndc );
1153
1154 void R_TransformModelToClip( const idVec3 &src, const float *modelMatrix, const float *projectionMatrix, idPlane &eye, idPlane &dst );
1155
1156 void R_TransformClipToDevice( const idPlane &clip, const viewDef_t *view, idVec3 &normalized );
1157
1158 void R_TransposeGLMatrix( const float in[16], float out[16] );
1159
1160 void R_SetViewMatrix( viewDef_t *viewDef );
1161
1162 void myGlMultMatrix( const float *a, const float *b, float *out );
1163
1164 /*
1165 ============================================================
1166
1167 LIGHT
1168
1169 ============================================================
1170 */
1171
1172 void R_ListRenderLightDefs_f( const idCmdArgs &args );
1173 void R_ListRenderEntityDefs_f( const idCmdArgs &args );
1174
1175 bool R_IssueEntityDefCallback( idRenderEntityLocal *def );
1176 idRenderModel *R_EntityDefDynamicModel( idRenderEntityLocal *def );
1177
1178 viewEntity_t *R_SetEntityDefViewEntity( idRenderEntityLocal *def );
1179 viewLight_t *R_SetLightDefViewLight( idRenderLightLocal *def );
1180
1181 void R_AddDrawSurf( const srfTriangles_t *tri, const viewEntity_t *space, const renderEntity_t *renderEntity,
1182                                         const idMaterial *shader, const idScreenRect &scissor );
1183
1184 void R_LinkLightSurf( const drawSurf_t **link, const srfTriangles_t *tri, const viewEntity_t *space, 
1185                                    const idRenderLightLocal *light, const idMaterial *shader, const idScreenRect &scissor, bool viewInsideShadow );
1186
1187 bool R_CreateAmbientCache( srfTriangles_t *tri, bool needsLighting );
1188 bool R_CreateLightingCache( const idRenderEntityLocal *ent, const idRenderLightLocal *light, srfTriangles_t *tri );
1189 void R_CreatePrivateShadowCache( srfTriangles_t *tri );
1190 void R_CreateVertexProgramShadowCache( srfTriangles_t *tri );
1191
1192 /*
1193 ============================================================
1194
1195 LIGHTRUN
1196
1197 ============================================================
1198 */
1199
1200 void R_RegenerateWorld_f( const idCmdArgs &args );
1201
1202 void R_ModulateLights_f( const idCmdArgs &args );
1203
1204 void R_SetLightProject( idPlane lightProject[4], const idVec3 origin, const idVec3 targetPoint,
1205            const idVec3 rightVector, const idVec3 upVector, const idVec3 start, const idVec3 stop );
1206
1207 void R_AddLightSurfaces( void );
1208 void R_AddModelSurfaces( void );
1209 void R_RemoveUnecessaryViewLights( void );
1210
1211 void R_FreeDerivedData( void );
1212 void R_ReCreateWorldReferences( void );
1213
1214 void R_CreateEntityRefs( idRenderEntityLocal *def );
1215 void R_CreateLightRefs( idRenderLightLocal *light );
1216
1217 void R_DeriveLightData( idRenderLightLocal *light );
1218 void R_FreeLightDefDerivedData( idRenderLightLocal *light );
1219 void R_CheckForEntityDefsUsingModel( idRenderModel *model );
1220
1221 void R_ClearEntityDefDynamicModel( idRenderEntityLocal *def );
1222 void R_FreeEntityDefDerivedData( idRenderEntityLocal *def, bool keepDecals, bool keepCachedDynamicModel );
1223 void R_FreeEntityDefCachedDynamicModel( idRenderEntityLocal *def );
1224 void R_FreeEntityDefDecals( idRenderEntityLocal *def );
1225 void R_FreeEntityDefOverlay( idRenderEntityLocal *def );
1226 void R_FreeEntityDefFadedDecals( idRenderEntityLocal *def, int time );
1227
1228 void R_CreateLightDefFogPortals( idRenderLightLocal *ldef );
1229
1230 /*
1231 ============================================================
1232
1233 POLYTOPE
1234
1235 ============================================================
1236 */
1237
1238 srfTriangles_t *R_PolytopeSurface( int numPlanes, const idPlane *planes, idWinding **windings );
1239
1240 /*
1241 ============================================================
1242
1243 RENDER
1244
1245 ============================================================
1246 */
1247
1248 void RB_EnterWeaponDepthHack();
1249 void RB_EnterModelDepthHack( float depth );
1250 void RB_LeaveDepthHack();
1251 void RB_DrawElementsImmediate( const srfTriangles_t *tri );
1252 void RB_RenderTriangleSurface( const srfTriangles_t *tri );
1253 void RB_T_RenderTriangleSurface( const drawSurf_t *surf );
1254 void RB_RenderDrawSurfListWithFunction( drawSurf_t **drawSurfs, int numDrawSurfs, 
1255                                           void (*triFunc_)( const drawSurf_t *) );
1256 void RB_RenderDrawSurfChainWithFunction( const drawSurf_t *drawSurfs, 
1257                                                                                 void (*triFunc_)( const drawSurf_t *) );
1258 void RB_DrawShaderPasses( drawSurf_t **drawSurfs, int numDrawSurfs );
1259 void RB_LoadShaderTextureMatrix( const float *shaderRegisters, const textureStage_t *texture );
1260 void RB_GetShaderTextureMatrix( const float *shaderRegisters, const textureStage_t *texture, float matrix[16] );
1261 void RB_CreateSingleDrawInteractions( const drawSurf_t *surf, void (*DrawInteraction)(const drawInteraction_t *) );
1262
1263 const shaderStage_t *RB_SetLightTexture( const idRenderLightLocal *light );
1264
1265 void RB_DrawView( const void *data );
1266
1267 void RB_DetermineLightScale( void );
1268 void RB_STD_LightScale( void );
1269 void RB_BeginDrawingView (void);
1270
1271 /*
1272 ============================================================
1273
1274 DRAW_STANDARD
1275
1276 ============================================================
1277 */
1278
1279 void RB_DrawElementsWithCounters( const srfTriangles_t *tri );
1280 void RB_DrawShadowElementsWithCounters( const srfTriangles_t *tri, int numIndexes );
1281 void RB_STD_FillDepthBuffer( drawSurf_t **drawSurfs, int numDrawSurfs );
1282 void RB_BindVariableStageImage( const textureStage_t *texture, const float *shaderRegisters );
1283 void RB_BindStageTexture( const float *shaderRegisters, const textureStage_t *texture, const drawSurf_t *surf );
1284 void RB_FinishStageTexture( const textureStage_t *texture, const drawSurf_t *surf );
1285 void RB_StencilShadowPass( const drawSurf_t *drawSurfs );
1286 void RB_STD_DrawView( void );
1287 void RB_STD_FogAllLights( void );
1288 void RB_BakeTextureMatrixIntoTexgen( idPlane lightProject[3], const float textureMatrix[16] );
1289
1290 /*
1291 ============================================================
1292
1293 DRAW_*
1294
1295 ============================================================
1296 */
1297
1298 void    RB_ARB_DrawInteractions( void );
1299
1300 void    R_R200_Init( void );
1301 void    RB_R200_DrawInteractions( void );
1302
1303 void    R_NV10_Init( void );
1304 void    RB_NV10_DrawInteractions( void );
1305
1306 void    R_NV20_Init( void );
1307 void    RB_NV20_DrawInteractions( void );
1308
1309 void    R_ARB2_Init( void );
1310 void    RB_ARB2_DrawInteractions( void );
1311 void    R_ReloadARBPrograms_f( const idCmdArgs &args );
1312 int             R_FindARBProgram( GLenum target, const char *program );
1313
1314 typedef enum {
1315         PROG_INVALID,
1316         VPROG_INTERACTION,
1317         VPROG_ENVIRONMENT,
1318         VPROG_BUMPY_ENVIRONMENT,
1319         VPROG_R200_INTERACTION,
1320         VPROG_STENCIL_SHADOW,
1321         VPROG_NV20_BUMP_AND_LIGHT,
1322         VPROG_NV20_DIFFUSE_COLOR,
1323         VPROG_NV20_SPECULAR_COLOR,
1324         VPROG_NV20_DIFFUSE_AND_SPECULAR_COLOR,
1325         VPROG_TEST,
1326         FPROG_INTERACTION,
1327         FPROG_ENVIRONMENT,
1328         FPROG_BUMPY_ENVIRONMENT,
1329         FPROG_TEST,
1330         VPROG_AMBIENT,
1331         FPROG_AMBIENT,
1332         VPROG_GLASSWARP,
1333         FPROG_GLASSWARP,
1334         PROG_USER
1335 } program_t;
1336
1337 /*
1338
1339   All vertex programs use the same constant register layout:
1340
1341 c[4]    localLightOrigin
1342 c[5]    localViewOrigin
1343 c[6]    lightProjection S
1344 c[7]    lightProjection T
1345 c[8]    lightProjection Q
1346 c[9]    lightFalloff    S
1347 c[10]   bumpMatrix S
1348 c[11]   bumpMatrix T
1349 c[12]   diffuseMatrix S
1350 c[13]   diffuseMatrix T
1351 c[14]   specularMatrix S
1352 c[15]   specularMatrix T
1353
1354
1355 c[20]   light falloff tq constant
1356
1357 // texture 0 was cube map
1358 // texture 1 will be the per-surface bump map
1359 // texture 2 will be the light falloff texture
1360 // texture 3 will be the light projection texture
1361 // texture 4 is the per-surface diffuse map
1362 // texture 5 is the per-surface specular map
1363 // texture 6 is the specular half angle cube map
1364
1365 */
1366
1367 typedef enum {
1368         PP_LIGHT_ORIGIN = 4,
1369         PP_VIEW_ORIGIN,
1370         PP_LIGHT_PROJECT_S,
1371         PP_LIGHT_PROJECT_T,
1372         PP_LIGHT_PROJECT_Q,
1373         PP_LIGHT_FALLOFF_S,
1374         PP_BUMP_MATRIX_S,
1375         PP_BUMP_MATRIX_T,
1376         PP_DIFFUSE_MATRIX_S,
1377         PP_DIFFUSE_MATRIX_T,
1378         PP_SPECULAR_MATRIX_S,
1379         PP_SPECULAR_MATRIX_T,
1380         PP_COLOR_MODULATE,
1381         PP_COLOR_ADD,
1382
1383         PP_LIGHT_FALLOFF_TQ = 20        // only for NV programs
1384 } programParameter_t;
1385
1386
1387 /*
1388 ============================================================
1389
1390 TR_STENCILSHADOWS
1391
1392 "facing" should have one more element than tri->numIndexes / 3, which should be set to 1
1393
1394 ============================================================
1395 */
1396
1397 void R_MakeShadowFrustums( idRenderLightLocal *def );
1398
1399 typedef enum {
1400         SG_DYNAMIC,             // use infinite projections
1401         SG_STATIC,              // clip to bounds
1402         SG_OFFLINE              // perform very time consuming optimizations
1403 } shadowGen_t;
1404
1405 srfTriangles_t *R_CreateShadowVolume( const idRenderEntityLocal *ent,
1406                                                                          const srfTriangles_t *tri, const idRenderLightLocal *light,
1407                                                                          shadowGen_t optimize, srfCullInfo_t &cullInfo );
1408
1409 /*
1410 ============================================================
1411
1412 TR_TURBOSHADOW
1413
1414 Fast, non-clipped overshoot shadow volumes
1415
1416 "facing" should have one more element than tri->numIndexes / 3, which should be set to 1
1417 calling this function may modify "facing" based on culling
1418
1419 ============================================================
1420 */
1421
1422 srfTriangles_t *R_CreateVertexProgramTurboShadowVolume( const idRenderEntityLocal *ent,
1423                                                                          const srfTriangles_t *tri, const idRenderLightLocal *light,
1424                                                                          srfCullInfo_t &cullInfo );
1425
1426 srfTriangles_t *R_CreateTurboShadowVolume( const idRenderEntityLocal *ent,
1427                                                                          const srfTriangles_t *tri, const idRenderLightLocal *light,
1428                                                                          srfCullInfo_t &cullInfo );
1429
1430 /*
1431 ============================================================
1432
1433 util/shadowopt3
1434
1435 dmap time optimization of shadow volumes, called from R_CreateShadowVolume
1436
1437 ============================================================
1438 */
1439
1440
1441 typedef struct {
1442         idVec3  *verts;                 // includes both front and back projections, caller should free
1443         int             numVerts;
1444         glIndex_t       *indexes;       // caller should free
1445
1446         // indexes must be sorted frontCap, rearCap, silPlanes so the caps can be removed
1447         // when the viewer is in a position that they don't need to see them
1448         int             numFrontCapIndexes;
1449         int             numRearCapIndexes;
1450         int             numSilPlaneIndexes;
1451         int             totalIndexes;
1452 } optimizedShadow_t;
1453
1454 optimizedShadow_t SuperOptimizeOccluders( idVec4 *verts, glIndex_t *indexes, int numIndexes, 
1455                                                                                  idPlane projectionPlane, idVec3 projectionOrigin );
1456
1457 void CleanupOptimizedShadowTris( srfTriangles_t *tri );
1458
1459 /*
1460 ============================================================
1461
1462 TRISURF
1463
1464 ============================================================
1465 */
1466
1467 #define USE_TRI_DATA_ALLOCATOR
1468
1469 void                            R_InitTriSurfData( void );
1470 void                            R_ShutdownTriSurfData( void );
1471 void                            R_PurgeTriSurfData( frameData_t *frame );
1472 void                            R_ShowTriSurfMemory_f( const idCmdArgs &args );
1473
1474 srfTriangles_t *        R_AllocStaticTriSurf( void );
1475 srfTriangles_t *        R_CopyStaticTriSurf( const srfTriangles_t *tri );
1476 void                            R_AllocStaticTriSurfVerts( srfTriangles_t *tri, int numVerts );
1477 void                            R_AllocStaticTriSurfIndexes( srfTriangles_t *tri, int numIndexes );
1478 void                            R_AllocStaticTriSurfShadowVerts( srfTriangles_t *tri, int numVerts );
1479 void                            R_AllocStaticTriSurfPlanes( srfTriangles_t *tri, int numIndexes );
1480 void                            R_ResizeStaticTriSurfVerts( srfTriangles_t *tri, int numVerts );
1481 void                            R_ResizeStaticTriSurfIndexes( srfTriangles_t *tri, int numIndexes );
1482 void                            R_ResizeStaticTriSurfShadowVerts( srfTriangles_t *tri, int numVerts );
1483 void                            R_ReferenceStaticTriSurfVerts( srfTriangles_t *tri, const srfTriangles_t *reference );
1484 void                            R_ReferenceStaticTriSurfIndexes( srfTriangles_t *tri, const srfTriangles_t *reference );
1485 void                            R_FreeStaticTriSurfSilIndexes( srfTriangles_t *tri );
1486 void                            R_FreeStaticTriSurf( srfTriangles_t *tri );
1487 void                            R_FreeStaticTriSurfVertexCaches( srfTriangles_t *tri );
1488 void                            R_ReallyFreeStaticTriSurf( srfTriangles_t *tri );
1489 void                            R_FreeDeferredTriSurfs( frameData_t *frame );
1490 int                                     R_TriSurfMemory( const srfTriangles_t *tri );
1491
1492 void                            R_BoundTriSurf( srfTriangles_t *tri );
1493 void                            R_RemoveDuplicatedTriangles( srfTriangles_t *tri );
1494 void                            R_CreateSilIndexes( srfTriangles_t *tri );
1495 void                            R_RemoveDegenerateTriangles( srfTriangles_t *tri );
1496 void                            R_RemoveUnusedVerts( srfTriangles_t *tri );
1497 void                            R_RangeCheckIndexes( const srfTriangles_t *tri );
1498 void                            R_CreateVertexNormals( srfTriangles_t *tri );   // also called by dmap
1499 void                            R_DeriveFacePlanes( srfTriangles_t *tri );              // also called by renderbump
1500 void                            R_CleanupTriangles( srfTriangles_t *tri, bool createNormals, bool identifySilEdges, bool useUnsmoothedTangents );
1501 void                            R_ReverseTriangles( srfTriangles_t *tri );
1502
1503 // Only deals with vertexes and indexes, not silhouettes, planes, etc.
1504 // Does NOT perform a cleanup triangles, so there may be duplicated verts in the result.
1505 srfTriangles_t *        R_MergeSurfaceList( const srfTriangles_t **surfaces, int numSurfaces );
1506 srfTriangles_t *        R_MergeTriangles( const srfTriangles_t *tri1, const srfTriangles_t *tri2 );
1507
1508 // if the deformed verts have significant enough texture coordinate changes to reverse the texture
1509 // polarity of a triangle, the tangents will be incorrect
1510 void                            R_DeriveTangents( srfTriangles_t *tri, bool allocFacePlanes = true );
1511
1512 // deformable meshes precalculate as much as possible from a base frame, then generate
1513 // complete srfTriangles_t from just a new set of vertexes
1514 typedef struct deformInfo_s {
1515         int                             numSourceVerts;
1516
1517         // numOutputVerts may be smaller if the input had duplicated or degenerate triangles
1518         // it will often be larger if the input had mirrored texture seams that needed
1519         // to be busted for proper tangent spaces
1520         int                             numOutputVerts;
1521
1522         int                             numMirroredVerts;
1523         int *                   mirroredVerts;
1524
1525         int                             numIndexes;
1526         glIndex_t *             indexes;
1527
1528         glIndex_t *             silIndexes;
1529
1530         int                             numDupVerts;
1531         int *                   dupVerts;
1532
1533         int                             numSilEdges;
1534         silEdge_t *             silEdges;
1535
1536         dominantTri_t * dominantTris;
1537 } deformInfo_t;
1538
1539
1540 deformInfo_t *          R_BuildDeformInfo( int numVerts, const idDrawVert *verts, int numIndexes, const int *indexes, bool useUnsmoothedTangents );
1541 void                            R_FreeDeformInfo( deformInfo_t *deformInfo );
1542 int                                     R_DeformInfoMemoryUsed( deformInfo_t *deformInfo );
1543
1544 /*
1545 ============================================================
1546
1547 SUBVIEW
1548
1549 ============================================================
1550 */
1551
1552 bool    R_PreciseCullSurface( const drawSurf_t *drawSurf, idBounds &ndcBounds );
1553 bool    R_GenerateSubViews( void );
1554
1555 /*
1556 ============================================================
1557
1558 SCENE GENERATION
1559
1560 ============================================================
1561 */
1562
1563 void R_InitFrameData( void );
1564 void R_ShutdownFrameData( void );
1565 int R_CountFrameData( void );
1566 void R_ToggleSmpFrame( void );
1567 void *R_FrameAlloc( int bytes );
1568 void *R_ClearedFrameAlloc( int bytes );
1569 void R_FrameFree( void *data );
1570
1571 void *R_StaticAlloc( int bytes );               // just malloc with error checking
1572 void *R_ClearedStaticAlloc( int bytes );        // with memset
1573 void R_StaticFree( void *data );
1574
1575
1576 /*
1577 =============================================================
1578
1579 RENDERER DEBUG TOOLS
1580
1581 =============================================================
1582 */
1583
1584 float RB_DrawTextLength( const char *text, float scale, int len );
1585 void RB_AddDebugText( const char *text, const idVec3 &origin, float scale, const idVec4 &color, const idMat3 &viewAxis, const int align, const int lifetime, const bool depthTest );
1586 void RB_ClearDebugText( int time );
1587 void RB_AddDebugLine( const idVec4 &color, const idVec3 &start, const idVec3 &end, const int lifeTime, const bool depthTest );
1588 void RB_ClearDebugLines( int time );
1589 void RB_AddDebugPolygon( const idVec4 &color, const idWinding &winding, const int lifeTime, const bool depthTest );
1590 void RB_ClearDebugPolygons( int time );
1591 void RB_DrawBounds( const idBounds &bounds );
1592 void RB_ShowLights( drawSurf_t **drawSurfs, int numDrawSurfs );
1593 void RB_ShowLightCount( drawSurf_t **drawSurfs, int numDrawSurfs );
1594 void RB_PolygonClear( void );
1595 void RB_ScanStencilBuffer( void );
1596 void RB_ShowDestinationAlpha( void );
1597 void RB_ShowOverdraw( void );
1598 void RB_RenderDebugTools( drawSurf_t **drawSurfs, int numDrawSurfs );
1599 void RB_ShutdownDebugTools( void );
1600
1601 /*
1602 =============================================================
1603
1604 TR_BACKEND
1605
1606 =============================================================
1607 */
1608
1609 void RB_SetDefaultGLState( void );
1610 void RB_SetGL2D( void );
1611
1612 // write a comment to the r_logFile if it is enabled
1613 void RB_LogComment( const char *comment, ... ) id_attribute((format(printf,1,2)));
1614
1615 void RB_ShowImages( void );
1616
1617 void RB_ExecuteBackEndCommands( const emptyCommand_t *cmds );
1618
1619
1620 /*
1621 =============================================================
1622
1623 TR_GUISURF
1624
1625 =============================================================
1626 */
1627
1628 void R_SurfaceToTextureAxis( const srfTriangles_t *tri, idVec3 &origin, idVec3 axis[3] );
1629 void R_RenderGuiSurf( idUserInterface *gui, drawSurf_t *drawSurf );
1630
1631 /*
1632 =============================================================
1633
1634 TR_ORDERINDEXES
1635
1636 =============================================================
1637 */
1638
1639 void R_OrderIndexes( int numIndexes, glIndex_t *indexes );
1640
1641 /*
1642 =============================================================
1643
1644 TR_DEFORM
1645
1646 =============================================================
1647 */
1648
1649 void R_DeformDrawSurf( drawSurf_t *drawSurf );
1650
1651 /*
1652 =============================================================
1653
1654 TR_TRACE
1655
1656 =============================================================
1657 */
1658
1659 typedef struct {
1660         float           fraction;
1661         // only valid if fraction < 1.0
1662         idVec3          point;
1663         idVec3          normal;
1664         int                     indexes[3];
1665 } localTrace_t;
1666
1667 localTrace_t R_LocalTrace( const idVec3 &start, const idVec3 &end, const float radius, const srfTriangles_t *tri );
1668 void RB_ShowTrace( drawSurf_t **drawSurfs, int numDrawSurfs );
1669
1670 /*
1671 =============================================================
1672
1673 TR_SHADOWBOUNDS
1674
1675 =============================================================
1676 */
1677 idScreenRect R_CalcIntersectionScissor( const idRenderLightLocal * lightDef,
1678                                                                             const idRenderEntityLocal * entityDef,
1679                                                                             const viewDef_t * viewDef );
1680
1681 //=============================================
1682
1683 #include "RenderWorld_local.h"
1684 #include "GuiModel.h"
1685 #include "VertexCache.h"
1686
1687 #endif /* !__TR_LOCAL_H__ */