tr_local.h 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  1. /*
  2. ===========================================================================
  3. Doom 3 BFG Edition GPL Source Code
  4. Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
  5. This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
  6. Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation, either version 3 of the License, or
  9. (at your option) any later version.
  10. Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
  16. In addition, the Doom 3 BFG Edition 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 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
  17. 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.
  18. ===========================================================================
  19. */
  20. #ifndef __TR_LOCAL_H__
  21. #define __TR_LOCAL_H__
  22. #include "../idlib/precompiled.h"
  23. #include "GLState.h"
  24. #include "ScreenRect.h"
  25. #include "ImageOpts.h"
  26. #include "Image.h"
  27. #include "RenderTexture.h"
  28. #include "Font.h"
  29. // everything that is needed by the backend needs
  30. // to be double buffered to allow it to run in
  31. // parallel on a dual cpu machine
  32. const int SMP_FRAMES = 1;
  33. // maximum texture units
  34. const int MAX_PROG_TEXTURE_PARMS = 16;
  35. const int FALLOFF_TEXTURE_SIZE = 64;
  36. const float DEFAULT_FOG_DISTANCE = 500.0f;
  37. // picky to get the bilerp correct at terminator
  38. const int FOG_ENTER_SIZE = 64;
  39. const float FOG_ENTER = (FOG_ENTER_SIZE+1.0f)/(FOG_ENTER_SIZE*2);
  40. enum demoCommand_t {
  41. DC_BAD,
  42. DC_RENDERVIEW,
  43. DC_UPDATE_ENTITYDEF,
  44. DC_DELETE_ENTITYDEF,
  45. DC_UPDATE_LIGHTDEF,
  46. DC_DELETE_LIGHTDEF,
  47. DC_LOADMAP,
  48. DC_CROP_RENDER,
  49. DC_UNCROP_RENDER,
  50. DC_CAPTURE_RENDER,
  51. DC_END_FRAME,
  52. DC_DEFINE_MODEL,
  53. DC_SET_PORTAL_STATE,
  54. DC_UPDATE_SOUNDOCCLUSION,
  55. DC_GUI_MODEL
  56. };
  57. /*
  58. ==============================================================================
  59. SURFACES
  60. ==============================================================================
  61. */
  62. #include "ModelDecal.h"
  63. #include "ModelOverlay.h"
  64. #include "Interaction.h"
  65. class idRenderWorldLocal;
  66. struct viewEntity_t;
  67. struct viewLight_t;
  68. // drawSurf_t structures command the back end to render surfaces
  69. // a given srfTriangles_t may be used with multiple viewEntity_t,
  70. // as when viewed in a subview or multiple viewport render, or
  71. // with multiple shaders when skinned, or, possibly with multiple
  72. // lights, although currently each lighting interaction creates
  73. // unique srfTriangles_t
  74. // drawSurf_t are always allocated and freed every frame, they are never cached
  75. struct drawSurf_t {
  76. const srfTriangles_t * frontEndGeo; // don't use on the back end, it may be updated by the front end!
  77. int numIndexes;
  78. vertCacheHandle_t indexCache; // triIndex_t
  79. vertCacheHandle_t ambientCache; // idDrawVert
  80. vertCacheHandle_t shadowCache; // idShadowVert / idShadowVertSkinned
  81. vertCacheHandle_t jointCache; // idJointMat
  82. const viewEntity_t * space;
  83. const idMaterial * material; // may be NULL for shadow volumes
  84. uint64 extraGLState; // Extra GL state |'d with material->stage[].drawStateBits
  85. float sort; // material->sort, modified by gui / entity sort offsets
  86. const float * shaderRegisters; // evaluated and adjusted for referenceShaders
  87. drawSurf_t * nextOnLight; // viewLight chains
  88. drawSurf_t ** linkChain; // defer linking to lights to a serial section to avoid a mutex
  89. idScreenRect scissorRect; // for scissor clipping, local inside renderView viewport
  90. int renderZFail;
  91. volatile shadowVolumeState_t shadowVolumeState;
  92. };
  93. // areas have references to hold all the lights and entities in them
  94. struct areaReference_t {
  95. areaReference_t * areaNext; // chain in the area
  96. areaReference_t * areaPrev;
  97. areaReference_t * ownerNext; // chain on either the entityDef or lightDef
  98. idRenderEntityLocal * entity; // only one of entity / light will be non-NULL
  99. idRenderLightLocal * light; // only one of entity / light will be non-NULL
  100. struct portalArea_s * area; // so owners can find all the areas they are in
  101. };
  102. // idRenderLight should become the new public interface replacing the qhandle_t to light defs in the idRenderWorld interface
  103. class idRenderLight {
  104. public:
  105. virtual ~idRenderLight() {}
  106. virtual void FreeRenderLight() = 0;
  107. virtual void UpdateRenderLight( const renderLight_t *re, bool forceUpdate = false ) = 0;
  108. virtual void GetRenderLight( renderLight_t *re ) = 0;
  109. virtual void ForceUpdate() = 0;
  110. virtual int GetIndex() = 0;
  111. };
  112. // idRenderEntity should become the new public interface replacing the qhandle_t to entity defs in the idRenderWorld interface
  113. class idRenderEntity {
  114. public:
  115. virtual ~idRenderEntity() {}
  116. virtual void FreeRenderEntity() = 0;
  117. virtual void UpdateRenderEntity( const renderEntity_t *re, bool forceUpdate = false ) = 0;
  118. virtual void GetRenderEntity( renderEntity_t *re ) = 0;
  119. virtual void ForceUpdate() = 0;
  120. virtual int GetIndex() = 0;
  121. // overlays are extra polygons that deform with animating models for blood and damage marks
  122. virtual void ProjectOverlay( const idPlane localTextureAxis[2], const idMaterial *material ) = 0;
  123. virtual void RemoveDecals() = 0;
  124. };
  125. class idRenderLightLocal : public idRenderLight {
  126. public:
  127. idRenderLightLocal();
  128. virtual void FreeRenderLight();
  129. virtual void UpdateRenderLight( const renderLight_t *re, bool forceUpdate = false );
  130. virtual void GetRenderLight( renderLight_t *re );
  131. virtual void ForceUpdate();
  132. virtual int GetIndex();
  133. bool LightCastsShadows() const { return parms.forceShadows || ( !parms.noShadows && lightShader->LightCastsShadows() ); }
  134. renderLight_t parms; // specification
  135. bool lightHasMoved; // the light has changed its position since it was
  136. // first added, so the prelight model is not valid
  137. idRenderWorldLocal * world;
  138. int index; // in world lightdefs
  139. int areaNum; // if not -1, we may be able to cull all the light's
  140. // interactions if !viewDef->connectedAreas[areaNum]
  141. int lastModifiedFrameNum; // to determine if it is constantly changing,
  142. // and should go in the dynamic frame memory, or kept
  143. // in the cached memory
  144. bool archived; // for demo writing
  145. // derived information
  146. idPlane lightProject[4]; // old style light projection where Z and W are flipped and projected lights lightProject[3] is divided by ( zNear + zFar )
  147. idRenderMatrix baseLightProject; // global xyz1 to projected light strq
  148. idRenderMatrix inverseBaseLightProject;// transforms the zero-to-one cube to exactly cover the light in world space
  149. const idMaterial * lightShader; // guaranteed to be valid, even if parms.shader isn't
  150. idImage * falloffImage;
  151. idVec3 globalLightOrigin; // accounting for lightCenter and parallel
  152. idBounds globalLightBounds;
  153. int viewCount; // if == tr.viewCount, the light is on the viewDef->viewLights list
  154. viewLight_t * viewLight;
  155. areaReference_t * references; // each area the light is present in will have a lightRef
  156. idInteraction * firstInteraction; // doubly linked list
  157. idInteraction * lastInteraction;
  158. struct doublePortal_s * foggedPortals;
  159. };
  160. class idRenderEntityLocal : public idRenderEntity {
  161. public:
  162. idRenderEntityLocal();
  163. virtual void FreeRenderEntity();
  164. virtual void UpdateRenderEntity( const renderEntity_t *re, bool forceUpdate = false );
  165. virtual void GetRenderEntity( renderEntity_t *re );
  166. virtual void ForceUpdate();
  167. virtual int GetIndex();
  168. // overlays are extra polygons that deform with animating models for blood and damage marks
  169. virtual void ProjectOverlay( const idPlane localTextureAxis[2], const idMaterial *material );
  170. virtual void RemoveDecals();
  171. bool IsDirectlyVisible() const;
  172. renderEntity_t parms;
  173. float modelMatrix[16]; // this is just a rearrangement of parms.axis and parms.origin
  174. idRenderMatrix modelRenderMatrix;
  175. idRenderMatrix inverseBaseModelProject;// transforms the unit cube to exactly cover the model in world space
  176. idRenderWorldLocal * world;
  177. int index; // in world entityDefs
  178. int lastModifiedFrameNum; // to determine if it is constantly changing,
  179. // and should go in the dynamic frame memory, or kept
  180. // in the cached memory
  181. bool archived; // for demo writing
  182. idRenderModel * dynamicModel; // if parms.model->IsDynamicModel(), this is the generated data
  183. int dynamicModelFrameCount; // continuously animating dynamic models will recreate
  184. // dynamicModel if this doesn't == tr.viewCount
  185. idRenderModel * cachedDynamicModel;
  186. // the local bounds used to place entityRefs, either from parms for dynamic entities, or a model bounds
  187. idBounds localReferenceBounds;
  188. // axis aligned bounding box in world space, derived from refernceBounds and
  189. // modelMatrix in R_CreateEntityRefs()
  190. idBounds globalReferenceBounds;
  191. // a viewEntity_t is created whenever a idRenderEntityLocal is considered for inclusion
  192. // in a given view, even if it turns out to not be visible
  193. int viewCount; // if tr.viewCount == viewCount, viewEntity is valid,
  194. // but the entity may still be off screen
  195. viewEntity_t * viewEntity; // in frame temporary memory
  196. idRenderModelDecal * decals; // decals that have been projected on this model
  197. idRenderModelOverlay * overlays; // blood overlays on animated models
  198. areaReference_t * entityRefs; // chain of all references
  199. idInteraction * firstInteraction; // doubly linked list
  200. idInteraction * lastInteraction;
  201. bool needsPortalSky;
  202. };
  203. struct shadowOnlyEntity_t {
  204. shadowOnlyEntity_t * next;
  205. idRenderEntityLocal * edef;
  206. };
  207. // viewLights are allocated on the frame temporary stack memory
  208. // a viewLight contains everything that the back end needs out of an idRenderLightLocal,
  209. // which the front end may be modifying simultaniously if running in SMP mode.
  210. // a viewLight may exist even without any surfaces, and may be relevent for fogging,
  211. // but should never exist if its volume does not intersect the view frustum
  212. struct viewLight_t {
  213. viewLight_t * next;
  214. // back end should NOT reference the lightDef, because it can change when running SMP
  215. idRenderLightLocal * lightDef;
  216. // for scissor clipping, local inside renderView viewport
  217. // scissorRect.Empty() is true if the viewEntity_t was never actually
  218. // seen through any portals
  219. idScreenRect scissorRect;
  220. // R_AddSingleLight() determined that the light isn't actually needed
  221. bool removeFromList;
  222. // R_AddSingleLight builds this list of entities that need to be added
  223. // to the viewEntities list because they potentially cast shadows into
  224. // the view, even though the aren't directly visible
  225. shadowOnlyEntity_t * shadowOnlyViewEntities;
  226. enum interactionState_t {
  227. INTERACTION_UNCHECKED,
  228. INTERACTION_NO,
  229. INTERACTION_YES
  230. };
  231. byte * entityInteractionState; // [numEntities]
  232. idVec3 globalLightOrigin; // global light origin used by backend
  233. idPlane lightProject[4]; // light project used by backend
  234. idPlane fogPlane; // fog plane for backend fog volume rendering
  235. idRenderMatrix inverseBaseLightProject; // the matrix for deforming the 'zeroOneCubeModel' to exactly cover the light volume in world space
  236. const idMaterial * lightShader; // light shader used by backend
  237. const float * shaderRegisters; // shader registers used by backend
  238. idImage * falloffImage; // falloff image used by backend
  239. drawSurf_t * globalShadows; // shadow everything
  240. drawSurf_t * localInteractions; // don't get local shadows
  241. drawSurf_t * localShadows; // don't shadow local surfaces
  242. drawSurf_t * globalInteractions; // get shadows from everything
  243. drawSurf_t * translucentInteractions; // translucent interactions don't get shadows
  244. // R_AddSingleLight will build a chain of parameters here to setup shadow volumes
  245. preLightShadowVolumeParms_t * preLightShadowVolumes;
  246. };
  247. // a viewEntity is created whenever a idRenderEntityLocal is considered for inclusion
  248. // in the current view, but it may still turn out to be culled.
  249. // viewEntity are allocated on the frame temporary stack memory
  250. // a viewEntity contains everything that the back end needs out of a idRenderEntityLocal,
  251. // which the front end may be modifying simultaneously if running in SMP mode.
  252. // A single entityDef can generate multiple viewEntity_t in a single frame, as when seen in a mirror
  253. struct viewEntity_t {
  254. viewEntity_t * next;
  255. // back end should NOT reference the entityDef, because it can change when running SMP
  256. idRenderEntityLocal * entityDef;
  257. // for scissor clipping, local inside renderView viewport
  258. // scissorRect.Empty() is true if the viewEntity_t was never actually
  259. // seen through any portals, but was created for shadow casting.
  260. // a viewEntity can have a non-empty scissorRect, meaning that an area
  261. // that it is in is visible, and still not be visible.
  262. idScreenRect scissorRect;
  263. bool isGuiSurface; // force two sided and vertex colors regardless of material setting
  264. bool skipMotionBlur;
  265. bool weaponDepthHack;
  266. float modelDepthHack;
  267. float modelMatrix[16]; // local coords to global coords
  268. float modelViewMatrix[16]; // local coords to eye coords
  269. idRenderMatrix mvp;
  270. // parallelAddModels will build a chain of surfaces here that will need to
  271. // be linked to the lights or added to the drawsurf list in a serial code section
  272. drawSurf_t * drawSurfs;
  273. // R_AddSingleModel will build a chain of parameters here to setup shadow volumes
  274. staticShadowVolumeParms_t * staticShadowVolumes;
  275. dynamicShadowVolumeParms_t * dynamicShadowVolumes;
  276. };
  277. const int MAX_CLIP_PLANES = 1; // we may expand this to six for some subview issues
  278. // viewDefs are allocated on the frame temporary stack memory
  279. struct viewDef_t {
  280. // specified in the call to DrawScene()
  281. renderView_t renderView;
  282. float projectionMatrix[16];
  283. idRenderMatrix projectionRenderMatrix; // tech5 version of projectionMatrix
  284. viewEntity_t worldSpace;
  285. idRenderWorldLocal *renderWorld;
  286. idVec3 initialViewAreaOrigin;
  287. // Used to find the portalArea that view flooding will take place from.
  288. // for a normal view, the initialViewOrigin will be renderView.viewOrg,
  289. // but a mirror may put the projection origin outside
  290. // of any valid area, or in an unconnected area of the map, so the view
  291. // area must be based on a point just off the surface of the mirror / subview.
  292. // It may be possible to get a failed portal pass if the plane of the
  293. // mirror intersects a portal, and the initialViewAreaOrigin is on
  294. // a different side than the renderView.viewOrg is.
  295. bool isSubview; // true if this view is not the main view
  296. bool isMirror; // the portal is a mirror, invert the face culling
  297. bool isXraySubview;
  298. bool isEditor;
  299. bool is2Dgui;
  300. int numClipPlanes; // mirrors will often use a single clip plane
  301. idPlane clipPlanes[MAX_CLIP_PLANES]; // in world space, the positive side
  302. // of the plane is the visible side
  303. idScreenRect viewport; // in real pixels and proper Y flip
  304. idScreenRect scissor;
  305. // for scissor clipping, local inside renderView viewport
  306. // subviews may only be rendering part of the main view
  307. // these are real physical pixel values, possibly scaled and offset from the
  308. // renderView x/y/width/height
  309. viewDef_t * superView; // never go into an infinite subview loop
  310. const drawSurf_t * subviewSurface;
  311. // drawSurfs are the visible surfaces of the viewEntities, sorted
  312. // by the material sort parameter
  313. drawSurf_t ** drawSurfs; // we don't use an idList for this, because
  314. int numDrawSurfs; // it is allocated in frame temporary memory
  315. int maxDrawSurfs; // may be resized
  316. viewLight_t * viewLights; // chain of all viewLights effecting view
  317. viewEntity_t * viewEntitys; // chain of all viewEntities effecting view, including off screen ones casting shadows
  318. // we use viewEntities as a check to see if a given view consists solely
  319. // of 2D rendering, which we can optimize in certain ways. A 2D view will
  320. // not have any viewEntities
  321. idPlane frustum[6]; // positive sides face outward, [4] is the front clip plane
  322. int areaNum; // -1 = not in a valid area
  323. // An array in frame temporary memory that lists if an area can be reached without
  324. // crossing a closed door. This is used to avoid drawing interactions
  325. // when the light is behind a closed door.
  326. bool * connectedAreas;
  327. };
  328. // complex light / surface interactions are broken up into multiple passes of a
  329. // simple interaction shader
  330. struct drawInteraction_t {
  331. const drawSurf_t * surf;
  332. idImage * bumpImage;
  333. idImage * diffuseImage;
  334. idImage * specularImage;
  335. idVec4 diffuseColor; // may have a light color baked into it
  336. idVec4 specularColor; // may have a light color baked into it
  337. stageVertexColor_t vertexColor; // applies to both diffuse and specular
  338. int ambientLight; // use tr.ambientNormalMap instead of normalization cube map
  339. // these are loaded into the vertex program
  340. idVec4 bumpMatrix[2];
  341. idVec4 diffuseMatrix[2];
  342. idVec4 specularMatrix[2];
  343. };
  344. /*
  345. =============================================================
  346. RENDERER BACK END COMMAND QUEUE
  347. TR_CMDS
  348. =============================================================
  349. */
  350. enum renderCommand_t {
  351. RC_NOP,
  352. RC_DRAW_VIEW_3D, // may be at a reduced resolution, will be upsampled before 2D GUIs
  353. RC_DRAW_VIEW_GUI, // not resolution scaled
  354. RC_SET_BUFFER,
  355. RC_COPY_RENDER,
  356. RC_POST_PROCESS,
  357. };
  358. struct emptyCommand_t {
  359. renderCommand_t commandId;
  360. renderCommand_t * next;
  361. };
  362. struct setBufferCommand_t {
  363. renderCommand_t commandId;
  364. renderCommand_t * next;
  365. GLenum buffer;
  366. };
  367. struct drawSurfsCommand_t {
  368. renderCommand_t commandId;
  369. renderCommand_t * next;
  370. viewDef_t * viewDef;
  371. };
  372. struct copyRenderCommand_t {
  373. renderCommand_t commandId;
  374. renderCommand_t * next;
  375. int x;
  376. int y;
  377. int imageWidth;
  378. int imageHeight;
  379. idImage * image;
  380. int cubeFace; // when copying to a cubeMap
  381. bool clearColorAfterCopy;
  382. };
  383. struct postProcessCommand_t {
  384. renderCommand_t commandId;
  385. renderCommand_t * next;
  386. viewDef_t * viewDef;
  387. };
  388. //=======================================================================
  389. // this is the inital allocation for max number of drawsurfs
  390. // in a given view, but it will automatically grow if needed
  391. const int INITIAL_DRAWSURFS = 2048;
  392. enum frameAllocType_t {
  393. FRAME_ALLOC_VIEW_DEF,
  394. FRAME_ALLOC_VIEW_ENTITY,
  395. FRAME_ALLOC_VIEW_LIGHT,
  396. FRAME_ALLOC_SURFACE_TRIANGLES,
  397. FRAME_ALLOC_DRAW_SURFACE,
  398. FRAME_ALLOC_INTERACTION_STATE,
  399. FRAME_ALLOC_SHADOW_ONLY_ENTITY,
  400. FRAME_ALLOC_SHADOW_VOLUME_PARMS,
  401. FRAME_ALLOC_SHADER_REGISTER,
  402. FRAME_ALLOC_DRAW_SURFACE_POINTER,
  403. FRAME_ALLOC_DRAW_COMMAND,
  404. FRAME_ALLOC_UNKNOWN,
  405. FRAME_ALLOC_MAX
  406. };
  407. // all of the information needed by the back end must be
  408. // contained in a idFrameData. This entire structure is
  409. // duplicated so the front and back end can run in parallel
  410. // on an SMP machine.
  411. class idFrameData {
  412. public:
  413. idSysInterlockedInteger frameMemoryAllocated;
  414. idSysInterlockedInteger frameMemoryUsed;
  415. byte * frameMemory;
  416. int highWaterAllocated; // max used on any frame
  417. int highWaterUsed;
  418. // the currently building command list commands can be inserted
  419. // at the front if needed, as required for dynamically generated textures
  420. emptyCommand_t * cmdHead; // may be of other command type based on commandId
  421. emptyCommand_t * cmdTail;
  422. };
  423. extern idFrameData *frameData;
  424. //=======================================================================
  425. void R_AddDrawViewCmd( viewDef_t *parms, bool guiOnly );
  426. void R_AddDrawPostProcess( viewDef_t *parms );
  427. void R_ReloadGuis_f( const idCmdArgs &args );
  428. void R_ListGuis_f( const idCmdArgs &args );
  429. void *R_GetCommandBuffer( int bytes );
  430. // this allows a global override of all materials
  431. bool R_GlobalShaderOverride( const idMaterial **shader );
  432. // this does various checks before calling the idDeclSkin
  433. const idMaterial *R_RemapShaderBySkin( const idMaterial *shader, const idDeclSkin *customSkin, const idMaterial *customShader );
  434. //====================================================
  435. /*
  436. ** performanceCounters_t
  437. */
  438. struct performanceCounters_t {
  439. int c_box_cull_in;
  440. int c_box_cull_out;
  441. int c_createInteractions; // number of calls to idInteraction::CreateInteraction
  442. int c_createShadowVolumes;
  443. int c_generateMd5;
  444. int c_entityDefCallbacks;
  445. int c_alloc; // counts for R_StaticAllc/R_StaticFree
  446. int c_free;
  447. int c_visibleViewEntities;
  448. int c_shadowViewEntities;
  449. int c_viewLights;
  450. int c_numViews; // number of total views rendered
  451. int c_deformedSurfaces; // idMD5Mesh::GenerateSurface
  452. int c_deformedVerts; // idMD5Mesh::GenerateSurface
  453. int c_deformedIndexes; // idMD5Mesh::GenerateSurface
  454. int c_tangentIndexes; // R_DeriveTangents()
  455. int c_entityUpdates;
  456. int c_lightUpdates;
  457. int c_entityReferences;
  458. int c_lightReferences;
  459. int c_guiSurfs;
  460. int frontEndMicroSec; // sum of time in all RE_RenderScene's in a frame
  461. };
  462. struct tmu_t {
  463. unsigned int current2DMap;
  464. unsigned int currentCubeMap;
  465. };
  466. const int MAX_MULTITEXTURE_UNITS = 8;
  467. enum vertexLayoutType_t {
  468. LAYOUT_UNKNOWN = 0,
  469. LAYOUT_DRAW_VERT,
  470. LAYOUT_DRAW_SHADOW_VERT,
  471. LAYOUT_DRAW_SHADOW_VERT_SKINNED
  472. };
  473. struct glstate_t {
  474. tmu_t tmu[MAX_MULTITEXTURE_UNITS];
  475. int currenttmu;
  476. int faceCulling;
  477. vertexLayoutType_t vertexLayout;
  478. unsigned int currentVertexBuffer;
  479. unsigned int currentIndexBuffer;
  480. float polyOfsScale;
  481. float polyOfsBias;
  482. uint64 glStateBits;
  483. };
  484. struct backEndCounters_t {
  485. int c_surfaces;
  486. int c_shaders;
  487. int c_drawElements;
  488. int c_drawIndexes;
  489. int c_shadowElements;
  490. int c_shadowIndexes;
  491. int c_copyFrameBuffer;
  492. float c_overDraw;
  493. int totalMicroSec; // total microseconds for backend run
  494. int shadowMicroSec;
  495. };
  496. // all state modified by the back end is separated
  497. // from the front end state
  498. struct backEndState_t {
  499. const viewDef_t * viewDef;
  500. backEndCounters_t pc;
  501. const viewEntity_t *currentSpace; // for detecting when a matrix must change
  502. idScreenRect currentScissor; // for scissor clipping, local inside renderView viewport
  503. glstate_t glState; // for OpenGL state deltas
  504. bool currentRenderCopied; // true if any material has already referenced _currentRender
  505. idRenderMatrix prevMVP[2]; // world MVP from previous frame for motion blur, per-eye
  506. // surfaces used for code-based drawing
  507. drawSurf_t unitSquareSurface;
  508. drawSurf_t zeroOneCubeSurface;
  509. drawSurf_t testImageSurface;
  510. };
  511. class idParallelJobList;
  512. const int MAX_GUI_SURFACES = 1024; // default size of the drawSurfs list for guis, will
  513. // be automatically expanded as needed
  514. static const int MAX_RENDER_CROPS = 8;
  515. /*
  516. ** Most renderer globals are defined here.
  517. ** backend functions should never modify any of these fields,
  518. ** but may read fields that aren't dynamically modified
  519. ** by the frontend.
  520. */
  521. class idRenderSystemLocal : public idRenderSystem {
  522. public:
  523. // external functions
  524. virtual void Init();
  525. virtual void Shutdown();
  526. virtual void ResetGuiModels();
  527. virtual void InitOpenGL();
  528. virtual void ShutdownOpenGL();
  529. virtual bool IsOpenGLRunning() const;
  530. virtual bool IsFullScreen() const;
  531. virtual stereo3DMode_t GetStereo3DMode() const;
  532. virtual bool HasQuadBufferSupport() const;
  533. virtual bool IsStereoScopicRenderingSupported() const;
  534. virtual stereo3DMode_t GetStereoScopicRenderingMode() const;
  535. virtual void EnableStereoScopicRendering( const stereo3DMode_t mode ) const;
  536. virtual int GetWidth() const;
  537. virtual int GetHeight() const;
  538. virtual float GetPixelAspect() const;
  539. virtual float GetPhysicalScreenWidthInCentimeters() const;
  540. virtual idRenderWorld * AllocRenderWorld();
  541. virtual void FreeRenderWorld( idRenderWorld *rw );
  542. virtual void BeginLevelLoad();
  543. virtual void EndLevelLoad();
  544. virtual void LoadLevelImages();
  545. virtual void Preload( const idPreloadManifest &manifest, const char *mapName );
  546. virtual void BeginAutomaticBackgroundSwaps( autoRenderIconType_t icon = AUTORENDER_DEFAULTICON );
  547. virtual void EndAutomaticBackgroundSwaps();
  548. virtual bool AreAutomaticBackgroundSwapsRunning( autoRenderIconType_t * usingAlternateIcon = NULL ) const;
  549. virtual idFont * RegisterFont( const char * fontName );
  550. virtual void ResetFonts();
  551. virtual void PrintMemInfo( MemInfo_t *mi );
  552. virtual void SetColor( const idVec4 & color );
  553. virtual uint32 GetColor();
  554. virtual void SetGLState( const uint64 glState ) ;
  555. virtual void DrawFilled( const idVec4 & color, float x, float y, float w, float h );
  556. virtual void DrawStretchPic ( float x, float y, float w, float h, float s1, float t1, float s2, float t2, const idMaterial *material );
  557. virtual void DrawStretchPic( const idVec4 & topLeft, const idVec4 & topRight, const idVec4 & bottomRight, const idVec4 & bottomLeft, const idMaterial * material );
  558. virtual void DrawStretchTri ( const idVec2 & p1, const idVec2 & p2, const idVec2 & p3, const idVec2 & t1, const idVec2 & t2, const idVec2 & t3, const idMaterial *material );
  559. virtual idDrawVert * AllocTris( int numVerts, const triIndex_t * indexes, int numIndexes, const idMaterial * material, const stereoDepthType_t stereoType = STEREO_DEPTH_TYPE_NONE );
  560. virtual void DrawSmallChar( int x, int y, int ch );
  561. virtual void DrawSmallStringExt( int x, int y, const char *string, const idVec4 &setColor, bool forceColor );
  562. virtual void DrawBigChar( int x, int y, int ch );
  563. virtual void DrawBigStringExt( int x, int y, const char *string, const idVec4 &setColor, bool forceColor );
  564. virtual void WriteDemoPics();
  565. virtual void DrawDemoPics();
  566. virtual const emptyCommand_t * SwapCommandBuffers( uint64 *frontEndMicroSec, uint64 *backEndMicroSec, uint64 *shadowMicroSec, uint64 *gpuMicroSec );
  567. virtual void SwapCommandBuffers_FinishRendering( uint64 *frontEndMicroSec, uint64 *backEndMicroSec, uint64 *shadowMicroSec, uint64 *gpuMicroSec );
  568. virtual const emptyCommand_t * SwapCommandBuffers_FinishCommandBuffers();
  569. virtual void RenderCommandBuffers( const emptyCommand_t * commandBuffers );
  570. virtual void TakeScreenshot( int width, int height, const char *fileName, int downSample, renderView_t *ref );
  571. virtual void CropRenderSize( int width, int height );
  572. virtual void CaptureRenderToImage( const char *imageName, bool clearColorAfterCopy = false );
  573. virtual void CaptureRenderToFile( const char *fileName, bool fixAlpha );
  574. virtual void UnCrop();
  575. virtual bool UploadImage( const char *imageName, const byte *data, int width, int height );
  576. public:
  577. // internal functions
  578. idRenderSystemLocal();
  579. ~idRenderSystemLocal();
  580. void Clear();
  581. void GetCroppedViewport( idScreenRect * viewport );
  582. void PerformResolutionScaling( int& newWidth, int& newHeight );
  583. int GetFrameCount() const { return frameCount; };
  584. public:
  585. // renderer globals
  586. bool registered; // cleared at shutdown, set at InitOpenGL
  587. bool takingScreenshot;
  588. int frameCount; // incremented every frame
  589. int viewCount; // incremented every view (twice a scene if subviewed)
  590. // and every R_MarkFragments call
  591. float frameShaderTime; // shader time for all non-world 2D rendering
  592. idVec4 ambientLightVector; // used for "ambient bump mapping"
  593. idList<idRenderWorldLocal*>worlds;
  594. idRenderWorldLocal * primaryWorld;
  595. renderView_t primaryRenderView;
  596. viewDef_t * primaryView;
  597. // many console commands need to know which world they should operate on
  598. const idMaterial * whiteMaterial;
  599. const idMaterial * charSetMaterial;
  600. const idMaterial * defaultPointLight;
  601. const idMaterial * defaultProjectedLight;
  602. const idMaterial * defaultMaterial;
  603. idImage * testImage;
  604. idCinematic * testVideo;
  605. int testVideoStartTime;
  606. idImage * ambientCubeImage; // hack for testing dependent ambient lighting
  607. viewDef_t * viewDef;
  608. performanceCounters_t pc; // performance counters
  609. viewEntity_t identitySpace; // can use if we don't know viewDef->worldSpace is valid
  610. idScreenRect renderCrops[MAX_RENDER_CROPS];
  611. int currentRenderCrop;
  612. // GUI drawing variables for surface creation
  613. int guiRecursionLevel; // to prevent infinite overruns
  614. uint32 currentColorNativeBytesOrder;
  615. uint64 currentGLState;
  616. class idGuiModel * guiModel;
  617. idList<idFont *, TAG_FONT> fonts;
  618. unsigned short gammaTable[256]; // brightness / gamma modify this
  619. srfTriangles_t * unitSquareTriangles;
  620. srfTriangles_t * zeroOneCubeTriangles;
  621. srfTriangles_t * testImageTriangles;
  622. // these are allocated at buffer swap time, but
  623. // the back end should only use the ones in the backEnd stucture,
  624. // which are copied over from the frame that was just swapped.
  625. drawSurf_t unitSquareSurface_;
  626. drawSurf_t zeroOneCubeSurface_;
  627. drawSurf_t testImageSurface_;
  628. idParallelJobList * frontEndJobList;
  629. unsigned timerQueryId; // for GL_TIME_ELAPSED_EXT queries
  630. };
  631. extern backEndState_t backEnd;
  632. extern idRenderSystemLocal tr;
  633. extern glconfig_t glConfig; // outside of TR since it shouldn't be cleared during ref re-init
  634. //
  635. // cvars
  636. //
  637. extern idCVar r_debugContext; // enable various levels of context debug
  638. extern idCVar r_glDriver; // "opengl32", etc
  639. extern idCVar r_skipIntelWorkarounds; // skip work arounds for Intel driver bugs
  640. extern idCVar r_vidMode; // video mode number
  641. extern idCVar r_displayRefresh; // optional display refresh rate option for vid mode
  642. extern idCVar r_fullscreen; // 0 = windowed, 1 = full screen
  643. extern idCVar r_multiSamples; // number of antialiasing samples
  644. extern idCVar r_znear; // near Z clip plane
  645. extern idCVar r_swapInterval; // changes wglSwapIntarval
  646. extern idCVar r_offsetFactor; // polygon offset parameter
  647. extern idCVar r_offsetUnits; // polygon offset parameter
  648. extern idCVar r_singleTriangle; // only draw a single triangle per primitive
  649. extern idCVar r_logFile; // number of frames to emit GL logs
  650. extern idCVar r_clear; // force screen clear every frame
  651. extern idCVar r_subviewOnly; // 1 = don't render main view, allowing subviews to be debugged
  652. extern idCVar r_lightScale; // all light intensities are multiplied by this, which is normally 2
  653. extern idCVar r_flareSize; // scale the flare deforms from the material def
  654. extern idCVar r_gamma; // changes gamma tables
  655. extern idCVar r_brightness; // changes gamma tables
  656. extern idCVar r_checkBounds; // compare all surface bounds with precalculated ones
  657. extern idCVar r_maxAnisotropicFiltering; // texture filtering parameter
  658. extern idCVar r_useTrilinearFiltering; // Extra quality filtering
  659. extern idCVar r_lodBias; // lod bias
  660. extern idCVar r_useLightPortalFlow; // 1 = do a more precise area reference determination
  661. extern idCVar r_useShadowSurfaceScissor; // 1 = scissor shadows by the scissor rect of the interaction surfaces
  662. extern idCVar r_useConstantMaterials; // 1 = use pre-calculated material registers if possible
  663. extern idCVar r_useNodeCommonChildren; // stop pushing reference bounds early when possible
  664. extern idCVar r_useSilRemap; // 1 = consider verts with the same XYZ, but different ST the same for shadows
  665. extern idCVar r_useLightPortalCulling; // 0 = none, 1 = box, 2 = exact clip of polyhedron faces, 3 MVP to plane culling
  666. extern idCVar r_useLightAreaCulling; // 0 = off, 1 = on
  667. extern idCVar r_useLightScissors; // 1 = use custom scissor rectangle for each light
  668. extern idCVar r_useEntityPortalCulling; // 0 = none, 1 = box
  669. extern idCVar r_skipPrelightShadows; // 1 = skip the dmap generated static shadow volumes
  670. extern idCVar r_useCachedDynamicModels; // 1 = cache snapshots of dynamic models
  671. extern idCVar r_useScissor; // 1 = scissor clip as portals and lights are processed
  672. extern idCVar r_usePortals; // 1 = use portals to perform area culling, otherwise draw everything
  673. extern idCVar r_useStateCaching; // avoid redundant state changes in GL_*() calls
  674. extern idCVar r_useEntityCallbacks; // if 0, issue the callback immediately at update time, rather than defering
  675. extern idCVar r_lightAllBackFaces; // light all the back faces, even when they would be shadowed
  676. extern idCVar r_useLightDepthBounds; // use depth bounds test on lights to reduce both shadow and interaction fill
  677. extern idCVar r_useShadowDepthBounds; // use depth bounds test on individual shadows to reduce shadow fill
  678. extern idCVar r_skipStaticInteractions; // skip interactions created at level load
  679. extern idCVar r_skipDynamicInteractions; // skip interactions created after level load
  680. extern idCVar r_skipPostProcess; // skip all post-process renderings
  681. extern idCVar r_skipSuppress; // ignore the per-view suppressions
  682. extern idCVar r_skipInteractions; // skip all light/surface interaction drawing
  683. extern idCVar r_skipFrontEnd; // bypasses all front end work, but 2D gui rendering still draws
  684. extern idCVar r_skipBackEnd; // don't draw anything
  685. extern idCVar r_skipCopyTexture; // do all rendering, but don't actually copyTexSubImage2D
  686. extern idCVar r_skipRender; // skip 3D rendering, but pass 2D
  687. extern idCVar r_skipRenderContext; // NULL the rendering context during backend 3D rendering
  688. extern idCVar r_skipTranslucent; // skip the translucent interaction rendering
  689. extern idCVar r_skipAmbient; // bypasses all non-interaction drawing
  690. extern idCVar r_skipNewAmbient; // bypasses all vertex/fragment program ambients
  691. extern idCVar r_skipBlendLights; // skip all blend lights
  692. extern idCVar r_skipFogLights; // skip all fog lights
  693. extern idCVar r_skipSubviews; // 1 = don't render any mirrors / cameras / etc
  694. extern idCVar r_skipGuiShaders; // 1 = don't render any gui elements on surfaces
  695. extern idCVar r_skipParticles; // 1 = don't render any particles
  696. extern idCVar r_skipUpdates; // 1 = don't accept any entity or light updates, making everything static
  697. extern idCVar r_skipDeforms; // leave all deform materials in their original state
  698. extern idCVar r_skipDynamicTextures; // don't dynamically create textures
  699. extern idCVar r_skipBump; // uses a flat surface instead of the bump map
  700. extern idCVar r_skipSpecular; // use black for specular
  701. extern idCVar r_skipDiffuse; // use black for diffuse
  702. extern idCVar r_skipDecals; // skip decal surfaces
  703. extern idCVar r_skipOverlays; // skip overlay surfaces
  704. extern idCVar r_skipShadows; // disable shadows
  705. extern idCVar r_ignoreGLErrors;
  706. extern idCVar r_screenFraction; // for testing fill rate, the resolution of the entire screen can be changed
  707. extern idCVar r_showUnsmoothedTangents; // highlight geometry rendered with unsmoothed tangents
  708. extern idCVar r_showSilhouette; // highlight edges that are casting shadow planes
  709. extern idCVar r_showVertexColor; // draws all triangles with the solid vertex color
  710. extern idCVar r_showUpdates; // report entity and light updates and ref counts
  711. extern idCVar r_showDemo; // report reads and writes to the demo file
  712. extern idCVar r_showDynamic; // report stats on dynamic surface generation
  713. extern idCVar r_showIntensity; // draw the screen colors based on intensity, red = 0, green = 128, blue = 255
  714. extern idCVar r_showTrace; // show the intersection of an eye trace with the world
  715. extern idCVar r_showDepth; // display the contents of the depth buffer and the depth range
  716. extern idCVar r_showTris; // enables wireframe rendering of the world
  717. extern idCVar r_showSurfaceInfo; // show surface material name under crosshair
  718. extern idCVar r_showNormals; // draws wireframe normals
  719. extern idCVar r_showEdges; // draw the sil edges
  720. extern idCVar r_showViewEntitys; // displays the bounding boxes of all view models and optionally the index
  721. extern idCVar r_showTexturePolarity; // shade triangles by texture area polarity
  722. extern idCVar r_showTangentSpace; // shade triangles by tangent space
  723. extern idCVar r_showDominantTri; // draw lines from vertexes to center of dominant triangles
  724. extern idCVar r_showTextureVectors; // draw each triangles texture (tangent) vectors
  725. extern idCVar r_showLights; // 1 = print light info, 2 = also draw volumes
  726. extern idCVar r_showLightCount; // colors surfaces based on light count
  727. extern idCVar r_showShadows; // visualize the stencil shadow volumes
  728. extern idCVar r_showLightScissors; // show light scissor rectangles
  729. extern idCVar r_showMemory; // print frame memory utilization
  730. extern idCVar r_showCull; // report sphere and box culling stats
  731. extern idCVar r_showAddModel; // report stats from tr_addModel
  732. extern idCVar r_showSurfaces; // report surface/light/shadow counts
  733. extern idCVar r_showPrimitives; // report vertex/index/draw counts
  734. extern idCVar r_showPortals; // draw portal outlines in color based on passed / not passed
  735. extern idCVar r_showSkel; // draw the skeleton when model animates
  736. extern idCVar r_showOverDraw; // show overdraw
  737. extern idCVar r_jointNameScale; // size of joint names when r_showskel is set to 1
  738. extern idCVar r_jointNameOffset; // offset of joint names when r_showskel is set to 1
  739. extern idCVar r_testGamma; // draw a grid pattern to test gamma levels
  740. extern idCVar r_testGammaBias; // draw a grid pattern to test gamma levels
  741. extern idCVar r_singleLight; // suppress all but one light
  742. extern idCVar r_singleEntity; // suppress all but one entity
  743. extern idCVar r_singleArea; // only draw the portal area the view is actually in
  744. extern idCVar r_singleSurface; // suppress all but one surface on each entity
  745. extern idCVar r_shadowPolygonOffset; // bias value added to depth test for stencil shadow drawing
  746. extern idCVar r_shadowPolygonFactor; // scale value for stencil shadow drawing
  747. extern idCVar r_jitter; // randomly subpixel jitter the projection matrix
  748. extern idCVar r_orderIndexes; // perform index reorganization to optimize vertex use
  749. extern idCVar r_debugLineDepthTest; // perform depth test on debug lines
  750. extern idCVar r_debugLineWidth; // width of debug lines
  751. extern idCVar r_debugArrowStep; // step size of arrow cone line rotation in degrees
  752. extern idCVar r_debugPolygonFilled;
  753. extern idCVar r_materialOverride; // override all materials
  754. extern idCVar r_debugRenderToTexture;
  755. extern idCVar stereoRender_deGhost; // subtract from opposite eye to reduce ghosting
  756. extern idCVar r_useGPUSkinning;
  757. /*
  758. ====================================================================
  759. INITIALIZATION
  760. ====================================================================
  761. */
  762. void R_Init();
  763. void R_InitOpenGL();
  764. void R_SetColorMappings();
  765. void R_ScreenShot_f( const idCmdArgs &args );
  766. void R_StencilShot();
  767. /*
  768. ====================================================================
  769. IMPLEMENTATION SPECIFIC FUNCTIONS
  770. ====================================================================
  771. */
  772. struct vidMode_t {
  773. int width;
  774. int height;
  775. int displayHz;
  776. bool operator==( const vidMode_t & a ) {
  777. return a.width == width && a.height == height && a.displayHz == displayHz;
  778. }
  779. };
  780. // the number of displays can be found by itterating this until it returns false
  781. // displayNum is the 0 based value passed to EnumDisplayDevices(), you must add
  782. // 1 to this to get an r_fullScreen value.
  783. bool R_GetModeListForDisplay( const int displayNum, idList<vidMode_t> & modeList );
  784. struct glimpParms_t {
  785. int x; // ignored in fullscreen
  786. int y; // ignored in fullscreen
  787. int width;
  788. int height;
  789. int fullScreen; // 0 = windowed, otherwise 1 based monitor number to go full screen on
  790. // -1 = borderless window for spanning multiple displays
  791. bool stereo;
  792. int displayHz;
  793. int multiSamples;
  794. };
  795. bool GLimp_Init( glimpParms_t parms );
  796. // If the desired mode can't be set satisfactorily, false will be returned.
  797. // If succesful, sets glConfig.nativeScreenWidth, glConfig.nativeScreenHeight, and glConfig.pixelAspect
  798. // The renderer will then reset the glimpParms to "safe mode" of 640x480
  799. // fullscreen and try again. If that also fails, the error will be fatal.
  800. bool GLimp_SetScreenParms( glimpParms_t parms );
  801. // will set up gl up with the new parms
  802. void GLimp_Shutdown();
  803. // Destroys the rendering context, closes the window, resets the resolution,
  804. // and resets the gamma ramps.
  805. void GLimp_SetGamma( unsigned short red[256],
  806. unsigned short green[256],
  807. unsigned short blue[256] );
  808. // Sets the hardware gamma ramps for gamma and brightness adjustment.
  809. // These are now taken as 16 bit values, so we can take full advantage
  810. // of dacs with >8 bits of precision
  811. bool GLimp_SpawnRenderThread( void (*function)() );
  812. // Returns false if the system only has a single processor
  813. void * GLimp_BackEndSleep();
  814. void GLimp_FrontEndSleep();
  815. void GLimp_WakeBackEnd( void *data );
  816. // these functions implement the dual processor syncronization
  817. void GLimp_ActivateContext();
  818. void GLimp_DeactivateContext();
  819. // These are used for managing SMP handoffs of the OpenGL context
  820. // between threads, and as a performance tunining aid. Setting
  821. // 'r_skipRenderContext 1' will call GLimp_DeactivateContext() before
  822. // the 3D rendering code, and GLimp_ActivateContext() afterwards. On
  823. // most OpenGL implementations, this will result in all OpenGL calls
  824. // being immediate returns, which lets us guage how much time is
  825. // being spent inside OpenGL.
  826. void GLimp_EnableLogging( bool enable );
  827. /*
  828. ============================================================
  829. RENDERWORLD_DEFS
  830. ============================================================
  831. */
  832. void R_DeriveEntityData( idRenderEntityLocal *def );
  833. void R_CreateEntityRefs( idRenderEntityLocal *def );
  834. void R_FreeEntityDefDerivedData( idRenderEntityLocal *def, bool keepDecals, bool keepCachedDynamicModel );
  835. void R_FreeEntityDefCachedDynamicModel( idRenderEntityLocal *def );
  836. void R_FreeEntityDefDecals( idRenderEntityLocal *def );
  837. void R_FreeEntityDefOverlay( idRenderEntityLocal *def );
  838. void R_FreeEntityDefFadedDecals( idRenderEntityLocal *def, int time );
  839. void R_CreateLightRefs( idRenderLightLocal *light );
  840. void R_FreeLightDefDerivedData( idRenderLightLocal *light );
  841. void R_FreeDerivedData();
  842. void R_ReCreateWorldReferences();
  843. void R_CheckForEntityDefsUsingModel( idRenderModel *model );
  844. void R_ModulateLights_f( const idCmdArgs &args );
  845. /*
  846. ============================================================
  847. RENDERWORLD_PORTALS
  848. ============================================================
  849. */
  850. viewEntity_t *R_SetEntityDefViewEntity( idRenderEntityLocal *def );
  851. viewLight_t *R_SetLightDefViewLight( idRenderLightLocal *def );
  852. /*
  853. ====================================================================
  854. TR_FRONTEND_MAIN
  855. ====================================================================
  856. */
  857. void R_InitFrameData();
  858. void R_ShutdownFrameData();
  859. void R_ToggleSmpFrame();
  860. void *R_FrameAlloc( int bytes, frameAllocType_t type = FRAME_ALLOC_UNKNOWN );
  861. void *R_ClearedFrameAlloc( int bytes, frameAllocType_t type = FRAME_ALLOC_UNKNOWN );
  862. void *R_StaticAlloc( int bytes, const memTag_t tag = TAG_RENDER_STATIC ); // just malloc with error checking
  863. void *R_ClearedStaticAlloc( int bytes ); // with memset
  864. void R_StaticFree( void *data );
  865. void R_RenderView( viewDef_t *parms );
  866. void R_RenderPostProcess( viewDef_t *parms );
  867. /*
  868. ============================================================
  869. TR_FRONTEND_ADDLIGHTS
  870. ============================================================
  871. */
  872. void R_ShadowBounds( const idBounds & modelBounds, const idBounds & lightBounds, const idVec3 & lightOrigin, idBounds & shadowBounds );
  873. ID_INLINE bool R_CullModelBoundsToLight( const idRenderLightLocal * light, const idBounds & localBounds, const idRenderMatrix & modelRenderMatrix ) {
  874. idRenderMatrix modelLightProject;
  875. idRenderMatrix::Multiply( light->baseLightProject, modelRenderMatrix, modelLightProject );
  876. return idRenderMatrix::CullBoundsToMVP( modelLightProject, localBounds, true );
  877. }
  878. void R_AddLights();
  879. void R_OptimizeViewLightsList();
  880. /*
  881. ============================================================
  882. TR_FRONTEND_ADDMODELS
  883. ============================================================
  884. */
  885. bool R_IssueEntityDefCallback( idRenderEntityLocal *def );
  886. idRenderModel *R_EntityDefDynamicModel( idRenderEntityLocal *def );
  887. void R_ClearEntityDefDynamicModel( idRenderEntityLocal *def );
  888. void R_SetupDrawSurfShader( drawSurf_t * drawSurf, const idMaterial * shader, const renderEntity_t * renderEntity );
  889. void R_SetupDrawSurfJoints( drawSurf_t * drawSurf, const srfTriangles_t * tri, const idMaterial * shader );
  890. void R_LinkDrawSurfToView( drawSurf_t * drawSurf, viewDef_t * viewDef );
  891. void R_AddModels();
  892. /*
  893. =============================================================
  894. TR_FRONTEND_DEFORM
  895. =============================================================
  896. */
  897. drawSurf_t * R_DeformDrawSurf( drawSurf_t * drawSurf );
  898. /*
  899. =============================================================
  900. TR_FRONTEND_GUISURF
  901. =============================================================
  902. */
  903. void R_SurfaceToTextureAxis( const srfTriangles_t *tri, idVec3 &origin, idVec3 axis[3] );
  904. void R_AddInGameGuis( const drawSurf_t * const drawSurfs[], const int numDrawSurfs );
  905. /*
  906. ============================================================
  907. TR_FRONTEND_SUBVIEW
  908. ============================================================
  909. */
  910. bool R_PreciseCullSurface( const drawSurf_t *drawSurf, idBounds &ndcBounds );
  911. bool R_GenerateSubViews( const drawSurf_t * const drawSurfs[], const int numDrawSurfs );
  912. /*
  913. ============================================================
  914. TR_TRISURF
  915. ============================================================
  916. */
  917. srfTriangles_t * R_AllocStaticTriSurf();
  918. void R_AllocStaticTriSurfVerts( srfTriangles_t *tri, int numVerts );
  919. void R_AllocStaticTriSurfIndexes( srfTriangles_t *tri, int numIndexes );
  920. void R_AllocStaticTriSurfPreLightShadowVerts( srfTriangles_t *tri, int numVerts );
  921. void R_AllocStaticTriSurfSilIndexes( srfTriangles_t *tri, int numIndexes );
  922. void R_AllocStaticTriSurfDominantTris( srfTriangles_t *tri, int numVerts );
  923. void R_AllocStaticTriSurfSilEdges( srfTriangles_t *tri, int numSilEdges );
  924. void R_AllocStaticTriSurfMirroredVerts( srfTriangles_t *tri, int numMirroredVerts );
  925. void R_AllocStaticTriSurfDupVerts( srfTriangles_t *tri, int numDupVerts );
  926. srfTriangles_t * R_CopyStaticTriSurf( const srfTriangles_t *tri );
  927. void R_ResizeStaticTriSurfVerts( srfTriangles_t *tri, int numVerts );
  928. void R_ResizeStaticTriSurfIndexes( srfTriangles_t *tri, int numIndexes );
  929. void R_ReferenceStaticTriSurfVerts( srfTriangles_t *tri, const srfTriangles_t *reference );
  930. void R_ReferenceStaticTriSurfIndexes( srfTriangles_t *tri, const srfTriangles_t *reference );
  931. void R_FreeStaticTriSurfSilIndexes( srfTriangles_t *tri );
  932. void R_FreeStaticTriSurf( srfTriangles_t *tri );
  933. void R_FreeStaticTriSurfVerts( srfTriangles_t *tri );
  934. void R_FreeStaticTriSurfVertexCaches( srfTriangles_t *tri );
  935. int R_TriSurfMemory( const srfTriangles_t *tri );
  936. void R_BoundTriSurf( srfTriangles_t *tri );
  937. void R_RemoveDuplicatedTriangles( srfTriangles_t *tri );
  938. void R_CreateSilIndexes( srfTriangles_t *tri );
  939. void R_RemoveDegenerateTriangles( srfTriangles_t *tri );
  940. void R_RemoveUnusedVerts( srfTriangles_t *tri );
  941. void R_RangeCheckIndexes( const srfTriangles_t *tri );
  942. void R_CreateVertexNormals( srfTriangles_t *tri ); // also called by dmap
  943. void R_CleanupTriangles( srfTriangles_t *tri, bool createNormals, bool identifySilEdges, bool useUnsmoothedTangents );
  944. void R_ReverseTriangles( srfTriangles_t *tri );
  945. // Only deals with vertexes and indexes, not silhouettes, planes, etc.
  946. // Does NOT perform a cleanup triangles, so there may be duplicated verts in the result.
  947. srfTriangles_t * R_MergeSurfaceList( const srfTriangles_t **surfaces, int numSurfaces );
  948. srfTriangles_t * R_MergeTriangles( const srfTriangles_t *tri1, const srfTriangles_t *tri2 );
  949. // if the deformed verts have significant enough texture coordinate changes to reverse the texture
  950. // polarity of a triangle, the tangents will be incorrect
  951. void R_DeriveTangents( srfTriangles_t *tri );
  952. // copy data from a front-end srfTriangles_t to a back-end drawSurf_t
  953. void R_InitDrawSurfFromTri( drawSurf_t & ds, srfTriangles_t & tri );
  954. // For static surfaces, the indexes, ambient, and shadow buffers can be pre-created at load
  955. // time, rather than being re-created each frame in the frame temporary buffers.
  956. void R_CreateStaticBuffersForTri( srfTriangles_t & tri );
  957. // deformable meshes precalculate as much as possible from a base frame, then generate
  958. // complete srfTriangles_t from just a new set of vertexes
  959. struct deformInfo_t {
  960. int numSourceVerts;
  961. // numOutputVerts may be smaller if the input had duplicated or degenerate triangles
  962. // it will often be larger if the input had mirrored texture seams that needed
  963. // to be busted for proper tangent spaces
  964. int numOutputVerts;
  965. idDrawVert * verts;
  966. int numIndexes;
  967. triIndex_t * indexes;
  968. triIndex_t * silIndexes; // indexes changed to be the first vertex with same XYZ, ignoring normal and texcoords
  969. int numMirroredVerts; // this many verts at the end of the vert list are tangent mirrors
  970. int * mirroredVerts; // tri->mirroredVerts[0] is the mirror of tri->numVerts - tri->numMirroredVerts + 0
  971. int numDupVerts; // number of duplicate vertexes
  972. int * dupVerts; // pairs of the number of the first vertex and the number of the duplicate vertex
  973. int numSilEdges; // number of silhouette edges
  974. silEdge_t * silEdges; // silhouette edges
  975. vertCacheHandle_t staticIndexCache; // GL_INDEX_TYPE
  976. vertCacheHandle_t staticAmbientCache; // idDrawVert
  977. vertCacheHandle_t staticShadowCache; // idShadowCacheSkinned
  978. };
  979. // if outputVertexes is not NULL, it will point to a newly allocated set of verts that includes the mirrored ones
  980. deformInfo_t * R_BuildDeformInfo( int numVerts, const idDrawVert *verts, int numIndexes, const int *indexes,
  981. bool useUnsmoothedTangents );
  982. void R_FreeDeformInfo( deformInfo_t *deformInfo );
  983. int R_DeformInfoMemoryUsed( deformInfo_t *deformInfo );
  984. /*
  985. =============================================================
  986. TR_TRACE
  987. =============================================================
  988. */
  989. struct localTrace_t {
  990. float fraction;
  991. // only valid if fraction < 1.0
  992. idVec3 point;
  993. idVec3 normal;
  994. int indexes[3];
  995. };
  996. localTrace_t R_LocalTrace( const idVec3 &start, const idVec3 &end, const float radius, const srfTriangles_t *tri );
  997. void RB_ShowTrace( drawSurf_t **drawSurfs, int numDrawSurfs );
  998. /*
  999. =============================================================
  1000. BACKEND
  1001. =============================================================
  1002. */
  1003. void RB_ExecuteBackEndCommands( const emptyCommand_t *cmds );
  1004. /*
  1005. ============================================================
  1006. TR_BACKEND_DRAW
  1007. ============================================================
  1008. */
  1009. void RB_DrawElementsWithCounters( const drawSurf_t *surf );
  1010. void RB_DrawViewInternal( const viewDef_t * viewDef, const int stereoEye );
  1011. void RB_DrawView( const void *data, const int stereoEye );
  1012. void RB_CopyRender( const void *data );
  1013. void RB_PostProcess( const void *data );
  1014. /*
  1015. =============================================================
  1016. TR_BACKEND_RENDERTOOLS
  1017. =============================================================
  1018. */
  1019. float RB_DrawTextLength( const char *text, float scale, int len );
  1020. 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 );
  1021. void RB_ClearDebugText( int time );
  1022. void RB_AddDebugLine( const idVec4 &color, const idVec3 &start, const idVec3 &end, const int lifeTime, const bool depthTest );
  1023. void RB_ClearDebugLines( int time );
  1024. void RB_AddDebugPolygon( const idVec4 &color, const idWinding &winding, const int lifeTime, const bool depthTest );
  1025. void RB_ClearDebugPolygons( int time );
  1026. void RB_DrawBounds( const idBounds &bounds );
  1027. void RB_ShowLights( drawSurf_t **drawSurfs, int numDrawSurfs );
  1028. void RB_ShowLightCount( drawSurf_t **drawSurfs, int numDrawSurfs );
  1029. void RB_PolygonClear();
  1030. void RB_ScanStencilBuffer();
  1031. void RB_ShowDestinationAlpha();
  1032. void RB_ShowOverdraw();
  1033. void RB_RenderDebugTools( drawSurf_t **drawSurfs, int numDrawSurfs );
  1034. void RB_ShutdownDebugTools();
  1035. //=============================================
  1036. #include "ResolutionScale.h"
  1037. #include "RenderLog.h"
  1038. #include "AutoRender.h"
  1039. #include "AutoRenderBink.h"
  1040. #include "jobs/ShadowShared.h"
  1041. #include "jobs/prelightshadowvolume/PreLightShadowVolume.h"
  1042. #include "jobs/staticshadowvolume/StaticShadowVolume.h"
  1043. #include "jobs/dynamicshadowvolume/DynamicShadowVolume.h"
  1044. #include "GraphicsAPIWrapper.h"
  1045. #include "GLMatrix.h"
  1046. #include "BufferObject.h"
  1047. #include "RenderProgs.h"
  1048. #include "RenderWorld_local.h"
  1049. #include "GuiModel.h"
  1050. #include "VertexCache.h"
  1051. #endif /* !__TR_LOCAL_H__ */