Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6089 lines
180 KiB

  1. //===== Copyright � 1996-2005, Valve Corporation, All rights reserved. ======//
  2. //
  3. // Purpose:
  4. //
  5. // $Revision: $
  6. // $NoKeywords: $
  7. //===========================================================================//
  8. #include "cmdlib.h"
  9. #include "tier3/tier3.h"
  10. #include "mathlib/mathlib.h"
  11. #include "bsplib.h"
  12. #include "zip_utils.h"
  13. #include "scriplib.h"
  14. #include "utllinkedlist.h"
  15. #include "bsptreedata.h"
  16. #include "cmodel.h"
  17. #include "gamebspfile.h"
  18. #include "materialsystem/imaterial.h"
  19. #include "materialsystem/hardwareverts.h"
  20. #include "utlbuffer.h"
  21. #include "utlrbtree.h"
  22. #include "utlsymbol.h"
  23. #include "utlstring.h"
  24. #include "checksum_crc.h"
  25. #include "physdll.h"
  26. #include "tier0/dbg.h"
  27. #include "lumpfiles.h"
  28. #include "vtf/vtf.h"
  29. #include "collisionutils.h"
  30. #include "tier1/tier1.h"
  31. #include "vphysics2_interface.h"
  32. #include "vphysics2_interface_flags.h"
  33. #include "../common/datalinker.h"
  34. #include "fmtstr.h"
  35. #include "studio.h"
  36. //=============================================================================
  37. // Boundary each lump should be aligned to
  38. // DO NOT CHANGE THIS! THIS IS FOR CLARITY! LUMP CENTRIC ALIGNMENT OCCURS PER LUMP
  39. #define LUMP_ALIGNMENT 4
  40. // PhysLevels require SIMD alignment
  41. #define LUMP_PHYSLEVEL_ALIGNMENT 16
  42. // Data descriptions for byte swapping - only needed
  43. // for structures that are written to file for use by the game.
  44. BEGIN_BYTESWAP_DATADESC( BSPHeader_t )
  45. DEFINE_FIELD( ident, FIELD_INTEGER ),
  46. DEFINE_FIELD( m_nVersion, FIELD_INTEGER ),
  47. DEFINE_EMBEDDED_ARRAY( lumps, HEADER_LUMPS ),
  48. DEFINE_FIELD( mapRevision, FIELD_INTEGER ),
  49. END_BYTESWAP_DATADESC()
  50. BEGIN_BYTESWAP_DATADESC( lump_t )
  51. DEFINE_FIELD( fileofs, FIELD_INTEGER ),
  52. DEFINE_FIELD( filelen, FIELD_INTEGER ),
  53. DEFINE_FIELD( version, FIELD_INTEGER ),
  54. DEFINE_ARRAY( fourCC, FIELD_CHARACTER, 4 ),
  55. END_BYTESWAP_DATADESC()
  56. BEGIN_BYTESWAP_DATADESC( dflagslump_t )
  57. DEFINE_FIELD( m_LevelFlags, FIELD_INTEGER ),
  58. END_BYTESWAP_DATADESC()
  59. BEGIN_BYTESWAP_DATADESC( dplane_t )
  60. DEFINE_FIELD( normal, FIELD_VECTOR ),
  61. DEFINE_FIELD( dist, FIELD_FLOAT ),
  62. DEFINE_FIELD( type, FIELD_INTEGER ),
  63. END_BYTESWAP_DATADESC()
  64. BEGIN_BYTESWAP_DATADESC( dleaf_version_0_t )
  65. DEFINE_FIELD( contents, FIELD_INTEGER ),
  66. DEFINE_FIELD( cluster, FIELD_SHORT ),
  67. DEFINE_BITFIELD( bf, FIELD_SHORT, 16 ),
  68. DEFINE_ARRAY( mins, FIELD_SHORT, 3 ),
  69. DEFINE_ARRAY( maxs, FIELD_SHORT, 3 ),
  70. DEFINE_FIELD( firstleafface, FIELD_SHORT ),
  71. DEFINE_FIELD( numleaffaces, FIELD_SHORT ),
  72. DEFINE_FIELD( firstleafbrush, FIELD_SHORT ),
  73. DEFINE_FIELD( numleafbrushes, FIELD_SHORT ),
  74. DEFINE_FIELD( leafWaterDataID, FIELD_SHORT ),
  75. DEFINE_EMBEDDED( m_AmbientLighting ),
  76. END_BYTESWAP_DATADESC()
  77. BEGIN_BYTESWAP_DATADESC( dleaf_t )
  78. DEFINE_FIELD( contents, FIELD_INTEGER ),
  79. DEFINE_FIELD( cluster, FIELD_SHORT ),
  80. DEFINE_BITFIELD( bf, FIELD_SHORT, 16 ),
  81. DEFINE_ARRAY( mins, FIELD_SHORT, 3 ),
  82. DEFINE_ARRAY( maxs, FIELD_SHORT, 3 ),
  83. DEFINE_FIELD( firstleafface, FIELD_SHORT ),
  84. DEFINE_FIELD( numleaffaces, FIELD_SHORT ),
  85. DEFINE_FIELD( firstleafbrush, FIELD_SHORT ),
  86. DEFINE_FIELD( numleafbrushes, FIELD_SHORT ),
  87. DEFINE_FIELD( leafWaterDataID, FIELD_SHORT ),
  88. END_BYTESWAP_DATADESC()
  89. BEGIN_BYTESWAP_DATADESC( CompressedLightCube ) // array of 6 ColorRGBExp32 (3 bytes and 1 char)
  90. DEFINE_ARRAY( m_Color, FIELD_CHARACTER, 6 * sizeof(ColorRGBExp32) ),
  91. END_BYTESWAP_DATADESC()
  92. BEGIN_BYTESWAP_DATADESC( dleafambientindex_t )
  93. DEFINE_FIELD( ambientSampleCount, FIELD_SHORT ),
  94. DEFINE_FIELD( firstAmbientSample, FIELD_SHORT ),
  95. END_BYTESWAP_DATADESC()
  96. BEGIN_BYTESWAP_DATADESC( dleafambientlighting_t ) // array of 6 ColorRGBExp32 (3 bytes and 1 char)
  97. DEFINE_EMBEDDED( cube ),
  98. DEFINE_FIELD( x, FIELD_CHARACTER ),
  99. DEFINE_FIELD( y, FIELD_CHARACTER ),
  100. DEFINE_FIELD( z, FIELD_CHARACTER ),
  101. DEFINE_FIELD( pad, FIELD_CHARACTER ),
  102. END_BYTESWAP_DATADESC()
  103. BEGIN_BYTESWAP_DATADESC( dvertex_t )
  104. DEFINE_FIELD( point, FIELD_VECTOR ),
  105. END_BYTESWAP_DATADESC()
  106. BEGIN_BYTESWAP_DATADESC( dnode_t )
  107. DEFINE_FIELD( planenum, FIELD_INTEGER ),
  108. DEFINE_ARRAY( children, FIELD_INTEGER, 2 ),
  109. DEFINE_ARRAY( mins, FIELD_SHORT, 3 ),
  110. DEFINE_ARRAY( maxs, FIELD_SHORT, 3 ),
  111. DEFINE_FIELD( firstface, FIELD_SHORT ),
  112. DEFINE_FIELD( numfaces, FIELD_SHORT ),
  113. DEFINE_FIELD( area, FIELD_SHORT ),
  114. END_BYTESWAP_DATADESC()
  115. BEGIN_BYTESWAP_DATADESC( texinfo_t )
  116. DEFINE_ARRAY( textureVecsTexelsPerWorldUnits, FIELD_FLOAT, 2 * 4 ),
  117. DEFINE_ARRAY( lightmapVecsLuxelsPerWorldUnits, FIELD_FLOAT, 2 * 4 ),
  118. DEFINE_FIELD( flags, FIELD_INTEGER ),
  119. DEFINE_FIELD( texdata, FIELD_INTEGER ),
  120. END_BYTESWAP_DATADESC()
  121. BEGIN_BYTESWAP_DATADESC( dtexdata_t )
  122. DEFINE_FIELD( reflectivity, FIELD_VECTOR ),
  123. DEFINE_FIELD( nameStringTableID, FIELD_INTEGER ),
  124. DEFINE_FIELD( width, FIELD_INTEGER ),
  125. DEFINE_FIELD( height, FIELD_INTEGER ),
  126. DEFINE_FIELD( view_width, FIELD_INTEGER ),
  127. DEFINE_FIELD( view_height, FIELD_INTEGER ),
  128. END_BYTESWAP_DATADESC()
  129. BEGIN_BYTESWAP_DATADESC( ddispinfo_t )
  130. DEFINE_FIELD( startPosition, FIELD_VECTOR ),
  131. DEFINE_FIELD( m_iDispVertStart, FIELD_INTEGER ),
  132. DEFINE_FIELD( m_iDispTriStart, FIELD_INTEGER ),
  133. DEFINE_FIELD( power, FIELD_INTEGER ),
  134. DEFINE_FIELD( minTess, FIELD_INTEGER ),
  135. DEFINE_FIELD( smoothingAngle, FIELD_FLOAT ),
  136. DEFINE_FIELD( contents, FIELD_INTEGER ),
  137. DEFINE_FIELD( m_iMapFace, FIELD_SHORT ),
  138. DEFINE_FIELD( m_iLightmapAlphaStart, FIELD_INTEGER ),
  139. DEFINE_FIELD( m_iLightmapSamplePositionStart, FIELD_INTEGER ),
  140. DEFINE_EMBEDDED_ARRAY( m_EdgeNeighbors, 4 ),
  141. DEFINE_EMBEDDED_ARRAY( m_CornerNeighbors, 4 ),
  142. DEFINE_ARRAY( m_AllowedVerts, FIELD_INTEGER, ddispinfo_t::ALLOWEDVERTS_SIZE ), // unsigned long
  143. END_BYTESWAP_DATADESC()
  144. BEGIN_BYTESWAP_DATADESC( CDispNeighbor )
  145. DEFINE_EMBEDDED_ARRAY( m_SubNeighbors, 2 ),
  146. END_BYTESWAP_DATADESC()
  147. BEGIN_BYTESWAP_DATADESC( CDispCornerNeighbors )
  148. DEFINE_ARRAY( m_Neighbors, FIELD_SHORT, MAX_DISP_CORNER_NEIGHBORS ),
  149. DEFINE_FIELD( m_nNeighbors, FIELD_CHARACTER ),
  150. END_BYTESWAP_DATADESC()
  151. BEGIN_BYTESWAP_DATADESC( CDispSubNeighbor )
  152. DEFINE_FIELD( m_iNeighbor, FIELD_SHORT ),
  153. DEFINE_FIELD( m_NeighborOrientation, FIELD_CHARACTER ),
  154. DEFINE_FIELD( m_Span, FIELD_CHARACTER ),
  155. DEFINE_FIELD( m_NeighborSpan, FIELD_CHARACTER ),
  156. END_BYTESWAP_DATADESC()
  157. BEGIN_BYTESWAP_DATADESC( CDispVert )
  158. DEFINE_FIELD( m_vVector, FIELD_VECTOR ),
  159. DEFINE_FIELD( m_flDist, FIELD_FLOAT ),
  160. DEFINE_FIELD( m_flAlpha, FIELD_FLOAT ),
  161. END_BYTESWAP_DATADESC()
  162. BEGIN_BYTESWAP_DATADESC( CDispTri )
  163. DEFINE_FIELD( m_uiTags, FIELD_SHORT ),
  164. END_BYTESWAP_DATADESC()
  165. BEGIN_BYTESWAP_DATADESC( CDispMultiBlend )
  166. DEFINE_FIELD( m_vMultiBlend, FIELD_VECTOR4D ),
  167. DEFINE_FIELD( m_vAlphaBlend, FIELD_VECTOR4D ),
  168. END_BYTESWAP_DATADESC()
  169. BEGIN_BYTESWAP_DATADESC( CFaceMacroTextureInfo )
  170. DEFINE_FIELD( m_MacroTextureNameID, FIELD_SHORT ),
  171. END_BYTESWAP_DATADESC()
  172. BEGIN_BYTESWAP_DATADESC( dprimitive_t )
  173. DEFINE_FIELD( type, FIELD_CHARACTER ),
  174. DEFINE_FIELD( firstIndex, FIELD_SHORT ),
  175. DEFINE_FIELD( indexCount, FIELD_SHORT ),
  176. DEFINE_FIELD( firstVert, FIELD_SHORT ),
  177. DEFINE_FIELD( vertCount, FIELD_SHORT ),
  178. END_BYTESWAP_DATADESC()
  179. BEGIN_BYTESWAP_DATADESC( dprimvert_t )
  180. DEFINE_FIELD( pos, FIELD_VECTOR ),
  181. END_BYTESWAP_DATADESC()
  182. BEGIN_BYTESWAP_DATADESC( dface_t )
  183. DEFINE_FIELD( planenum, FIELD_SHORT ),
  184. DEFINE_FIELD( side, FIELD_CHARACTER ),
  185. DEFINE_FIELD( onNode, FIELD_CHARACTER ),
  186. DEFINE_FIELD( firstedge, FIELD_INTEGER ),
  187. DEFINE_FIELD( numedges, FIELD_SHORT ),
  188. DEFINE_FIELD( texinfo, FIELD_SHORT ),
  189. DEFINE_FIELD( dispinfo, FIELD_SHORT ),
  190. DEFINE_FIELD( surfaceFogVolumeID, FIELD_SHORT ),
  191. DEFINE_ARRAY( styles, FIELD_CHARACTER, MAXLIGHTMAPS ),
  192. DEFINE_FIELD( lightofs, FIELD_INTEGER ),
  193. DEFINE_FIELD( area, FIELD_FLOAT ),
  194. DEFINE_ARRAY( m_LightmapTextureMinsInLuxels, FIELD_INTEGER, 2 ),
  195. DEFINE_ARRAY( m_LightmapTextureSizeInLuxels, FIELD_INTEGER, 2 ),
  196. DEFINE_FIELD( origFace, FIELD_INTEGER ),
  197. DEFINE_FIELD( m_NumPrims, FIELD_SHORT ),
  198. DEFINE_FIELD( firstPrimID, FIELD_SHORT ),
  199. DEFINE_FIELD( smoothingGroups, FIELD_INTEGER ),
  200. END_BYTESWAP_DATADESC()
  201. BEGIN_BYTESWAP_DATADESC( dfaceid_t )
  202. DEFINE_FIELD( hammerfaceid, FIELD_SHORT ),
  203. END_BYTESWAP_DATADESC()
  204. BEGIN_BYTESWAP_DATADESC( dfacebrushlist_t )
  205. DEFINE_FIELD( m_nFaceBrushCount, FIELD_SHORT ),
  206. DEFINE_FIELD( m_nFaceBrushStart, FIELD_SHORT ),
  207. END_BYTESWAP_DATADESC()
  208. BEGIN_BYTESWAP_DATADESC( dbrush_t )
  209. DEFINE_FIELD( firstside, FIELD_INTEGER ),
  210. DEFINE_FIELD( numsides, FIELD_INTEGER ),
  211. DEFINE_FIELD( contents, FIELD_INTEGER ),
  212. END_BYTESWAP_DATADESC()
  213. BEGIN_BYTESWAP_DATADESC( dbrushside_t )
  214. DEFINE_FIELD( planenum, FIELD_SHORT ),
  215. DEFINE_FIELD( texinfo, FIELD_SHORT ),
  216. DEFINE_FIELD( dispinfo, FIELD_SHORT ),
  217. DEFINE_FIELD( bevel, FIELD_CHARACTER ),
  218. DEFINE_FIELD( thin, FIELD_CHARACTER ),
  219. END_BYTESWAP_DATADESC()
  220. BEGIN_BYTESWAP_DATADESC( dedge_t )
  221. DEFINE_ARRAY( v, FIELD_SHORT, 2 ),
  222. END_BYTESWAP_DATADESC()
  223. BEGIN_BYTESWAP_DATADESC( dmodel_t )
  224. DEFINE_FIELD( mins, FIELD_VECTOR ),
  225. DEFINE_FIELD( maxs, FIELD_VECTOR ),
  226. DEFINE_FIELD( origin, FIELD_VECTOR ),
  227. DEFINE_FIELD( headnode, FIELD_INTEGER ),
  228. DEFINE_FIELD( firstface, FIELD_INTEGER ),
  229. DEFINE_FIELD( numfaces, FIELD_INTEGER ),
  230. END_BYTESWAP_DATADESC()
  231. BEGIN_BYTESWAP_DATADESC( dphysmodel_t )
  232. DEFINE_FIELD( modelIndex, FIELD_INTEGER ),
  233. DEFINE_FIELD( dataSize, FIELD_INTEGER ),
  234. DEFINE_FIELD( keydataSize, FIELD_INTEGER ),
  235. DEFINE_FIELD( solidCount, FIELD_INTEGER ),
  236. END_BYTESWAP_DATADESC()
  237. BEGIN_BYTESWAP_DATADESC( dphysdisp_t )
  238. DEFINE_FIELD( numDisplacements, FIELD_SHORT ),
  239. END_BYTESWAP_DATADESC()
  240. BEGIN_BYTESWAP_DATADESC( darea_t )
  241. DEFINE_FIELD( numareaportals, FIELD_INTEGER ),
  242. DEFINE_FIELD( firstareaportal, FIELD_INTEGER ),
  243. END_BYTESWAP_DATADESC()
  244. BEGIN_BYTESWAP_DATADESC( dareaportal_t )
  245. DEFINE_FIELD( m_PortalKey, FIELD_SHORT ),
  246. DEFINE_FIELD( otherarea, FIELD_SHORT ),
  247. DEFINE_FIELD( m_FirstClipPortalVert, FIELD_SHORT ),
  248. DEFINE_FIELD( m_nClipPortalVerts, FIELD_SHORT ),
  249. DEFINE_FIELD( planenum, FIELD_INTEGER ),
  250. END_BYTESWAP_DATADESC()
  251. BEGIN_BYTESWAP_DATADESC( dworldlight_version0_t )
  252. DEFINE_FIELD( origin, FIELD_VECTOR ),
  253. DEFINE_FIELD( intensity, FIELD_VECTOR ),
  254. DEFINE_FIELD( normal, FIELD_VECTOR ),
  255. DEFINE_FIELD( cluster, FIELD_INTEGER ),
  256. DEFINE_FIELD( type, FIELD_INTEGER ), // enumeration
  257. DEFINE_FIELD( style, FIELD_INTEGER ),
  258. DEFINE_FIELD( stopdot, FIELD_FLOAT ),
  259. DEFINE_FIELD( stopdot2, FIELD_FLOAT ),
  260. DEFINE_FIELD( exponent, FIELD_FLOAT ),
  261. DEFINE_FIELD( radius, FIELD_FLOAT ),
  262. DEFINE_FIELD( constant_attn, FIELD_FLOAT ),
  263. DEFINE_FIELD( linear_attn, FIELD_FLOAT ),
  264. DEFINE_FIELD( quadratic_attn, FIELD_FLOAT ),
  265. DEFINE_FIELD( flags, FIELD_INTEGER ),
  266. DEFINE_FIELD( texinfo, FIELD_INTEGER ),
  267. DEFINE_FIELD( owner, FIELD_INTEGER ),
  268. END_BYTESWAP_DATADESC()
  269. BEGIN_BYTESWAP_DATADESC( dworldlight_t )
  270. DEFINE_FIELD( origin, FIELD_VECTOR ),
  271. DEFINE_FIELD( intensity, FIELD_VECTOR ),
  272. DEFINE_FIELD( normal, FIELD_VECTOR ),
  273. DEFINE_FIELD( shadow_cast_offset, FIELD_VECTOR ),
  274. DEFINE_FIELD( cluster, FIELD_INTEGER ),
  275. DEFINE_FIELD( type, FIELD_INTEGER ), // enumeration
  276. DEFINE_FIELD( style, FIELD_INTEGER ),
  277. DEFINE_FIELD( stopdot, FIELD_FLOAT ),
  278. DEFINE_FIELD( stopdot2, FIELD_FLOAT ),
  279. DEFINE_FIELD( exponent, FIELD_FLOAT ),
  280. DEFINE_FIELD( radius, FIELD_FLOAT ),
  281. DEFINE_FIELD( constant_attn, FIELD_FLOAT ),
  282. DEFINE_FIELD( linear_attn, FIELD_FLOAT ),
  283. DEFINE_FIELD( quadratic_attn, FIELD_FLOAT ),
  284. DEFINE_FIELD( flags, FIELD_INTEGER ),
  285. DEFINE_FIELD( texinfo, FIELD_INTEGER ),
  286. DEFINE_FIELD( owner, FIELD_INTEGER ),
  287. END_BYTESWAP_DATADESC()
  288. BEGIN_BYTESWAP_DATADESC( dleafwaterdata_t )
  289. DEFINE_FIELD( surfaceZ, FIELD_FLOAT ),
  290. DEFINE_FIELD( minZ, FIELD_FLOAT ),
  291. DEFINE_FIELD( surfaceTexInfoID, FIELD_SHORT ),
  292. END_BYTESWAP_DATADESC()
  293. BEGIN_BYTESWAP_DATADESC( doccluderdata_t )
  294. DEFINE_FIELD( flags, FIELD_INTEGER ),
  295. DEFINE_FIELD( firstpoly, FIELD_INTEGER ),
  296. DEFINE_FIELD( polycount, FIELD_INTEGER ),
  297. DEFINE_FIELD( mins, FIELD_VECTOR ),
  298. DEFINE_FIELD( maxs, FIELD_VECTOR ),
  299. DEFINE_FIELD( area, FIELD_INTEGER ),
  300. END_BYTESWAP_DATADESC()
  301. BEGIN_BYTESWAP_DATADESC( doccluderpolydata_t )
  302. DEFINE_FIELD( firstvertexindex, FIELD_INTEGER ),
  303. DEFINE_FIELD( vertexcount, FIELD_INTEGER ),
  304. DEFINE_FIELD( planenum, FIELD_INTEGER ),
  305. END_BYTESWAP_DATADESC()
  306. BEGIN_BYTESWAP_DATADESC( dcubemapsample_t )
  307. DEFINE_ARRAY( origin, FIELD_INTEGER, 3 ),
  308. DEFINE_FIELD( size, FIELD_CHARACTER ),
  309. END_BYTESWAP_DATADESC()
  310. BEGIN_BYTESWAP_DATADESC( doverlay_t )
  311. DEFINE_FIELD( nId, FIELD_INTEGER ),
  312. DEFINE_FIELD( nTexInfo, FIELD_SHORT ),
  313. DEFINE_FIELD( m_nFaceCountAndRenderOrder, FIELD_SHORT ),
  314. DEFINE_ARRAY( aFaces, FIELD_INTEGER, OVERLAY_BSP_FACE_COUNT ),
  315. DEFINE_ARRAY( flU, FIELD_FLOAT, 2 ),
  316. DEFINE_ARRAY( flV, FIELD_FLOAT, 2 ),
  317. DEFINE_ARRAY( vecUVPoints, FIELD_VECTOR, 4 ),
  318. DEFINE_FIELD( vecOrigin, FIELD_VECTOR ),
  319. DEFINE_FIELD( vecBasisNormal, FIELD_VECTOR ),
  320. END_BYTESWAP_DATADESC()
  321. BEGIN_BYTESWAP_DATADESC( dwateroverlay_t )
  322. DEFINE_FIELD( nId, FIELD_INTEGER ),
  323. DEFINE_FIELD( nTexInfo, FIELD_SHORT ),
  324. DEFINE_FIELD( m_nFaceCountAndRenderOrder, FIELD_SHORT ),
  325. DEFINE_ARRAY( aFaces, FIELD_INTEGER, WATEROVERLAY_BSP_FACE_COUNT ),
  326. DEFINE_ARRAY( flU, FIELD_FLOAT, 2 ),
  327. DEFINE_ARRAY( flV, FIELD_FLOAT, 2 ),
  328. DEFINE_ARRAY( vecUVPoints, FIELD_VECTOR, 4 ),
  329. DEFINE_FIELD( vecOrigin, FIELD_VECTOR ),
  330. DEFINE_FIELD( vecBasisNormal, FIELD_VECTOR ),
  331. END_BYTESWAP_DATADESC()
  332. BEGIN_BYTESWAP_DATADESC( doverlayfade_t )
  333. DEFINE_FIELD( flFadeDistMinSq, FIELD_FLOAT ),
  334. DEFINE_FIELD( flFadeDistMaxSq, FIELD_FLOAT ),
  335. END_BYTESWAP_DATADESC()
  336. BEGIN_BYTESWAP_DATADESC( doverlaysystemlevel_t )
  337. DEFINE_FIELD( nMinCPULevel, FIELD_CHARACTER ),
  338. DEFINE_FIELD( nMaxCPULevel, FIELD_CHARACTER ),
  339. DEFINE_FIELD( nMinGPULevel, FIELD_CHARACTER ),
  340. DEFINE_FIELD( nMaxGPULevel, FIELD_CHARACTER ),
  341. END_BYTESWAP_DATADESC()
  342. BEGIN_BYTESWAP_DATADESC( dgamelumpheader_t )
  343. DEFINE_FIELD( lumpCount, FIELD_INTEGER ),
  344. END_BYTESWAP_DATADESC()
  345. BEGIN_BYTESWAP_DATADESC( dgamelump_t )
  346. DEFINE_FIELD( id, FIELD_INTEGER ), // GameLumpId_t
  347. DEFINE_FIELD( flags, FIELD_SHORT ),
  348. DEFINE_FIELD( version, FIELD_SHORT ),
  349. DEFINE_FIELD( fileofs, FIELD_INTEGER ),
  350. DEFINE_FIELD( filelen, FIELD_INTEGER ),
  351. END_BYTESWAP_DATADESC()
  352. // From gamebspfile.h
  353. BEGIN_BYTESWAP_DATADESC( StaticPropDictLump_t )
  354. DEFINE_ARRAY( m_Name, FIELD_CHARACTER, STATIC_PROP_NAME_LENGTH ),
  355. END_BYTESWAP_DATADESC()
  356. // version 10
  357. BEGIN_BYTESWAP_DATADESC( StaticPropLump_t )
  358. DEFINE_FIELD( m_Origin, FIELD_VECTOR ),
  359. DEFINE_FIELD( m_Angles, FIELD_VECTOR ), // QAngle
  360. DEFINE_FIELD( m_PropType, FIELD_SHORT ),
  361. DEFINE_FIELD( m_FirstLeaf, FIELD_SHORT ),
  362. DEFINE_FIELD( m_LeafCount, FIELD_SHORT ),
  363. DEFINE_FIELD( m_Solid, FIELD_CHARACTER ),
  364. DEFINE_FIELD( m_Flags, FIELD_CHARACTER ),
  365. DEFINE_FIELD( m_Skin, FIELD_INTEGER ),
  366. DEFINE_FIELD( m_FadeMinDist, FIELD_FLOAT ),
  367. DEFINE_FIELD( m_FadeMaxDist, FIELD_FLOAT ),
  368. DEFINE_FIELD( m_LightingOrigin, FIELD_VECTOR ),
  369. DEFINE_FIELD( m_flForcedFadeScale, FIELD_FLOAT ),
  370. DEFINE_FIELD( m_nMinCPULevel, FIELD_CHARACTER ),
  371. DEFINE_FIELD( m_nMinCPULevel, FIELD_CHARACTER ),
  372. DEFINE_FIELD( m_nMinGPULevel, FIELD_CHARACTER ),
  373. DEFINE_FIELD( m_nMinGPULevel, FIELD_CHARACTER ),
  374. DEFINE_FIELD( m_DiffuseModulation, FIELD_COLOR32 ),
  375. DEFINE_FIELD( m_bDisableX360, FIELD_BOOLEAN ),
  376. DEFINE_FIELD( m_FlagsEx, FIELD_INTEGER ),
  377. END_BYTESWAP_DATADESC()
  378. BEGIN_BYTESWAP_DATADESC( StaticPropLumpV4_t )
  379. DEFINE_FIELD( m_Origin, FIELD_VECTOR ),
  380. DEFINE_FIELD( m_Angles, FIELD_VECTOR ), // QAngle
  381. DEFINE_FIELD( m_PropType, FIELD_SHORT ),
  382. DEFINE_FIELD( m_FirstLeaf, FIELD_SHORT ),
  383. DEFINE_FIELD( m_LeafCount, FIELD_SHORT ),
  384. DEFINE_FIELD( m_Solid, FIELD_CHARACTER ),
  385. DEFINE_FIELD( m_Flags, FIELD_CHARACTER ),
  386. DEFINE_FIELD( m_Skin, FIELD_INTEGER ),
  387. DEFINE_FIELD( m_FadeMinDist, FIELD_FLOAT ),
  388. DEFINE_FIELD( m_FadeMaxDist, FIELD_FLOAT ),
  389. DEFINE_FIELD( m_LightingOrigin, FIELD_VECTOR ),
  390. END_BYTESWAP_DATADESC()
  391. BEGIN_BYTESWAP_DATADESC( StaticPropLumpV5_t )
  392. DEFINE_FIELD( m_Origin, FIELD_VECTOR ),
  393. DEFINE_FIELD( m_Angles, FIELD_VECTOR ), // QAngle
  394. DEFINE_FIELD( m_PropType, FIELD_SHORT ),
  395. DEFINE_FIELD( m_FirstLeaf, FIELD_SHORT ),
  396. DEFINE_FIELD( m_LeafCount, FIELD_SHORT ),
  397. DEFINE_FIELD( m_Solid, FIELD_CHARACTER ),
  398. DEFINE_FIELD( m_Flags, FIELD_CHARACTER ),
  399. DEFINE_FIELD( m_Skin, FIELD_INTEGER ),
  400. DEFINE_FIELD( m_FadeMinDist, FIELD_FLOAT ),
  401. DEFINE_FIELD( m_FadeMaxDist, FIELD_FLOAT ),
  402. DEFINE_FIELD( m_LightingOrigin, FIELD_VECTOR ),
  403. DEFINE_FIELD( m_flForcedFadeScale, FIELD_FLOAT ),
  404. END_BYTESWAP_DATADESC()
  405. BEGIN_BYTESWAP_DATADESC( StaticPropLumpV6_t )
  406. DEFINE_FIELD( m_Origin, FIELD_VECTOR ),
  407. DEFINE_FIELD( m_Angles, FIELD_VECTOR ), // QAngle
  408. DEFINE_FIELD( m_PropType, FIELD_SHORT ),
  409. DEFINE_FIELD( m_FirstLeaf, FIELD_SHORT ),
  410. DEFINE_FIELD( m_LeafCount, FIELD_SHORT ),
  411. DEFINE_FIELD( m_Solid, FIELD_CHARACTER ),
  412. DEFINE_FIELD( m_Flags, FIELD_CHARACTER ),
  413. DEFINE_FIELD( m_Skin, FIELD_INTEGER ),
  414. DEFINE_FIELD( m_FadeMinDist, FIELD_FLOAT ),
  415. DEFINE_FIELD( m_FadeMaxDist, FIELD_FLOAT ),
  416. DEFINE_FIELD( m_LightingOrigin, FIELD_VECTOR ),
  417. DEFINE_FIELD( m_flForcedFadeScale, FIELD_FLOAT ),
  418. DEFINE_FIELD( m_nMinDXLevel, FIELD_SHORT ),
  419. DEFINE_FIELD( m_nMaxDXLevel, FIELD_SHORT ),
  420. END_BYTESWAP_DATADESC()
  421. BEGIN_BYTESWAP_DATADESC( StaticPropLumpV7_t )
  422. DEFINE_FIELD( m_Origin, FIELD_VECTOR ),
  423. DEFINE_FIELD( m_Angles, FIELD_VECTOR ), // QAngle
  424. DEFINE_FIELD( m_PropType, FIELD_SHORT ),
  425. DEFINE_FIELD( m_FirstLeaf, FIELD_SHORT ),
  426. DEFINE_FIELD( m_LeafCount, FIELD_SHORT ),
  427. DEFINE_FIELD( m_Solid, FIELD_CHARACTER ),
  428. DEFINE_FIELD( m_Flags, FIELD_CHARACTER ),
  429. DEFINE_FIELD( m_Skin, FIELD_INTEGER ),
  430. DEFINE_FIELD( m_FadeMinDist, FIELD_FLOAT ),
  431. DEFINE_FIELD( m_FadeMaxDist, FIELD_FLOAT ),
  432. DEFINE_FIELD( m_LightingOrigin, FIELD_VECTOR ),
  433. DEFINE_FIELD( m_flForcedFadeScale, FIELD_FLOAT ),
  434. DEFINE_FIELD( m_nMinDXLevel, FIELD_SHORT ),
  435. DEFINE_FIELD( m_nMaxDXLevel, FIELD_SHORT ),
  436. DEFINE_FIELD( m_DiffuseModulation, FIELD_COLOR32 ),
  437. END_BYTESWAP_DATADESC()
  438. BEGIN_BYTESWAP_DATADESC( StaticPropLumpV8_t )
  439. DEFINE_FIELD( m_Origin, FIELD_VECTOR ),
  440. DEFINE_FIELD( m_Angles, FIELD_VECTOR ), // QAngle
  441. DEFINE_FIELD( m_PropType, FIELD_SHORT ),
  442. DEFINE_FIELD( m_FirstLeaf, FIELD_SHORT ),
  443. DEFINE_FIELD( m_LeafCount, FIELD_SHORT ),
  444. DEFINE_FIELD( m_Solid, FIELD_CHARACTER ),
  445. DEFINE_FIELD( m_Flags, FIELD_CHARACTER ),
  446. DEFINE_FIELD( m_Skin, FIELD_INTEGER ),
  447. DEFINE_FIELD( m_FadeMinDist, FIELD_FLOAT ),
  448. DEFINE_FIELD( m_FadeMaxDist, FIELD_FLOAT ),
  449. DEFINE_FIELD( m_LightingOrigin, FIELD_VECTOR ),
  450. DEFINE_FIELD( m_flForcedFadeScale, FIELD_FLOAT ),
  451. DEFINE_FIELD( m_nMinCPULevel, FIELD_CHARACTER ),
  452. DEFINE_FIELD( m_nMinCPULevel, FIELD_CHARACTER ),
  453. DEFINE_FIELD( m_nMinGPULevel, FIELD_CHARACTER ),
  454. DEFINE_FIELD( m_nMinGPULevel, FIELD_CHARACTER ),
  455. DEFINE_FIELD( m_DiffuseModulation, FIELD_COLOR32 ),
  456. END_BYTESWAP_DATADESC()
  457. BEGIN_BYTESWAP_DATADESC( StaticPropLumpV9_t )
  458. DEFINE_FIELD( m_Origin, FIELD_VECTOR ),
  459. DEFINE_FIELD( m_Angles, FIELD_VECTOR ), // QAngle
  460. DEFINE_FIELD( m_PropType, FIELD_SHORT ),
  461. DEFINE_FIELD( m_FirstLeaf, FIELD_SHORT ),
  462. DEFINE_FIELD( m_LeafCount, FIELD_SHORT ),
  463. DEFINE_FIELD( m_Solid, FIELD_CHARACTER ),
  464. DEFINE_FIELD( m_Flags, FIELD_CHARACTER ),
  465. DEFINE_FIELD( m_Skin, FIELD_INTEGER ),
  466. DEFINE_FIELD( m_FadeMinDist, FIELD_FLOAT ),
  467. DEFINE_FIELD( m_FadeMaxDist, FIELD_FLOAT ),
  468. DEFINE_FIELD( m_LightingOrigin, FIELD_VECTOR ),
  469. DEFINE_FIELD( m_flForcedFadeScale, FIELD_FLOAT ),
  470. DEFINE_FIELD( m_nMinCPULevel, FIELD_CHARACTER ),
  471. DEFINE_FIELD( m_nMinCPULevel, FIELD_CHARACTER ),
  472. DEFINE_FIELD( m_nMinGPULevel, FIELD_CHARACTER ),
  473. DEFINE_FIELD( m_nMinGPULevel, FIELD_CHARACTER ),
  474. DEFINE_FIELD( m_DiffuseModulation, FIELD_COLOR32 ),
  475. DEFINE_FIELD( m_bDisableX360, FIELD_BOOLEAN ),
  476. END_BYTESWAP_DATADESC()
  477. BEGIN_BYTESWAP_DATADESC( StaticPropLeafLump_t )
  478. DEFINE_FIELD( m_Leaf, FIELD_SHORT ),
  479. END_BYTESWAP_DATADESC()
  480. BEGIN_BYTESWAP_DATADESC( dprophull_t )
  481. DEFINE_FIELD( m_nVertCount, FIELD_INTEGER ),
  482. DEFINE_FIELD( m_nVertStart, FIELD_INTEGER ),
  483. DEFINE_FIELD( m_nSurfaceProp, FIELD_INTEGER ),
  484. DEFINE_FIELD( m_nContents, FIELD_INTEGER ),
  485. END_BYTESWAP_DATADESC()
  486. BEGIN_BYTESWAP_DATADESC( dprophulltris_t )
  487. DEFINE_FIELD( m_nIndexCount, FIELD_INTEGER ),
  488. DEFINE_FIELD( m_nIndexStart, FIELD_INTEGER ),
  489. END_BYTESWAP_DATADESC()
  490. BEGIN_BYTESWAP_DATADESC( dpropcollision_t )
  491. DEFINE_FIELD( m_nHullCount, FIELD_INTEGER ),
  492. DEFINE_FIELD( m_nHullStart, FIELD_INTEGER ),
  493. END_BYTESWAP_DATADESC()
  494. BEGIN_BYTESWAP_DATADESC( DetailObjectDictLump_t )
  495. DEFINE_ARRAY( m_Name, FIELD_CHARACTER, DETAIL_NAME_LENGTH ),
  496. END_BYTESWAP_DATADESC()
  497. BEGIN_BYTESWAP_DATADESC( DetailObjectLump_t )
  498. DEFINE_FIELD( m_Origin, FIELD_VECTOR ),
  499. DEFINE_FIELD( m_Angles, FIELD_VECTOR ), // QAngle
  500. DEFINE_FIELD( m_DetailModel, FIELD_SHORT ),
  501. DEFINE_FIELD( m_Leaf, FIELD_SHORT ),
  502. DEFINE_ARRAY( m_Lighting, FIELD_CHARACTER, 4 ), // ColorRGBExp32
  503. DEFINE_FIELD( m_LightStyles, FIELD_INTEGER ),
  504. DEFINE_FIELD( m_LightStyleCount, FIELD_CHARACTER ),
  505. DEFINE_FIELD( m_SwayAmount, FIELD_CHARACTER ),
  506. DEFINE_FIELD( m_ShapeAngle, FIELD_CHARACTER ),
  507. DEFINE_FIELD( m_ShapeSize, FIELD_CHARACTER ),
  508. DEFINE_FIELD( m_Orientation, FIELD_CHARACTER ),
  509. DEFINE_ARRAY( m_Padding2, FIELD_CHARACTER, 3 ),
  510. DEFINE_FIELD( m_Type, FIELD_CHARACTER ),
  511. DEFINE_ARRAY( m_Padding3, FIELD_CHARACTER, 3 ),
  512. DEFINE_FIELD( m_flScale, FIELD_FLOAT ),
  513. END_BYTESWAP_DATADESC()
  514. BEGIN_BYTESWAP_DATADESC( DetailSpriteDictLump_t )
  515. DEFINE_FIELD( m_UL, FIELD_VECTOR2D ),
  516. DEFINE_FIELD( m_LR, FIELD_VECTOR2D ),
  517. DEFINE_FIELD( m_TexUL, FIELD_VECTOR2D ),
  518. DEFINE_FIELD( m_TexLR, FIELD_VECTOR2D ),
  519. END_BYTESWAP_DATADESC()
  520. BEGIN_BYTESWAP_DATADESC( DetailPropLightstylesLump_t )
  521. DEFINE_ARRAY( m_Lighting, FIELD_CHARACTER, 4 ), // ColorRGBExp32
  522. DEFINE_FIELD( m_Style, FIELD_CHARACTER ),
  523. END_BYTESWAP_DATADESC()
  524. // From vradstaticprops.h
  525. namespace HardwareVerts
  526. {
  527. BEGIN_BYTESWAP_DATADESC( MeshHeader_t )
  528. DEFINE_FIELD( m_nLod, FIELD_INTEGER ),
  529. DEFINE_FIELD( m_nVertexes, FIELD_INTEGER ),
  530. DEFINE_FIELD( m_nOffset, FIELD_INTEGER ),
  531. DEFINE_ARRAY( m_nUnused, FIELD_INTEGER, 4 ),
  532. END_BYTESWAP_DATADESC()
  533. BEGIN_BYTESWAP_DATADESC( FileHeader_t )
  534. DEFINE_FIELD( m_nVersion, FIELD_INTEGER ),
  535. DEFINE_FIELD( m_nChecksum, FIELD_INTEGER ),
  536. DEFINE_FIELD( m_nVertexFlags, FIELD_INTEGER ),
  537. DEFINE_FIELD( m_nVertexSize, FIELD_INTEGER ),
  538. DEFINE_FIELD( m_nVertexes, FIELD_INTEGER ),
  539. DEFINE_FIELD( m_nMeshes, FIELD_INTEGER ),
  540. DEFINE_ARRAY( m_nUnused, FIELD_INTEGER, 4 ),
  541. END_BYTESWAP_DATADESC()
  542. } // end namespace
  543. BEGIN_BYTESWAP_DATADESC( dphyslevelV0_t )
  544. DEFINE_FIELD( toolVersion, FIELD_INTEGER ),
  545. DEFINE_FIELD( dataVersion, FIELD_INTEGER ),
  546. DEFINE_FIELD( sizeofDiskPhysics2LevelMesh, FIELD_INTEGER ),
  547. DEFINE_FIELD( buildTime, FIELD_INTEGER ),
  548. DEFINE_FIELD( levelMeshes.size, FIELD_INTEGER ),
  549. DEFINE_FIELD( levelMeshes.offset, FIELD_INTEGER ),
  550. DEFINE_FIELD( polysoup.offset, FIELD_INTEGER ),
  551. DEFINE_FIELD( mopp.offset, FIELD_INTEGER ),
  552. DEFINE_FIELD( displacementMesh.offset, FIELD_INTEGER ),
  553. DEFINE_FIELD( staticProps.offset, FIELD_INTEGER ),
  554. DEFINE_FIELD( levelWaterMeshes.size, FIELD_INTEGER ),
  555. DEFINE_FIELD( levelWaterMeshes.offset, FIELD_INTEGER ),
  556. DEFINE_FIELD( nReserved2[0], FIELD_INTEGER ),
  557. DEFINE_FIELD( nReserved2[1], FIELD_INTEGER ),
  558. END_BYTESWAP_DATADESC()
  559. BEGIN_BYTESWAP_DATADESC(DiskPhysics2Polytope_t)
  560. DEFINE_FIELD( offsetPolytope, FIELD_INTEGER ),
  561. DEFINE_FIELD( offsetInertia, FIELD_INTEGER )
  562. END_BYTESWAP_DATADESC()
  563. BEGIN_BYTESWAP_DATADESC(DiskPhysics2LevelMesh_t)
  564. DEFINE_FIELD( polymesh.offset, FIELD_INTEGER ),
  565. DEFINE_FIELD( flags, FIELD_INTEGER )
  566. END_BYTESWAP_DATADESC()
  567. static char *s_LumpNames[] = {
  568. "LUMP_ENTITIES", // 0
  569. "LUMP_PLANES", // 1
  570. "LUMP_TEXDATA", // 2
  571. "LUMP_VERTEXES", // 3
  572. "LUMP_VISIBILITY", // 4
  573. "LUMP_NODES", // 5
  574. "LUMP_TEXINFO", // 6
  575. "LUMP_FACES", // 7
  576. "LUMP_LIGHTING", // 8
  577. "LUMP_OCCLUSION", // 9
  578. "LUMP_LEAFS", // 10
  579. "LUMP_FACEIDS", // 11
  580. "LUMP_EDGES", // 12
  581. "LUMP_SURFEDGES", // 13
  582. "LUMP_MODELS", // 14
  583. "LUMP_WORLDLIGHTS", // 15
  584. "LUMP_LEAFFACES", // 16
  585. "LUMP_LEAFBRUSHES", // 17
  586. "LUMP_BRUSHES", // 18
  587. "LUMP_BRUSHSIDES", // 19
  588. "LUMP_AREAS", // 20
  589. "LUMP_AREAPORTALS", // 21
  590. "LUMP_FACEBRUSHES", // 22
  591. "LUMP_FACEBRUSHLIST", // 23
  592. "LUMP_UNUSED1", // 24
  593. "LUMP_UNUSED2", // 25
  594. "LUMP_DISPINFO", // 26
  595. "LUMP_ORIGINALFACES", // 27
  596. "LUMP_PHYSDISP", // 28
  597. "LUMP_PHYSCOLLIDE", // 29
  598. "LUMP_VERTNORMALS", // 30
  599. "LUMP_VERTNORMALINDICES", // 31
  600. "LUMP_DISP_LIGHTMAP_ALPHAS", // 32
  601. "LUMP_DISP_VERTS", // 33
  602. "LUMP_DISP_LIGHTMAP_SAMPLE_POSITIONS", // 34
  603. "LUMP_GAME_LUMP", // 35
  604. "LUMP_LEAFWATERDATA", // 36
  605. "LUMP_PRIMITIVES", // 37
  606. "LUMP_PRIMVERTS", // 38
  607. "LUMP_PRIMINDICES", // 39
  608. "LUMP_PAKFILE", // 40
  609. "LUMP_CLIPPORTALVERTS", // 41
  610. "LUMP_CUBEMAPS", // 42
  611. "LUMP_TEXDATA_STRING_DATA", // 43
  612. "LUMP_TEXDATA_STRING_TABLE", // 44
  613. "LUMP_OVERLAYS", // 45
  614. "LUMP_LEAFMINDISTTOWATER", // 46
  615. "LUMP_FACE_MACRO_TEXTURE_INFO", // 47
  616. "LUMP_DISP_TRIS", // 48
  617. "LUMP_PROP_BLOB", // 49
  618. "LUMP_WATEROVERLAYS", // 50
  619. "LUMP_LEAF_AMBIENT_INDEX_HDR", // 51
  620. "LUMP_LEAF_AMBIENT_INDEX", // 52
  621. "LUMP_LIGHTING_HDR", // 53
  622. "LUMP_WORLDLIGHTS_HDR", // 54
  623. "LUMP_LEAF_AMBIENT_LIGHTING_HDR", // 55
  624. "LUMP_LEAF_AMBIENT_LIGHTING", // 56
  625. "LUMP_XZIPPAKFILE", // 57
  626. "LUMP_FACES_HDR", // 58
  627. "LUMP_MAP_FLAGS", // 59
  628. "LUMP_OVERLAY_FADES", // 60
  629. "LUMP_OVERLAY_SYSTEM_LEVELS", // 61
  630. "LUMP_PHYSLEVEL", // 62
  631. "LUMP_DISP_MULTIBLEND" // 63
  632. };
  633. const char *GetLumpName( unsigned int lumpnum )
  634. {
  635. if ( lumpnum >= ARRAYSIZE( s_LumpNames ) )
  636. {
  637. return "UNKNOWN";
  638. }
  639. return s_LumpNames[lumpnum];
  640. }
  641. // "-hdr" tells us to use the HDR fields (if present) on the light sources. Also, tells us to write
  642. // out the HDR lumps for lightmaps, ambient leaves, and lights sources.
  643. bool g_bHDR = false;
  644. // Set to true to generate Xbox360 native output files
  645. static bool g_bSwapOnLoad = false;
  646. static bool g_bSwapOnWrite = false;
  647. VTFConvertFunc_t g_pVTFConvertFunc;
  648. VHVFixupFunc_t g_pVHVFixupFunc;
  649. CompressFunc_t g_pCompressFunc;
  650. StudioConvertFunc_t g_pStudioConvertFunc;
  651. CUtlVector< CUtlString > g_StaticPropNames;
  652. CUtlVector< int > g_StaticPropInstances;
  653. CByteswap g_Swap;
  654. uint32 g_LevelFlags = 0;
  655. int nummodels;
  656. dmodel_t dmodels[MAX_MAP_MODELS];
  657. int visdatasize;
  658. byte dvisdata[MAX_MAP_VISIBILITY];
  659. dvis_t *dvis = (dvis_t *)dvisdata;
  660. CUtlVector<byte> dlightdataHDR;
  661. CUtlVector<byte> dlightdataLDR;
  662. CUtlVector<byte> *pdlightdata = &dlightdataLDR;
  663. CUtlVector<char> dentdata;
  664. int numleafs;
  665. #if !defined( BSP_USE_LESS_MEMORY )
  666. dleaf_t dleafs[MAX_MAP_LEAFS];
  667. #else
  668. dleaf_t *dleafs;
  669. #endif
  670. CUtlVector<dleafambientindex_t> g_LeafAmbientIndexLDR;
  671. CUtlVector<dleafambientindex_t> g_LeafAmbientIndexHDR;
  672. CUtlVector<dleafambientindex_t> *g_pLeafAmbientIndex = NULL;
  673. CUtlVector<dleafambientlighting_t> g_LeafAmbientLightingLDR;
  674. CUtlVector<dleafambientlighting_t> g_LeafAmbientLightingHDR;
  675. CUtlVector<dleafambientlighting_t> *g_pLeafAmbientLighting = NULL;
  676. unsigned short g_LeafMinDistToWater[MAX_MAP_LEAFS];
  677. int numplanes;
  678. dplane_t dplanes[MAX_MAP_PLANES];
  679. int numvertexes;
  680. dvertex_t dvertexes[MAX_MAP_VERTS];
  681. int g_numvertnormalindices; // dfaces reference these. These index g_vertnormals.
  682. unsigned short g_vertnormalindices[MAX_MAP_VERTNORMALS];
  683. int g_numvertnormals;
  684. Vector g_vertnormals[MAX_MAP_VERTNORMALS];
  685. int numnodes;
  686. dnode_t dnodes[MAX_MAP_NODES];
  687. CUtlVector<texinfo_t> texinfo( MAX_MAP_TEXINFO );
  688. int numtexdata;
  689. dtexdata_t dtexdata[MAX_MAP_TEXDATA];
  690. //
  691. // displacement map bsp file info: dispinfo
  692. //
  693. CUtlVector<ddispinfo_t> g_dispinfo;
  694. CUtlVector<CDispVert> g_DispVerts;
  695. CUtlVector<CDispTri> g_DispTris;
  696. CUtlVector<CDispMultiBlend> g_DispMultiBlend;
  697. CUtlVector<unsigned char> g_DispLightmapSamplePositions; // LUMP_DISP_LIGHTMAP_SAMPLE_POSITIONS
  698. int numorigfaces;
  699. dface_t dorigfaces[MAX_MAP_FACES];
  700. int g_numprimitives = 0;
  701. dprimitive_t g_primitives[MAX_MAP_PRIMITIVES];
  702. int g_numprimverts = 0;
  703. dprimvert_t g_primverts[MAX_MAP_PRIMVERTS];
  704. int g_numprimindices = 0;
  705. unsigned short g_primindices[MAX_MAP_PRIMINDICES];
  706. int numfaces;
  707. dface_t dfaces[MAX_MAP_FACES];
  708. int numfaceids;
  709. CUtlVector<dfaceid_t> dfaceids;
  710. CUtlVector<uint16> dfacebrushes;
  711. CUtlVector<dfacebrushlist_t> dfacebrushlists;
  712. int numfaces_hdr;
  713. dface_t dfaces_hdr[MAX_MAP_FACES];
  714. int numedges;
  715. dedge_t dedges[MAX_MAP_EDGES];
  716. int numleaffaces;
  717. unsigned short dleaffaces[MAX_MAP_LEAFFACES];
  718. int numleafbrushes;
  719. unsigned short dleafbrushes[MAX_MAP_LEAFBRUSHES];
  720. int numsurfedges;
  721. int dsurfedges[MAX_MAP_SURFEDGES];
  722. int numbrushes;
  723. dbrush_t dbrushes[MAX_MAP_BRUSHES];
  724. int numbrushsides;
  725. dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES];
  726. int numareas;
  727. darea_t dareas[MAX_MAP_AREAS];
  728. int numareaportals;
  729. dareaportal_t dareaportals[MAX_MAP_AREAPORTALS];
  730. int numworldlightsLDR;
  731. dworldlight_t dworldlightsLDR[MAX_MAP_WORLDLIGHTS];
  732. int numworldlightsHDR;
  733. dworldlight_t dworldlightsHDR[MAX_MAP_WORLDLIGHTS];
  734. int *pNumworldlights = &numworldlightsLDR;
  735. dworldlight_t *dworldlights = dworldlightsLDR;
  736. int numleafwaterdata = 0;
  737. dleafwaterdata_t dleafwaterdata[MAX_MAP_LEAFWATERDATA];
  738. CUtlVector<CFaceMacroTextureInfo> g_FaceMacroTextureInfos;
  739. Vector g_ClipPortalVerts[MAX_MAP_PORTALVERTS];
  740. int g_nClipPortalVerts;
  741. dcubemapsample_t g_CubemapSamples[MAX_MAP_CUBEMAPSAMPLES];
  742. int g_nCubemapSamples = 0;
  743. int g_nOverlayCount;
  744. doverlay_t g_Overlays[MAX_MAP_OVERLAYS];
  745. doverlayfade_t g_OverlayFades[MAX_MAP_OVERLAYS];
  746. doverlaysystemlevel_t g_OverlaySystemLevels[MAX_MAP_OVERLAYS];
  747. int g_nWaterOverlayCount;
  748. dwateroverlay_t g_WaterOverlays[MAX_MAP_WATEROVERLAYS];
  749. CUtlVector<char> g_TexDataStringData;
  750. CUtlVector<int> g_TexDataStringTable;
  751. byte *g_pPhysCollide = NULL;
  752. int g_PhysCollideSize = 0;
  753. int g_MapRevision = 0;
  754. byte *g_pPhysLevel = NULL;
  755. int g_PhysLevelSize = 0;
  756. byte *g_pPhysDisp = NULL;
  757. int g_PhysDispSize = 0;
  758. CUtlVector<doccluderdata_t> g_OccluderData( 256, 256 );
  759. CUtlVector<doccluderpolydata_t> g_OccluderPolyData( 1024, 1024 );
  760. CUtlVector<int> g_OccluderVertexIndices( 2048, 2048 );
  761. template <class T> static void WriteData( T *pData, int count = 1 );
  762. template <class T> static void WriteData( int fieldType, T *pData, int count = 1 );
  763. template< class T > static void AddLump( int lumpnum, T *pData, int count, int version = 0, int nAlignment = 1 );
  764. template< class T > static void AddLump( int lumpnum, CUtlVector<T> &data, int version = 0, int nAlignment = 1 );
  765. BSPHeader_t *g_pBSPHeader;
  766. FileHandle_t g_hBSPFile;
  767. struct Lumps_t
  768. {
  769. void *pLumps[HEADER_LUMPS];
  770. int size[HEADER_LUMPS];
  771. bool bLumpParsed[HEADER_LUMPS];
  772. bool bLumpFixed[HEADER_LUMPS];
  773. } g_Lumps;
  774. CGameLump g_GameLumps;
  775. static IZip *s_pakFile = 0;
  776. //-----------------------------------------------------------------------------
  777. // Keep the file position aligned to an arbitrary boundary.
  778. // Returns updated file position.
  779. //-----------------------------------------------------------------------------
  780. static unsigned int AlignFilePosition( FileHandle_t hFile, int alignment )
  781. {
  782. unsigned int currPosition = g_pFileSystem->Tell( hFile );
  783. if ( alignment >= 2 )
  784. {
  785. unsigned int newPosition = AlignValue( currPosition, alignment );
  786. unsigned int count = newPosition - currPosition;
  787. if ( count )
  788. {
  789. char *pBuffer;
  790. char smallBuffer[4096];
  791. if ( count > sizeof( smallBuffer ) )
  792. {
  793. pBuffer = (char *)malloc( count );
  794. }
  795. else
  796. {
  797. pBuffer = smallBuffer;
  798. }
  799. memset( pBuffer, 0, count );
  800. SafeWrite( hFile, pBuffer, count );
  801. if ( pBuffer != smallBuffer )
  802. {
  803. free( pBuffer );
  804. }
  805. currPosition = newPosition;
  806. }
  807. }
  808. return currPosition;
  809. }
  810. //-----------------------------------------------------------------------------
  811. // Purpose: // Get a pakfile instance
  812. // Output : IZip*
  813. //-----------------------------------------------------------------------------
  814. IZip* GetPakFile( void )
  815. {
  816. if ( !s_pakFile )
  817. {
  818. s_pakFile = IZip::CreateZip();
  819. }
  820. return s_pakFile;
  821. }
  822. //-----------------------------------------------------------------------------
  823. // Purpose: Free the pak files
  824. //-----------------------------------------------------------------------------
  825. void ReleasePakFileLumps( void )
  826. {
  827. // Release the pak files
  828. IZip::ReleaseZip( s_pakFile );
  829. s_pakFile = NULL;
  830. }
  831. //-----------------------------------------------------------------------------
  832. // Purpose: Set the sector alignment for all subsequent zip operations
  833. //-----------------------------------------------------------------------------
  834. void ForceAlignment( IZip *pak, bool bAlign, bool bCompatibleFormat, unsigned int alignmentSize )
  835. {
  836. pak->ForceAlignment( bAlign, bCompatibleFormat, alignmentSize );
  837. }
  838. //-----------------------------------------------------------------------------
  839. // Purpose: Store data back out to .bsp file
  840. //-----------------------------------------------------------------------------
  841. static void WritePakFileLump( void )
  842. {
  843. CUtlBuffer buf( 0, 0 );
  844. GetPakFile()->ActivateByteSwapping( IsX360() );
  845. GetPakFile()->SaveToBuffer( buf );
  846. // must respect pak file alignment
  847. // pad up and ensure lump starts on same aligned boundary
  848. AlignFilePosition( g_hBSPFile, GetPakFile()->GetAlignment() );
  849. // Now store final buffers out to file
  850. AddLump( LUMP_PAKFILE, (byte*)buf.Base(), buf.TellPut() );
  851. }
  852. //-----------------------------------------------------------------------------
  853. // Purpose: Remove all entries
  854. //-----------------------------------------------------------------------------
  855. void ClearPakFile( IZip *pak )
  856. {
  857. pak->Reset();
  858. }
  859. //-----------------------------------------------------------------------------
  860. // Purpose: Add file from disk to .bsp PAK lump
  861. // Input : *relativename -
  862. // *fullpath -
  863. //-----------------------------------------------------------------------------
  864. void AddFileToPak( IZip *pak, const char *relativename, const char *fullpath )
  865. {
  866. pak->AddFileToZip( relativename, fullpath );
  867. }
  868. //-----------------------------------------------------------------------------
  869. // Purpose: Add buffer to .bsp PAK lump as named file
  870. // Input : *relativename -
  871. // *data -
  872. // length -
  873. //-----------------------------------------------------------------------------
  874. void AddBufferToPak( IZip *pak, const char *pRelativeName, void *data, int length, bool bTextMode )
  875. {
  876. pak->AddBufferToZip( pRelativeName, data, length, bTextMode );
  877. }
  878. //-----------------------------------------------------------------------------
  879. // Purpose: Check if a file already exists in the pack file.
  880. // Input : *relativename -
  881. //-----------------------------------------------------------------------------
  882. bool FileExistsInPak( IZip *pak, const char *pRelativeName )
  883. {
  884. return pak->FileExistsInZip( pRelativeName );
  885. }
  886. //-----------------------------------------------------------------------------
  887. // Read a file from the pack file
  888. //-----------------------------------------------------------------------------
  889. bool ReadFileFromPak( IZip *pak, const char *pRelativeName, bool bTextMode, CUtlBuffer &buf )
  890. {
  891. return pak->ReadFileFromZip( pRelativeName, bTextMode, buf );
  892. }
  893. //-----------------------------------------------------------------------------
  894. // Purpose: Remove file from .bsp PAK lump
  895. // Input : *relativename -
  896. //-----------------------------------------------------------------------------
  897. void RemoveFileFromPak( IZip *pak, const char *relativename )
  898. {
  899. pak->RemoveFileFromZip( relativename );
  900. }
  901. //-----------------------------------------------------------------------------
  902. // Purpose: Get next filename in directory
  903. // Input : id, -1 to start, returns next id, or -1 at list conclusion
  904. //-----------------------------------------------------------------------------
  905. int GetNextFilename( IZip *pak, int id, char *pBuffer, int bufferSize, int &fileSize )
  906. {
  907. return pak->GetNextFilename( id, pBuffer, bufferSize, fileSize );
  908. }
  909. //-----------------------------------------------------------------------------
  910. // Convert four-CC code to a handle + back
  911. //-----------------------------------------------------------------------------
  912. GameLumpHandle_t CGameLump::GetGameLumpHandle( GameLumpId_t id )
  913. {
  914. // NOTE: I'm also expecting game lump id's to be four-CC codes
  915. Assert( id > HEADER_LUMPS );
  916. FOR_EACH_LL(m_GameLumps, i)
  917. {
  918. if (m_GameLumps[i].m_Id == id)
  919. return i;
  920. }
  921. return InvalidGameLump();
  922. }
  923. GameLumpId_t CGameLump::GetGameLumpId( GameLumpHandle_t handle )
  924. {
  925. return m_GameLumps[handle].m_Id;
  926. }
  927. int CGameLump::GetGameLumpFlags( GameLumpHandle_t handle )
  928. {
  929. return m_GameLumps[handle].m_Flags;
  930. }
  931. int CGameLump::GetGameLumpVersion( GameLumpHandle_t handle )
  932. {
  933. return m_GameLumps[handle].m_Version;
  934. }
  935. //-----------------------------------------------------------------------------
  936. // Game lump accessor methods
  937. //-----------------------------------------------------------------------------
  938. void* CGameLump::GetGameLump( GameLumpHandle_t id )
  939. {
  940. return m_GameLumps[id].m_Memory.Base();
  941. }
  942. int CGameLump::GameLumpSize( GameLumpHandle_t id )
  943. {
  944. return m_GameLumps[id].m_Memory.NumAllocated();
  945. }
  946. //-----------------------------------------------------------------------------
  947. // Game lump iteration methods
  948. //-----------------------------------------------------------------------------
  949. GameLumpHandle_t CGameLump::FirstGameLump()
  950. {
  951. return (m_GameLumps.Count()) ? m_GameLumps.Head() : InvalidGameLump();
  952. }
  953. GameLumpHandle_t CGameLump::NextGameLump( GameLumpHandle_t handle )
  954. {
  955. return (m_GameLumps.IsValidIndex(handle)) ? m_GameLumps.Next(handle) : InvalidGameLump();
  956. }
  957. GameLumpHandle_t CGameLump::InvalidGameLump()
  958. {
  959. return 0xFFFF;
  960. }
  961. //-----------------------------------------------------------------------------
  962. // Game lump creation/destruction method
  963. //-----------------------------------------------------------------------------
  964. GameLumpHandle_t CGameLump::CreateGameLump( GameLumpId_t id, int size, int flags, int version )
  965. {
  966. Assert( GetGameLumpHandle(id) == InvalidGameLump() );
  967. GameLumpHandle_t handle = m_GameLumps.AddToTail();
  968. m_GameLumps[handle].m_Id = id;
  969. m_GameLumps[handle].m_Flags = flags;
  970. m_GameLumps[handle].m_Version = version;
  971. m_GameLumps[handle].m_Memory.EnsureCapacity( size );
  972. return handle;
  973. }
  974. void CGameLump::DestroyGameLump( GameLumpHandle_t handle )
  975. {
  976. m_GameLumps.Remove( handle );
  977. }
  978. void CGameLump::DestroyAllGameLumps()
  979. {
  980. m_GameLumps.RemoveAll();
  981. }
  982. //-----------------------------------------------------------------------------
  983. // Compute file size and clump count
  984. //-----------------------------------------------------------------------------
  985. void CGameLump::ComputeGameLumpSizeAndCount( int& size, int& clumpCount )
  986. {
  987. // Figure out total size of the client lumps
  988. size = 0;
  989. clumpCount = 0;
  990. GameLumpHandle_t h;
  991. for( h = FirstGameLump(); h != InvalidGameLump(); h = NextGameLump( h ) )
  992. {
  993. ++clumpCount;
  994. size += GameLumpSize( h );
  995. }
  996. // Add on headers
  997. size += sizeof( dgamelumpheader_t ) + clumpCount * sizeof( dgamelump_t );
  998. }
  999. void CGameLump::SwapGameLump( GameLumpId_t id, int version, byte *dest, byte *src, int length )
  1000. {
  1001. int count = 0;
  1002. switch( id )
  1003. {
  1004. case GAMELUMP_STATIC_PROPS:
  1005. // Swap the static prop model dict
  1006. count = *(int*)src;
  1007. g_Swap.SwapBufferToTargetEndian( (int*)dest, (int*)src );
  1008. count = g_bSwapOnLoad ? *(int*)dest : count;
  1009. src += sizeof(int);
  1010. dest += sizeof(int);
  1011. g_Swap.SwapFieldsToTargetEndian( (StaticPropDictLump_t*)dest, (StaticPropDictLump_t*)src, count );
  1012. src += sizeof(StaticPropDictLump_t) * count;
  1013. dest += sizeof(StaticPropDictLump_t) * count;
  1014. // Swap the leaf list
  1015. count = *(int*)src;
  1016. g_Swap.SwapBufferToTargetEndian( (int*)dest, (int*)src );
  1017. count = g_bSwapOnLoad ? *(int*)dest : count;
  1018. src += sizeof(int);
  1019. dest += sizeof(int);
  1020. g_Swap.SwapFieldsToTargetEndian( (StaticPropLeafLump_t*)dest, (StaticPropLeafLump_t*)src, count );
  1021. src += sizeof(StaticPropLeafLump_t) * count;
  1022. dest += sizeof(StaticPropLeafLump_t) * count;
  1023. // Swap the models
  1024. count = *(int*)src;
  1025. g_Swap.SwapBufferToTargetEndian( (int*)dest, (int*)src );
  1026. count = g_bSwapOnLoad ? *(int*)dest : count;
  1027. src += sizeof(int);
  1028. dest += sizeof(int);
  1029. // The one-at-a-time swap is to compensate for these structures
  1030. // possibly being misaligned, which crashes the Xbox 360.
  1031. if ( version == 4 )
  1032. {
  1033. StaticPropLumpV4_t lump;
  1034. for ( int i = 0; i < count; ++i )
  1035. {
  1036. Q_memcpy( &lump, src, sizeof(StaticPropLumpV4_t) );
  1037. g_Swap.SwapFieldsToTargetEndian( &lump, &lump );
  1038. Q_memcpy( dest, &lump, sizeof(StaticPropLumpV4_t) );
  1039. src += sizeof( StaticPropLumpV4_t );
  1040. dest += sizeof( StaticPropLumpV4_t );
  1041. }
  1042. }
  1043. else if ( version == 5 )
  1044. {
  1045. StaticPropLumpV5_t lump;
  1046. for ( int i = 0; i < count; ++i )
  1047. {
  1048. Q_memcpy( &lump, src, sizeof(StaticPropLumpV5_t) );
  1049. g_Swap.SwapFieldsToTargetEndian( &lump, &lump );
  1050. Q_memcpy( dest, &lump, sizeof(StaticPropLumpV5_t) );
  1051. src += sizeof( StaticPropLumpV5_t );
  1052. dest += sizeof( StaticPropLumpV5_t );
  1053. }
  1054. }
  1055. else if ( version == 6 )
  1056. {
  1057. StaticPropLumpV6_t lump;
  1058. for ( int i = 0; i < count; ++i )
  1059. {
  1060. Q_memcpy( &lump, src, sizeof( StaticPropLumpV6_t ) );
  1061. g_Swap.SwapFieldsToTargetEndian( &lump, &lump );
  1062. Q_memcpy( dest, &lump, sizeof( StaticPropLumpV6_t ) );
  1063. src += sizeof( StaticPropLumpV6_t );
  1064. dest += sizeof( StaticPropLumpV6_t );
  1065. }
  1066. }
  1067. else if ( version == 7 )
  1068. {
  1069. StaticPropLumpV7_t lump;
  1070. for ( int i = 0; i < count; ++i )
  1071. {
  1072. Q_memcpy( &lump, src, sizeof( StaticPropLumpV7_t ) );
  1073. g_Swap.SwapFieldsToTargetEndian( &lump, &lump );
  1074. Q_memcpy( dest, &lump, sizeof( StaticPropLumpV7_t ) );
  1075. src += sizeof( StaticPropLumpV7_t );
  1076. dest += sizeof( StaticPropLumpV7_t );
  1077. }
  1078. }
  1079. else if ( version == 8 )
  1080. {
  1081. StaticPropLumpV8_t lump;
  1082. for ( int i = 0; i < count; ++i )
  1083. {
  1084. Q_memcpy( &lump, src, sizeof(StaticPropLumpV8_t) );
  1085. g_Swap.SwapFieldsToTargetEndian( &lump, &lump );
  1086. Q_memcpy( dest, &lump, sizeof(StaticPropLumpV8_t) );
  1087. src += sizeof( StaticPropLumpV8_t );
  1088. dest += sizeof( StaticPropLumpV8_t );
  1089. }
  1090. }
  1091. else if ( version == 9 )
  1092. {
  1093. StaticPropLumpV9_t lump;
  1094. for ( int i = 0; i < count; ++i )
  1095. {
  1096. Q_memcpy( &lump, src, sizeof(StaticPropLumpV9_t) );
  1097. g_Swap.SwapFieldsToTargetEndian( &lump, &lump );
  1098. Q_memcpy( dest, &lump, sizeof(StaticPropLumpV9_t) );
  1099. src += sizeof( StaticPropLumpV9_t );
  1100. dest += sizeof( StaticPropLumpV9_t );
  1101. }
  1102. }
  1103. else
  1104. {
  1105. if ( version != 10 )
  1106. {
  1107. Error( "Unknown Static Prop Lump version %d didn't get swapped!\n", version );
  1108. }
  1109. StaticPropLump_t lump;
  1110. for ( int i = 0; i < count; ++i )
  1111. {
  1112. Q_memcpy( &lump, src, sizeof(StaticPropLump_t) );
  1113. g_Swap.SwapFieldsToTargetEndian( &lump, &lump );
  1114. Q_memcpy( dest, &lump, sizeof(StaticPropLump_t) );
  1115. src += sizeof( StaticPropLump_t );
  1116. dest += sizeof( StaticPropLump_t );
  1117. }
  1118. }
  1119. break;
  1120. case GAMELUMP_DETAIL_PROPS:
  1121. // Swap the detail prop model dict
  1122. count = *(int*)src;
  1123. g_Swap.SwapBufferToTargetEndian( (int*)dest, (int*)src );
  1124. count = g_bSwapOnLoad ? *(int*)dest : count;
  1125. src += sizeof(int);
  1126. dest += sizeof(int);
  1127. g_Swap.SwapFieldsToTargetEndian( (DetailObjectDictLump_t*)dest, (DetailObjectDictLump_t*)src, count );
  1128. src += sizeof(DetailObjectDictLump_t) * count;
  1129. dest += sizeof(DetailObjectDictLump_t) * count;
  1130. if ( version == 4 )
  1131. {
  1132. // Swap the detail sprite dict
  1133. count = *(int*)src;
  1134. g_Swap.SwapBufferToTargetEndian( (int*)dest, (int*)src );
  1135. count = g_bSwapOnLoad ? *(int*)dest : count;
  1136. src += sizeof(int);
  1137. dest += sizeof(int);
  1138. DetailSpriteDictLump_t spritelump;
  1139. for ( int i = 0; i < count; ++i )
  1140. {
  1141. Q_memcpy( &spritelump, src, sizeof(DetailSpriteDictLump_t) );
  1142. g_Swap.SwapFieldsToTargetEndian( &spritelump, &spritelump );
  1143. Q_memcpy( dest, &spritelump, sizeof(DetailSpriteDictLump_t) );
  1144. src += sizeof(DetailSpriteDictLump_t);
  1145. dest += sizeof(DetailSpriteDictLump_t);
  1146. }
  1147. // Swap the models
  1148. count = *(int*)src;
  1149. g_Swap.SwapBufferToTargetEndian( (int*)dest, (int*)src );
  1150. count = g_bSwapOnLoad ? *(int*)dest : count;
  1151. src += sizeof(int);
  1152. dest += sizeof(int);
  1153. DetailObjectLump_t objectlump;
  1154. for ( int i = 0; i < count; ++i )
  1155. {
  1156. Q_memcpy( &objectlump, src, sizeof(DetailObjectLump_t) );
  1157. g_Swap.SwapFieldsToTargetEndian( &objectlump, &objectlump );
  1158. Q_memcpy( dest, &objectlump, sizeof(DetailObjectLump_t) );
  1159. src += sizeof(DetailObjectLump_t);
  1160. dest += sizeof(DetailObjectLump_t);
  1161. }
  1162. }
  1163. break;
  1164. case GAMELUMP_DETAIL_PROP_LIGHTING:
  1165. // Swap the LDR light styles
  1166. count = *(int*)src;
  1167. g_Swap.SwapBufferToTargetEndian( (int*)dest, (int*)src );
  1168. count = g_bSwapOnLoad ? *(int*)dest : count;
  1169. src += sizeof(int);
  1170. dest += sizeof(int);
  1171. g_Swap.SwapFieldsToTargetEndian( (DetailPropLightstylesLump_t*)dest, (DetailPropLightstylesLump_t*)src, count );
  1172. src += sizeof(DetailObjectDictLump_t) * count;
  1173. dest += sizeof(DetailObjectDictLump_t) * count;
  1174. break;
  1175. case GAMELUMP_DETAIL_PROP_LIGHTING_HDR:
  1176. // Swap the HDR light styles
  1177. count = *(int*)src;
  1178. g_Swap.SwapBufferToTargetEndian( (int*)dest, (int*)src );
  1179. count = g_bSwapOnLoad ? *(int*)dest : count;
  1180. src += sizeof(int);
  1181. dest += sizeof(int);
  1182. g_Swap.SwapFieldsToTargetEndian( (DetailPropLightstylesLump_t*)dest, (DetailPropLightstylesLump_t*)src, count );
  1183. src += sizeof(DetailObjectDictLump_t) * count;
  1184. dest += sizeof(DetailObjectDictLump_t) * count;
  1185. break;
  1186. default:
  1187. char idchars[5] = {0};
  1188. Q_memcpy( idchars, &id, 4 );
  1189. Warning( "Unknown game lump '%s' didn't get swapped!\n", idchars );
  1190. memcpy ( dest, src, length);
  1191. break;
  1192. }
  1193. }
  1194. //-----------------------------------------------------------------------------
  1195. // Game lump file I/O
  1196. //-----------------------------------------------------------------------------
  1197. void CGameLump::ParseGameLump( BSPHeader_t* pHeader )
  1198. {
  1199. g_GameLumps.DestroyAllGameLumps();
  1200. g_Lumps.bLumpParsed[LUMP_GAME_LUMP] = true;
  1201. int length = pHeader->lumps[LUMP_GAME_LUMP].filelen;
  1202. int ofs = pHeader->lumps[LUMP_GAME_LUMP].fileofs;
  1203. if (length > 0)
  1204. {
  1205. // Read dictionary...
  1206. dgamelumpheader_t* pGameLumpHeader = (dgamelumpheader_t*)((byte *)pHeader + ofs);
  1207. if ( g_bSwapOnLoad )
  1208. {
  1209. g_Swap.SwapFieldsToTargetEndian( pGameLumpHeader );
  1210. }
  1211. dgamelump_t* pGameLump = (dgamelump_t*)(pGameLumpHeader + 1);
  1212. for (int i = 0; i < pGameLumpHeader->lumpCount; ++i )
  1213. {
  1214. if ( g_bSwapOnLoad )
  1215. {
  1216. g_Swap.SwapFieldsToTargetEndian( &pGameLump[i] );
  1217. }
  1218. int length = pGameLump[i].filelen;
  1219. GameLumpHandle_t lump = g_GameLumps.CreateGameLump( pGameLump[i].id, length, pGameLump[i].flags, pGameLump[i].version );
  1220. if ( g_bSwapOnLoad )
  1221. {
  1222. SwapGameLump( pGameLump[i].id, pGameLump[i].version, (byte*)g_GameLumps.GetGameLump(lump), (byte *)pHeader + pGameLump[i].fileofs, length );
  1223. }
  1224. else
  1225. {
  1226. memcpy( g_GameLumps.GetGameLump(lump), (byte *)pHeader + pGameLump[i].fileofs, length );
  1227. }
  1228. }
  1229. }
  1230. }
  1231. //-----------------------------------------------------------------------------
  1232. // String table methods
  1233. //-----------------------------------------------------------------------------
  1234. const char *TexDataStringTable_GetString( int stringID )
  1235. {
  1236. return &g_TexDataStringData[g_TexDataStringTable[stringID]];
  1237. }
  1238. int TexDataStringTable_AddOrFindString( const char *pString )
  1239. {
  1240. int i;
  1241. // garymcthack: Make this use an RBTree!
  1242. for( i = 0; i < g_TexDataStringTable.Count(); i++ )
  1243. {
  1244. if( stricmp( pString, &g_TexDataStringData[g_TexDataStringTable[i]] ) == 0 )
  1245. {
  1246. return i;
  1247. }
  1248. }
  1249. int len = strlen( pString );
  1250. int outOffset = g_TexDataStringData.AddMultipleToTail( len+1, pString );
  1251. int outIndex = g_TexDataStringTable.AddToTail( outOffset );
  1252. return outIndex;
  1253. }
  1254. //-----------------------------------------------------------------------------
  1255. // Adds all game lumps into one big block
  1256. //-----------------------------------------------------------------------------
  1257. static void AddGameLumps()
  1258. {
  1259. // Figure out total size of the client lumps
  1260. int size, clumpCount;
  1261. g_GameLumps.ComputeGameLumpSizeAndCount( size, clumpCount );
  1262. // Set up the main lump dictionary entry
  1263. g_Lumps.size[LUMP_GAME_LUMP] = 0; // mark it written
  1264. lump_t* lump = &g_pBSPHeader->lumps[LUMP_GAME_LUMP];
  1265. lump->fileofs = g_pFileSystem->Tell( g_hBSPFile );
  1266. lump->filelen = size;
  1267. // write header
  1268. dgamelumpheader_t header;
  1269. header.lumpCount = clumpCount;
  1270. WriteData( &header );
  1271. // write dictionary
  1272. dgamelump_t dict;
  1273. // offset is absolute
  1274. int offset = lump->fileofs + sizeof( header ) + clumpCount * sizeof( dgamelump_t );
  1275. GameLumpHandle_t h;
  1276. for ( h = g_GameLumps.FirstGameLump(); h != g_GameLumps.InvalidGameLump(); h = g_GameLumps.NextGameLump( h ) )
  1277. {
  1278. dict.id = g_GameLumps.GetGameLumpId(h);
  1279. dict.version = g_GameLumps.GetGameLumpVersion(h);
  1280. dict.flags = g_GameLumps.GetGameLumpFlags(h);
  1281. dict.fileofs = offset;
  1282. dict.filelen = g_GameLumps.GameLumpSize( h );
  1283. offset += dict.filelen;
  1284. WriteData( &dict );
  1285. }
  1286. // write game lump data
  1287. // offsets march along in the same manner as the dictionary encoded them
  1288. for ( h = g_GameLumps.FirstGameLump(); h != g_GameLumps.InvalidGameLump(); h = g_GameLumps.NextGameLump( h ) )
  1289. {
  1290. unsigned int lumpsize = g_GameLumps.GameLumpSize(h);
  1291. if ( g_bSwapOnWrite )
  1292. {
  1293. g_GameLumps.SwapGameLump( g_GameLumps.GetGameLumpId(h), g_GameLumps.GetGameLumpVersion(h), (byte*)g_GameLumps.GetGameLump(h), (byte*)g_GameLumps.GetGameLump(h), lumpsize );
  1294. }
  1295. SafeWrite( g_hBSPFile, g_GameLumps.GetGameLump(h), lumpsize );
  1296. }
  1297. // stay aligned on lump boundaries
  1298. AlignFilePosition( g_hBSPFile, LUMP_ALIGNMENT );
  1299. }
  1300. //-----------------------------------------------------------------------------
  1301. // Adds the occluder lump...
  1302. //-----------------------------------------------------------------------------
  1303. static void AddOcclusionLump( )
  1304. {
  1305. g_Lumps.size[LUMP_OCCLUSION] = 0; // mark it written
  1306. int nOccluderCount = g_OccluderData.Count();
  1307. int nOccluderPolyDataCount = g_OccluderPolyData.Count();
  1308. int nOccluderVertexIndices = g_OccluderVertexIndices.Count();
  1309. int nLumpLength = nOccluderCount * sizeof(doccluderdata_t) +
  1310. nOccluderPolyDataCount * sizeof(doccluderpolydata_t) +
  1311. nOccluderVertexIndices * sizeof(int) +
  1312. 3 * sizeof(int);
  1313. lump_t *lump = &g_pBSPHeader->lumps[LUMP_OCCLUSION];
  1314. lump->fileofs = g_pFileSystem->Tell( g_hBSPFile );
  1315. lump->filelen = nLumpLength;
  1316. lump->version = LUMP_OCCLUSION_VERSION;
  1317. lump->fourCC[0] = ( char )0;
  1318. lump->fourCC[1] = ( char )0;
  1319. lump->fourCC[2] = ( char )0;
  1320. lump->fourCC[3] = ( char )0;
  1321. // Data is swapped in place, so the 'Count' variables aren't safe to use after they're written
  1322. WriteData( FIELD_INTEGER, &nOccluderCount );
  1323. WriteData( (doccluderdata_t*)g_OccluderData.Base(), g_OccluderData.Count() );
  1324. WriteData( FIELD_INTEGER, &nOccluderPolyDataCount );
  1325. WriteData( (doccluderpolydata_t*)g_OccluderPolyData.Base(), g_OccluderPolyData.Count() );
  1326. WriteData( FIELD_INTEGER, &nOccluderVertexIndices );
  1327. WriteData( FIELD_INTEGER, (int*)g_OccluderVertexIndices.Base(), g_OccluderVertexIndices.Count() );
  1328. }
  1329. //-----------------------------------------------------------------------------
  1330. // Loads the occluder lump...
  1331. //-----------------------------------------------------------------------------
  1332. static void UnserializeOcclusionLumpV2( CUtlBuffer &buf )
  1333. {
  1334. int nCount = buf.GetInt();
  1335. if ( nCount )
  1336. {
  1337. g_OccluderData.SetCount( nCount );
  1338. buf.GetObjects( g_OccluderData.Base(), nCount );
  1339. }
  1340. nCount = buf.GetInt();
  1341. if ( nCount )
  1342. {
  1343. g_OccluderPolyData.SetCount( nCount );
  1344. buf.GetObjects( g_OccluderPolyData.Base(), nCount );
  1345. }
  1346. nCount = buf.GetInt();
  1347. if ( nCount )
  1348. {
  1349. if ( g_bSwapOnLoad )
  1350. {
  1351. g_Swap.SwapBufferToTargetEndian( (int*)buf.PeekGet(), (int*)buf.PeekGet(), nCount );
  1352. }
  1353. g_OccluderVertexIndices.SetCount( nCount );
  1354. buf.Get( g_OccluderVertexIndices.Base(), nCount * sizeof(g_OccluderVertexIndices[0]) );
  1355. }
  1356. }
  1357. static void LoadOcclusionLump()
  1358. {
  1359. g_OccluderData.RemoveAll();
  1360. g_OccluderPolyData.RemoveAll();
  1361. g_OccluderVertexIndices.RemoveAll();
  1362. int length, ofs;
  1363. g_Lumps.bLumpParsed[LUMP_OCCLUSION] = true;
  1364. length = g_pBSPHeader->lumps[LUMP_OCCLUSION].filelen;
  1365. ofs = g_pBSPHeader->lumps[LUMP_OCCLUSION].fileofs;
  1366. CUtlBuffer buf( (byte *)g_pBSPHeader + ofs, length, CUtlBuffer::READ_ONLY );
  1367. buf.ActivateByteSwapping( g_bSwapOnLoad );
  1368. switch ( g_pBSPHeader->lumps[LUMP_OCCLUSION].version )
  1369. {
  1370. case 2:
  1371. UnserializeOcclusionLumpV2( buf );
  1372. break;
  1373. case 0:
  1374. break;
  1375. default:
  1376. Error("Unknown occlusion lump version!\n");
  1377. break;
  1378. }
  1379. }
  1380. /*
  1381. ===============
  1382. CompressVis
  1383. ===============
  1384. */
  1385. int CompressVis (byte *vis, byte *dest)
  1386. {
  1387. int j;
  1388. int rep;
  1389. int visrow;
  1390. byte *dest_p;
  1391. dest_p = dest;
  1392. // visrow = (r_numvisleafs + 7)>>3;
  1393. visrow = (dvis->numclusters + 7)>>3;
  1394. for (j=0 ; j<visrow ; j++)
  1395. {
  1396. *dest_p++ = vis[j];
  1397. if (vis[j])
  1398. continue;
  1399. rep = 1;
  1400. for ( j++; j<visrow ; j++)
  1401. if (vis[j] || rep == 255)
  1402. break;
  1403. else
  1404. rep++;
  1405. *dest_p++ = rep;
  1406. j--;
  1407. }
  1408. return dest_p - dest;
  1409. }
  1410. /*
  1411. ===================
  1412. DecompressVis
  1413. ===================
  1414. */
  1415. void DecompressVis (byte *in, byte *decompressed)
  1416. {
  1417. int c;
  1418. byte *out;
  1419. int row;
  1420. // row = (r_numvisleafs+7)>>3;
  1421. row = (dvis->numclusters+7)>>3;
  1422. out = decompressed;
  1423. do
  1424. {
  1425. if (*in)
  1426. {
  1427. *out++ = *in++;
  1428. continue;
  1429. }
  1430. c = in[1];
  1431. if (!c)
  1432. Error ("DecompressVis: 0 repeat");
  1433. in += 2;
  1434. if ((out - decompressed) + c > row)
  1435. {
  1436. c = row - (out - decompressed);
  1437. Warning( "warning: Vis decompression overrun\n" );
  1438. }
  1439. while (c)
  1440. {
  1441. *out++ = 0;
  1442. c--;
  1443. }
  1444. } while (out - decompressed < row);
  1445. }
  1446. //-----------------------------------------------------------------------------
  1447. // Lump-specific swap functions
  1448. //-----------------------------------------------------------------------------
  1449. struct swapcollideheader_t
  1450. {
  1451. DECLARE_BYTESWAP_DATADESC();
  1452. int size;
  1453. int vphysicsID;
  1454. short version;
  1455. short modelType;
  1456. };
  1457. struct swapcompactsurfaceheader_t : swapcollideheader_t
  1458. {
  1459. DECLARE_BYTESWAP_DATADESC();
  1460. int surfaceSize;
  1461. Vector dragAxisAreas;
  1462. int axisMapSize;
  1463. };
  1464. struct swapmoppsurfaceheader_t : swapcollideheader_t
  1465. {
  1466. DECLARE_BYTESWAP_DATADESC();
  1467. int moppSize;
  1468. };
  1469. BEGIN_BYTESWAP_DATADESC( swapcollideheader_t )
  1470. DEFINE_FIELD( size, FIELD_INTEGER ),
  1471. DEFINE_FIELD( vphysicsID, FIELD_INTEGER ),
  1472. DEFINE_FIELD( version, FIELD_SHORT ),
  1473. DEFINE_FIELD( modelType, FIELD_SHORT ),
  1474. END_BYTESWAP_DATADESC()
  1475. BEGIN_BYTESWAP_DATADESC_( swapcompactsurfaceheader_t, swapcollideheader_t )
  1476. DEFINE_FIELD( surfaceSize, FIELD_INTEGER ),
  1477. DEFINE_FIELD( dragAxisAreas, FIELD_VECTOR ),
  1478. DEFINE_FIELD( axisMapSize, FIELD_INTEGER ),
  1479. END_BYTESWAP_DATADESC()
  1480. BEGIN_BYTESWAP_DATADESC_( swapmoppsurfaceheader_t, swapcollideheader_t )
  1481. DEFINE_FIELD( moppSize, FIELD_INTEGER ),
  1482. END_BYTESWAP_DATADESC()
  1483. static void SwapPhyscollideLump( byte *pDestBase, byte *pSrcBase, unsigned int &count )
  1484. {
  1485. IPhysicsCollision *physcollision = NULL;
  1486. CSysModule *pPhysicsModule = g_pFullFileSystem->LoadModule( "vphysics.dll" );
  1487. if ( pPhysicsModule )
  1488. {
  1489. CreateInterfaceFn physicsFactory = Sys_GetFactory( pPhysicsModule );
  1490. if ( physicsFactory )
  1491. {
  1492. physcollision = (IPhysicsCollision *)physicsFactory( VPHYSICS_COLLISION_INTERFACE_VERSION, NULL );
  1493. }
  1494. }
  1495. if ( !physcollision )
  1496. {
  1497. Warning("!!! WARNING: Can't swap the physcollide lump!\n" );
  1498. return;
  1499. }
  1500. // physics data is variable length. The last physmodel is a NULL pointer
  1501. // with modelIndex -1, dataSize -1
  1502. dphysmodel_t *pPhysModel;
  1503. byte *pSrc = pSrcBase;
  1504. // first the src chunks have to be aligned properly
  1505. // swap increases size, allocate enough expansion room
  1506. byte *pSrcAlignedBase = (byte*)malloc( 2*count );
  1507. byte *basePtr = pSrcAlignedBase;
  1508. byte *pSrcAligned = pSrcAlignedBase;
  1509. do
  1510. {
  1511. if ( g_bSwapOnLoad )
  1512. {
  1513. g_Swap.SwapFieldsToTargetEndian( (dphysmodel_t*)pSrcAligned, (dphysmodel_t*)pSrc );
  1514. }
  1515. else
  1516. {
  1517. Q_memcpy( pSrcAligned, pSrc, sizeof(dphysmodel_t) );
  1518. }
  1519. pPhysModel = (dphysmodel_t*)pSrcAligned;
  1520. pSrc += sizeof(dphysmodel_t);
  1521. pSrcAligned += sizeof(dphysmodel_t);
  1522. if ( pPhysModel->dataSize > 0 )
  1523. {
  1524. // Align the collide headers
  1525. for ( int i = 0; i < pPhysModel->solidCount; ++i )
  1526. {
  1527. // Get data size
  1528. int size;
  1529. Q_memcpy( &size, pSrc, sizeof(int) );
  1530. if ( g_bSwapOnLoad )
  1531. size = SwapLong( size );
  1532. // Fixup size
  1533. int padBytes = 0;
  1534. if ( size % 4 != 0 )
  1535. {
  1536. padBytes = ( 4 - size % 4 );
  1537. count += padBytes;
  1538. pPhysModel->dataSize += padBytes;
  1539. }
  1540. // Copy data and size into alligned buffer
  1541. int newsize = size + padBytes;
  1542. if ( g_bSwapOnLoad )
  1543. newsize = SwapLong( newsize );
  1544. Q_memcpy( pSrcAligned, &newsize, sizeof(int) );
  1545. Q_memcpy( pSrcAligned + sizeof(int), pSrc + sizeof(int), size );
  1546. pSrcAligned += size + padBytes + sizeof(int);
  1547. pSrc += size + sizeof(int);
  1548. }
  1549. int padBytes = 0;
  1550. int dataSize = pPhysModel->dataSize + pPhysModel->keydataSize;
  1551. Q_memcpy( pSrcAligned, pSrc, pPhysModel->keydataSize );
  1552. pSrc += pPhysModel->keydataSize;
  1553. pSrcAligned += pPhysModel->keydataSize;
  1554. if ( dataSize % 4 != 0 )
  1555. {
  1556. // Next chunk will be unaligned
  1557. padBytes = ( 4 - dataSize % 4 );
  1558. pPhysModel->keydataSize += padBytes;
  1559. count += padBytes;
  1560. Q_memset( pSrcAligned, 0, padBytes );
  1561. pSrcAligned += padBytes;
  1562. }
  1563. }
  1564. } while ( pPhysModel->dataSize > 0 );
  1565. // Now the data can be swapped properly
  1566. pSrcBase = pSrcAlignedBase;
  1567. pSrc = pSrcBase;
  1568. byte *pDest = pDestBase;
  1569. do
  1570. {
  1571. // src headers are in native format
  1572. pPhysModel = (dphysmodel_t*)pSrc;
  1573. if ( g_bSwapOnWrite )
  1574. {
  1575. g_Swap.SwapFieldsToTargetEndian( (dphysmodel_t*)pDest, (dphysmodel_t*)pSrc );
  1576. }
  1577. else
  1578. {
  1579. Q_memcpy( pDest, pSrc, sizeof(dphysmodel_t) );
  1580. }
  1581. pSrc += sizeof(dphysmodel_t);
  1582. pDest += sizeof(dphysmodel_t);
  1583. pSrcBase = pSrc;
  1584. pDestBase = pDest;
  1585. if ( pPhysModel->dataSize > 0 )
  1586. {
  1587. vcollide_t collide = {0};
  1588. int dataSize = pPhysModel->dataSize + pPhysModel->keydataSize;
  1589. if ( g_bSwapOnWrite )
  1590. {
  1591. // Load the collide data
  1592. physcollision->VCollideLoad( &collide, pPhysModel->solidCount, (const char *)pSrc, dataSize, false );
  1593. }
  1594. int *offsets = new int[ pPhysModel->solidCount ];
  1595. // Swap the collision data headers
  1596. for ( int i = 0; i < pPhysModel->solidCount; ++i )
  1597. {
  1598. int headerSize = 0;
  1599. swapcollideheader_t *baseHdr = (swapcollideheader_t*)pSrc;
  1600. short modelType = baseHdr->modelType;
  1601. if ( g_bSwapOnLoad )
  1602. {
  1603. g_Swap.SwapBufferToTargetEndian( &modelType );
  1604. }
  1605. if ( modelType == 0 ) // COLLIDE_POLY
  1606. {
  1607. headerSize = sizeof(swapcompactsurfaceheader_t);
  1608. swapcompactsurfaceheader_t swapHdr;
  1609. Q_memcpy( &swapHdr, pSrc, headerSize );
  1610. g_Swap.SwapFieldsToTargetEndian( &swapHdr, &swapHdr );
  1611. Q_memcpy( pDest, &swapHdr, headerSize );
  1612. }
  1613. else if ( modelType == 1 ) // COLLIDE_MOPP
  1614. {
  1615. // The PC still unserializes these, but we don't support them
  1616. if ( g_bSwapOnWrite )
  1617. {
  1618. collide.solids[i] = NULL;
  1619. }
  1620. headerSize = sizeof(swapmoppsurfaceheader_t);
  1621. swapmoppsurfaceheader_t swapHdr;
  1622. Q_memcpy( &swapHdr, pSrc, headerSize );
  1623. g_Swap.SwapFieldsToTargetEndian( &swapHdr, &swapHdr );
  1624. Q_memcpy( pDest, &swapHdr, headerSize );
  1625. }
  1626. else
  1627. {
  1628. // Shouldn't happen
  1629. Assert( 0 );
  1630. }
  1631. if ( g_bSwapOnLoad )
  1632. {
  1633. // src needs the native header data to load the vcollides
  1634. Q_memcpy( pSrc, pDest, headerSize );
  1635. }
  1636. // HACK: Need either surfaceSize or moppSize - both sit at the same offset in the structure
  1637. swapmoppsurfaceheader_t *hdr = (swapmoppsurfaceheader_t*)pSrc;
  1638. pSrc += hdr->size + sizeof(int);
  1639. pDest += hdr->size + sizeof(int);
  1640. offsets[i] = hdr->size;
  1641. }
  1642. pSrc = pSrcBase;
  1643. pDest = pDestBase;
  1644. if ( g_bSwapOnLoad )
  1645. {
  1646. physcollision->VCollideLoad( &collide, pPhysModel->solidCount, (const char *)pSrc, dataSize, true );
  1647. }
  1648. // Write out the ledge tree data
  1649. for ( int i = 0; i < pPhysModel->solidCount; ++i )
  1650. {
  1651. if ( collide.solids[i] )
  1652. {
  1653. // skip over the size member
  1654. pSrc += sizeof(int);
  1655. pDest += sizeof(int);
  1656. int offset = physcollision->CollideWrite( (char*)pDest, collide.solids[i], g_bSwapOnWrite );
  1657. pSrc += offset;
  1658. pDest += offset;
  1659. }
  1660. else
  1661. {
  1662. pSrc += offsets[i] + sizeof(int);
  1663. pDest += offsets[i] + sizeof(int);
  1664. }
  1665. }
  1666. // copy the keyvalues data
  1667. Q_memcpy( pDest, pSrc, pPhysModel->keydataSize );
  1668. pDest += pPhysModel->keydataSize;
  1669. pSrc += pPhysModel->keydataSize;
  1670. // Free the memory
  1671. physcollision->VCollideUnload( &collide );
  1672. delete [] offsets;
  1673. }
  1674. // avoid infinite loop on badly formed file
  1675. if ( (pSrc - basePtr) > count )
  1676. break;
  1677. } while ( pPhysModel->dataSize > 0 );
  1678. free( pSrcAlignedBase );
  1679. }
  1680. static void SwapPhyslevelLump( byte *pDest, byte *pSrc, uint &count, int maxExpand )
  1681. {
  1682. #if defined( PHYSICS2_PHYSX_ENABLE )
  1683. // TODO: this must be in AppSystem code
  1684. if ( !g_pPhysics2 )
  1685. {
  1686. CreateInterfaceFn pCreateVphysics = Sys_GetFactory( Sys_LoadModule( "vphysics.dll" ) );
  1687. ConnectTier1Libraries( &pCreateVphysics, 1 );
  1688. }
  1689. if ( !g_pPhysics2 )
  1690. {
  1691. return;
  1692. }
  1693. DataLinker::Stream stream;
  1694. dphyslevelV0_t *pRootIn = ( dphyslevelV0_t * )pSrc;
  1695. if ( count < sizeof( dphyslevelV0_t ) )
  1696. {
  1697. Warning( "Physlevel Lump size is too small (%d bytes)\n", count );
  1698. return;
  1699. }
  1700. if ( pRootIn->dataVersion != pRootIn->DATA_VERSION )
  1701. {
  1702. count = 0;
  1703. Warning( "Physlevel lump is old (%x != %x), can't swap\n", pRootIn->dataVersion, pRootIn->DATA_VERSION );
  1704. return;
  1705. }
  1706. if ( g_bSwapOnLoad ? g_bSwapOnWrite : !g_bSwapOnWrite )
  1707. {
  1708. Warning( "SwapPhyslevelLump: g_bSwapOnLoad == g_bSwapOnWrite, so skipping swapping\n" );
  1709. return;
  1710. }
  1711. if ( g_bSwapOnLoad )
  1712. {
  1713. //g_Swap.SwapFieldsToTargetEndian(pRootIn);
  1714. count = 0;
  1715. Warning( "Physlevel swap on load is not supported\n" );
  1716. // Loading Big-endian data is NOT SUPPORTED
  1717. return;
  1718. }
  1719. IPhysics2ResourceManager *pManager = g_pPhysics2->GetResourceManager();
  1720. IPhysics2Cook *pCook = g_pPhysics2->GetCook();
  1721. pCook->SetTargetPlatform( g_bSwapOnWrite ? pCook->PLATFORM_XENON : pCook->PLATFORM_PC );
  1722. if ( sizeof( DiskPhysics2LevelMesh_t ) != pRootIn->sizeofDiskPhysics2LevelMesh )
  1723. {
  1724. Error( "sizeof(DiskPhysics2LevelMesh_t) changed unexpectedly!\n" );
  1725. }
  1726. dphyslevelV0_t *pRootOut = stream.Write<dphyslevelV0_t>();
  1727. pRootOut->buildTime = pRootIn->buildTime;//(int)time(NULL);
  1728. pRootOut->toolVersion = 4;
  1729. pRootOut->dataVersion = pRootOut->DATA_VERSION;
  1730. pRootOut->sizeofDiskPhysics2LevelMesh = sizeof( DiskPhysics2LevelMesh_t );
  1731. /*if ( pRootIn->polysoup.NotNull() )
  1732. {
  1733. CPhysics2Polysoup *pPolysoupUn = pManager->UnserializePolysoup( pRootIn->polysoup.GetPtr() );
  1734. stream.IStream::Link( &pRootOut->polysoup, pCook->SerializeShape( pPolysoupUn, &stream ) );
  1735. pManager->Release( pPolysoupUn );
  1736. }
  1737. if ( pRootIn->displacementMesh.NotNull() )
  1738. {
  1739. CPhysics2Polysoup *pDisplacementUn = pManager->UnserializePolysoup( pRootIn->displacementMesh.GetPtr() );
  1740. stream.IStream::Link( &pRootOut->displacementMesh, pCook->SerializeShape( pDisplacementUn, &stream ) );
  1741. pManager->Release( pDisplacementUn );
  1742. }*/
  1743. int nLevelMeshCount = pRootIn->levelMeshes.size, nLevelWaterMeshCount = pRootIn->levelWaterMeshes.size;
  1744. DiskPhysics2LevelMesh_t *pDiskLevelMeshes = stream.WriteAndLinkArray( &pRootOut->levelMeshes, nLevelMeshCount );
  1745. DiskPhysics2LevelMesh_t *pDiskLevelWaterMeshes = stream.WriteAndLinkArray( &pRootOut->levelWaterMeshes, nLevelWaterMeshCount );
  1746. // go through all levelMeshes and re-serialize them
  1747. for ( int nLevelMesh = 0; nLevelMesh < nLevelMeshCount; ++nLevelMesh )
  1748. {
  1749. const DiskPhysics2LevelMesh_t &refLevelMeshIn = pRootIn->levelMeshes[nLevelMesh];
  1750. Assert( refLevelMeshIn.polymesh.offset );
  1751. CPhysics2Shape *pShapeUn = NULL;
  1752. if( refLevelMeshIn.flags & refLevelMeshIn.FLAG_FORCE_POLYTOPE )
  1753. {
  1754. pShapeUn = pManager->UnserializePolytope( refLevelMeshIn.polymesh.GetPtr() );
  1755. }
  1756. else
  1757. {
  1758. // default: polysoup
  1759. pShapeUn = pManager->UnserializePolysoup( refLevelMeshIn.polymesh.GetPtr() );
  1760. }
  1761. DiskPhysics2LevelMesh_t &refOut = pDiskLevelMeshes[ nLevelMesh ];
  1762. stream.Link( &refOut.polymesh.offset, pCook->SerializeShape( pShapeUn, &stream ) );
  1763. pManager->Release ( pShapeUn );
  1764. if ( g_bSwapOnWrite )
  1765. {
  1766. g_Swap.SwapFieldsToTargetEndian( &refOut );
  1767. }
  1768. }
  1769. for ( int nLevelWaterMesh = 0; nLevelWaterMesh < nLevelWaterMeshCount; ++nLevelWaterMesh )
  1770. {
  1771. const DiskPhysics2LevelMesh_t &refLevelWaterMeshIn = pRootIn->levelWaterMeshes[nLevelWaterMesh];
  1772. Assert( refLevelWaterMeshIn.polymesh.offset );
  1773. CPhysics2Shape *pShapeUn = NULL;
  1774. if( refLevelWaterMeshIn.flags & refLevelWaterMeshIn.FLAG_FORCE_POLYSOUP )
  1775. {
  1776. pShapeUn = pManager->UnserializePolysoup( refLevelWaterMeshIn.polymesh.GetPtr() );
  1777. }
  1778. else
  1779. {
  1780. // default: polytope
  1781. pShapeUn = pManager->UnserializePolytope( refLevelWaterMeshIn.polymesh.GetPtr() );
  1782. }
  1783. DiskPhysics2LevelMesh_t &refOut = pDiskLevelWaterMeshes[ nLevelWaterMesh ];
  1784. stream.Link( &refOut.polymesh.offset, pCook->SerializeShape( pShapeUn, &stream ) );
  1785. pManager->Release ( pShapeUn );
  1786. if ( g_bSwapOnWrite )
  1787. {
  1788. g_Swap.SwapFieldsToTargetEndian( &refOut );
  1789. }
  1790. }
  1791. // we're deliberately skipping mopp as it's not supported ATM
  1792. if ( g_bSwapOnWrite )
  1793. {
  1794. g_Swap.SwapFieldsToTargetEndian( pRootOut );
  1795. }
  1796. uint nNewSize = stream.GetTotalSize();
  1797. if ( nNewSize > maxExpand )
  1798. {
  1799. Warning( "X360 PhysLevel lump is too big (%d->%d bytes)\n", count, nNewSize );
  1800. count = 0;
  1801. return;
  1802. }
  1803. if ( nNewSize != count )
  1804. {
  1805. // Msg( "PhysLevel size changed %d bytes\n", nNewSize - count );
  1806. }
  1807. count = nNewSize;
  1808. stream.Compile( pDest );
  1809. #endif
  1810. }
  1811. // UNDONE: This code is not yet tested.
  1812. static void SwapPhysdispLump( byte *pDest, byte *pSrc, int count )
  1813. {
  1814. // the format of this lump is one unsigned short dispCount, then dispCount unsigned shorts of sizes
  1815. // followed by an array of variable length (each element is the length of the corresponding entry in the
  1816. // previous table) byte-stream data structure of the displacement collision models
  1817. // these byte-stream structs are endian-neutral because each element is byte-sized
  1818. unsigned short dispCount = *(unsigned short*)pSrc;
  1819. if ( g_bSwapOnLoad )
  1820. {
  1821. g_Swap.SwapBufferToTargetEndian( &dispCount );
  1822. }
  1823. g_Swap.SwapBufferToTargetEndian( (unsigned short*)pDest, (unsigned short*)pSrc, dispCount + 1 );
  1824. const int nBytes = (dispCount + 1) * sizeof( unsigned short );
  1825. pSrc += nBytes;
  1826. pDest += nBytes;
  1827. count -= nBytes;
  1828. g_Swap.SwapBufferToTargetEndian( pDest, pSrc, count );
  1829. }
  1830. static void SwapVisibilityLump( byte *pDest, byte *pSrc, int count )
  1831. {
  1832. int firstInt = *(int*)pSrc;
  1833. if ( g_bSwapOnLoad )
  1834. {
  1835. g_Swap.SwapBufferToTargetEndian( &firstInt );
  1836. }
  1837. int intCt = firstInt * 2 + 1;
  1838. const int hdrSize = intCt * sizeof(int);
  1839. g_Swap.SwapBufferToTargetEndian( (int*)pDest, (int*)pSrc, intCt );
  1840. g_Swap.SwapBufferToTargetEndian( pDest + hdrSize, pSrc + hdrSize, count - hdrSize );
  1841. }
  1842. //=============================================================================
  1843. void Lumps_Init( void )
  1844. {
  1845. memset( &g_Lumps, 0, sizeof(g_Lumps) );
  1846. }
  1847. int LumpVersion( int lump )
  1848. {
  1849. return g_pBSPHeader->lumps[lump].version;
  1850. }
  1851. bool HasLump( int lump )
  1852. {
  1853. return g_pBSPHeader->lumps[lump].filelen > 0;
  1854. }
  1855. void ValidateLump( int lump, int length, int size, int forceVersion )
  1856. {
  1857. if ( length % size )
  1858. {
  1859. Error( "ValidateLump: odd size for lump %d", lump );
  1860. }
  1861. if ( forceVersion >= 0 && forceVersion != g_pBSPHeader->lumps[lump].version )
  1862. {
  1863. Error( "ValidateLump: old version for lump %d in map!", lump );
  1864. }
  1865. }
  1866. //-----------------------------------------------------------------------------
  1867. // Add Lumps of integral types without datadescs
  1868. //-----------------------------------------------------------------------------
  1869. template< class T >
  1870. int CopyLumpInternal( int nFieldType, int nLump, T *pDest, int nForceVersion )
  1871. {
  1872. g_Lumps.bLumpParsed[nLump] = true;
  1873. // Vectors are passed in as floats
  1874. int nFieldSize = ( nFieldType == FIELD_VECTOR ) ? sizeof( Vector ) : sizeof( T );
  1875. unsigned int nLength = g_pBSPHeader->lumps[nLump].filelen;
  1876. if ( g_Lumps.bLumpFixed[nLump] )
  1877. {
  1878. nLength = g_Lumps.size[nLump];
  1879. }
  1880. ValidateLump( nLump, nLength, nFieldSize, nForceVersion );
  1881. // count must be of the integral type
  1882. unsigned int nCount = nLength / sizeof( T );
  1883. byte *pLumpData;
  1884. if ( g_Lumps.bLumpFixed[nLump] )
  1885. {
  1886. pLumpData = (byte *)g_Lumps.pLumps[nLump];
  1887. }
  1888. else
  1889. {
  1890. unsigned int ofs = g_pBSPHeader->lumps[nLump].fileofs;
  1891. pLumpData = ( (byte*)g_pBSPHeader + ofs );
  1892. }
  1893. if ( g_bSwapOnLoad )
  1894. {
  1895. switch( nLump )
  1896. {
  1897. case LUMP_VISIBILITY:
  1898. SwapVisibilityLump( (byte*)pDest, pLumpData, nCount );
  1899. break;
  1900. case LUMP_PHYSCOLLIDE:
  1901. // SwapPhyscollideLump may change size
  1902. SwapPhyscollideLump( (byte*)pDest, pLumpData, nCount );
  1903. nLength = nCount;
  1904. break;
  1905. case LUMP_PHYSDISP:
  1906. SwapPhysdispLump( (byte*)pDest, pLumpData, nCount );
  1907. break;
  1908. case LUMP_PHYSLEVEL:
  1909. SwapPhyslevelLump( (byte*)pDest, pLumpData, nCount, nCount );
  1910. break;
  1911. default:
  1912. g_Swap.SwapBufferToTargetEndian( pDest, (T*)pLumpData, nCount );
  1913. break;
  1914. }
  1915. }
  1916. else
  1917. {
  1918. memcpy( pDest, pLumpData, nLength );
  1919. }
  1920. // Return actual count of elements
  1921. return nLength / nFieldSize;
  1922. }
  1923. template< class T >
  1924. int CopyLump( int fieldType, int lump, T *dest, int forceVersion = -1 )
  1925. {
  1926. return CopyLumpInternal( fieldType, lump, dest, forceVersion );
  1927. }
  1928. template< class T >
  1929. void CopyLump( int fieldType, int lump, CUtlVector<T> &dest, int forceVersion = -1 )
  1930. {
  1931. Assert( fieldType != FIELD_VECTOR ); // TODO: Support this if necessary
  1932. dest.SetSize( g_pBSPHeader->lumps[lump].filelen / sizeof(T) );
  1933. CopyLumpInternal( fieldType, lump, dest.Base(), forceVersion );
  1934. }
  1935. template< class T >
  1936. void CopyOptionalLump( int fieldType, int lump, CUtlVector<T> &dest, int forceVersion = -1 )
  1937. {
  1938. // not fatal if not present
  1939. if ( !HasLump( lump ) )
  1940. return;
  1941. dest.SetSize( g_pBSPHeader->lumps[lump].filelen / sizeof(T) );
  1942. CopyLumpInternal( fieldType, lump, dest.Base(), forceVersion );
  1943. }
  1944. template< class T >
  1945. int CopyVariableLump( int fieldType, int lump, void **dest, int forceVersion = -1 )
  1946. {
  1947. int length = g_pBSPHeader->lumps[lump].filelen;
  1948. *dest = malloc( length );
  1949. return CopyLumpInternal<T>( fieldType, lump, (T*)*dest, forceVersion );
  1950. }
  1951. //-----------------------------------------------------------------------------
  1952. // Add Lumps of object types with datadescs
  1953. //-----------------------------------------------------------------------------
  1954. template< class T >
  1955. int CopyLumpInternal( int nLump, T *pDest, int forceVersion )
  1956. {
  1957. g_Lumps.bLumpParsed[nLump] = true;
  1958. unsigned int nLength = g_pBSPHeader->lumps[nLump].filelen;
  1959. if ( g_Lumps.bLumpFixed[nLump] )
  1960. {
  1961. nLength = g_Lumps.size[nLump];
  1962. }
  1963. ValidateLump( nLump, nLength, sizeof( T ), forceVersion );
  1964. unsigned int nCount = nLength / sizeof( T );
  1965. byte *pLumpData;
  1966. if ( g_Lumps.bLumpFixed[nLump] )
  1967. {
  1968. // lump has been pre-fixed, use that data
  1969. pLumpData = (byte *)g_Lumps.pLumps[nLump];
  1970. }
  1971. else
  1972. {
  1973. unsigned int nFileOffset = g_pBSPHeader->lumps[nLump].fileofs;
  1974. pLumpData = (byte*)g_pBSPHeader + nFileOffset;
  1975. }
  1976. if ( g_bSwapOnLoad )
  1977. {
  1978. g_Swap.SwapFieldsToTargetEndian( pDest, pLumpData, nCount );
  1979. }
  1980. else
  1981. {
  1982. memcpy( pDest, pLumpData, nLength );
  1983. }
  1984. return nCount;
  1985. }
  1986. template< class T >
  1987. int CopyLump( int lump, T *dest, int forceVersion = -1 )
  1988. {
  1989. return CopyLumpInternal( lump, dest, forceVersion );
  1990. }
  1991. template< class T >
  1992. void CopyLump( int lump, CUtlVector<T> &dest, int forceVersion = -1 )
  1993. {
  1994. dest.SetSize( g_pBSPHeader->lumps[lump].filelen / sizeof(T) );
  1995. CopyLumpInternal( lump, dest.Base(), forceVersion );
  1996. }
  1997. template< class T >
  1998. void CopyOptionalLump( int lump, CUtlVector<T> &dest, int forceVersion = -1 )
  1999. {
  2000. // not fatal if not present
  2001. if ( !HasLump( lump ) )
  2002. return;
  2003. dest.SetSize( g_pBSPHeader->lumps[lump].filelen / sizeof(T) );
  2004. CopyLumpInternal( lump, dest.Base(), forceVersion );
  2005. }
  2006. template< class T >
  2007. int CopyVariableLump( int lump, void **dest, int forceVersion = -1 )
  2008. {
  2009. int length = g_pBSPHeader->lumps[lump].filelen;
  2010. *dest = malloc( length );
  2011. return CopyLumpInternal<T>( lump, (T*)*dest, forceVersion );
  2012. }
  2013. //-----------------------------------------------------------------------------
  2014. // Add/Write unknown lumps
  2015. //-----------------------------------------------------------------------------
  2016. void Lumps_Parse( void )
  2017. {
  2018. int i;
  2019. for ( i = 0; i < HEADER_LUMPS; i++ )
  2020. {
  2021. if ( !g_Lumps.bLumpParsed[i] && g_pBSPHeader->lumps[i].filelen )
  2022. {
  2023. g_Lumps.size[i] = CopyVariableLump<byte>( FIELD_CHARACTER, i, &g_Lumps.pLumps[i], -1 );
  2024. Msg( "Reading unknown lump #%d (%d bytes)\n", i, g_Lumps.size[i] );
  2025. }
  2026. }
  2027. }
  2028. void Lumps_Write( void )
  2029. {
  2030. int i;
  2031. for ( i = 0; i < HEADER_LUMPS; i++ )
  2032. {
  2033. if ( g_Lumps.size[i] )
  2034. {
  2035. Msg( "Writing unknown lump #%d (%d bytes)\n", i, g_Lumps.size[i] );
  2036. AddLump( i, (byte*)g_Lumps.pLumps[i], g_Lumps.size[i] );
  2037. }
  2038. if ( g_Lumps.pLumps[i] )
  2039. {
  2040. free( g_Lumps.pLumps[i] );
  2041. g_Lumps.pLumps[i] = NULL;
  2042. }
  2043. }
  2044. }
  2045. int LoadLeafs( void )
  2046. {
  2047. #if defined( BSP_USE_LESS_MEMORY )
  2048. dleafs = (dleaf_t*)malloc( g_pBSPHeader->lumps[LUMP_LEAFS].filelen );
  2049. #endif
  2050. switch ( LumpVersion( LUMP_LEAFS ) )
  2051. {
  2052. case 0:
  2053. {
  2054. g_Lumps.bLumpParsed[LUMP_LEAFS] = true;
  2055. int length = g_pBSPHeader->lumps[LUMP_LEAFS].filelen;
  2056. int size = sizeof( dleaf_version_0_t );
  2057. if ( length % size )
  2058. {
  2059. Error( "odd size for LUMP_LEAFS\n" );
  2060. }
  2061. int count = length / size;
  2062. void *pSrcBase = ( ( byte * )g_pBSPHeader + g_pBSPHeader->lumps[LUMP_LEAFS].fileofs );
  2063. dleaf_version_0_t *pSrc = (dleaf_version_0_t *)pSrcBase;
  2064. dleaf_t *pDst = dleafs;
  2065. // version 0 predates HDR, build the LDR
  2066. g_LeafAmbientLightingLDR.SetCount( count );
  2067. g_LeafAmbientIndexLDR.SetCount( count );
  2068. dleafambientlighting_t *pDstLeafAmbientLighting = &g_LeafAmbientLightingLDR[0];
  2069. for ( int i = 0; i < count; i++ )
  2070. {
  2071. g_LeafAmbientIndexLDR[i].ambientSampleCount = 1;
  2072. g_LeafAmbientIndexLDR[i].firstAmbientSample = i;
  2073. if ( g_bSwapOnLoad )
  2074. {
  2075. g_Swap.SwapFieldsToTargetEndian( pSrc );
  2076. }
  2077. // pDst is a subset of pSrc;
  2078. *pDst = *( ( dleaf_t * )( void * )pSrc );
  2079. pDstLeafAmbientLighting->cube = pSrc->m_AmbientLighting;
  2080. pDstLeafAmbientLighting->x = pDstLeafAmbientLighting->y = pDstLeafAmbientLighting->z = pDstLeafAmbientLighting->pad = 0;
  2081. pDst++;
  2082. pSrc++;
  2083. pDstLeafAmbientLighting++;
  2084. }
  2085. return count;
  2086. }
  2087. case 1:
  2088. return CopyLump( LUMP_LEAFS, dleafs );
  2089. default:
  2090. Assert( 0 );
  2091. Error( "Unknown LUMP_LEAFS version\n" );
  2092. return 0;
  2093. }
  2094. }
  2095. void LoadLeafAmbientLighting( int numLeafs )
  2096. {
  2097. if ( LumpVersion( LUMP_LEAFS ) == 0 )
  2098. {
  2099. // an older leaf version already built the LDR ambient lighting on load
  2100. return;
  2101. }
  2102. // old BSP with ambient, or new BSP with no lighting, convert ambient light to new format or create dummy ambient
  2103. if ( !HasLump( LUMP_LEAF_AMBIENT_INDEX ) )
  2104. {
  2105. // a bunch of legacy maps, have these lumps with garbage versions
  2106. // expect them to be NOT the current version
  2107. if ( HasLump(LUMP_LEAF_AMBIENT_LIGHTING) )
  2108. {
  2109. Assert( LumpVersion( LUMP_LEAF_AMBIENT_LIGHTING ) != LUMP_LEAF_AMBIENT_LIGHTING_VERSION );
  2110. }
  2111. if ( HasLump(LUMP_LEAF_AMBIENT_LIGHTING_HDR) )
  2112. {
  2113. Assert( LumpVersion( LUMP_LEAF_AMBIENT_LIGHTING_HDR ) != LUMP_LEAF_AMBIENT_LIGHTING_VERSION );
  2114. }
  2115. void *pSrcBase = ( ( byte * )g_pBSPHeader + g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_LIGHTING].fileofs );
  2116. CompressedLightCube *pSrc = NULL;
  2117. if ( HasLump( LUMP_LEAF_AMBIENT_LIGHTING ) )
  2118. {
  2119. pSrc = (CompressedLightCube*)pSrcBase;
  2120. }
  2121. g_LeafAmbientIndexLDR.SetCount( numLeafs );
  2122. g_LeafAmbientLightingLDR.SetCount( numLeafs );
  2123. void *pSrcBaseHDR = ( ( byte * )g_pBSPHeader + g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_LIGHTING_HDR].fileofs );
  2124. CompressedLightCube *pSrcHDR = NULL;
  2125. if ( HasLump( LUMP_LEAF_AMBIENT_LIGHTING_HDR ) )
  2126. {
  2127. pSrcHDR = (CompressedLightCube*)pSrcBaseHDR;
  2128. }
  2129. g_LeafAmbientIndexHDR.SetCount( numLeafs );
  2130. g_LeafAmbientLightingHDR.SetCount( numLeafs );
  2131. for ( int i = 0; i < numLeafs; i++ )
  2132. {
  2133. g_LeafAmbientIndexLDR[i].ambientSampleCount = 1;
  2134. g_LeafAmbientIndexLDR[i].firstAmbientSample = i;
  2135. g_LeafAmbientIndexHDR[i].ambientSampleCount = 1;
  2136. g_LeafAmbientIndexHDR[i].firstAmbientSample = i;
  2137. Q_memset( &g_LeafAmbientLightingLDR[i], 0, sizeof(g_LeafAmbientLightingLDR[i]) );
  2138. Q_memset( &g_LeafAmbientLightingHDR[i], 0, sizeof(g_LeafAmbientLightingHDR[i]) );
  2139. if ( pSrc )
  2140. {
  2141. if ( g_bSwapOnLoad )
  2142. {
  2143. g_Swap.SwapFieldsToTargetEndian( &pSrc[i] );
  2144. }
  2145. g_LeafAmbientLightingLDR[i].cube = pSrc[i];
  2146. }
  2147. if ( pSrcHDR )
  2148. {
  2149. if ( g_bSwapOnLoad )
  2150. {
  2151. g_Swap.SwapFieldsToTargetEndian( &pSrcHDR[i] );
  2152. }
  2153. g_LeafAmbientLightingHDR[i].cube = pSrcHDR[i];
  2154. }
  2155. }
  2156. g_Lumps.bLumpParsed[LUMP_LEAF_AMBIENT_LIGHTING] = true;
  2157. g_Lumps.bLumpParsed[LUMP_LEAF_AMBIENT_INDEX] = true;
  2158. g_Lumps.bLumpParsed[LUMP_LEAF_AMBIENT_LIGHTING_HDR] = true;
  2159. g_Lumps.bLumpParsed[LUMP_LEAF_AMBIENT_INDEX_HDR] = true;
  2160. }
  2161. else
  2162. {
  2163. CopyOptionalLump( LUMP_LEAF_AMBIENT_LIGHTING, g_LeafAmbientLightingLDR );
  2164. CopyOptionalLump( LUMP_LEAF_AMBIENT_INDEX, g_LeafAmbientIndexLDR );
  2165. CopyOptionalLump( LUMP_LEAF_AMBIENT_LIGHTING_HDR, g_LeafAmbientLightingHDR );
  2166. CopyOptionalLump( LUMP_LEAF_AMBIENT_INDEX_HDR, g_LeafAmbientIndexHDR );
  2167. }
  2168. }
  2169. int LoadWorldLights( int lumpnum, dworldlight_t *pWorldlights )
  2170. {
  2171. Assert( lumpnum == LUMP_WORLDLIGHTS || lumpnum == LUMP_WORLDLIGHTS_HDR );
  2172. if ( lumpnum != LUMP_WORLDLIGHTS && lumpnum != LUMP_WORLDLIGHTS_HDR )
  2173. {
  2174. Error( "Unexpected worldlight lumpnum %d\n", lumpnum );
  2175. }
  2176. if ( !HasLump( lumpnum ) )
  2177. {
  2178. return 0;
  2179. }
  2180. int count = 0;
  2181. int version = LumpVersion( lumpnum );
  2182. if ( version == 0 )
  2183. {
  2184. // old version
  2185. dworldlight_version0_t *pOldWorldlights = (dworldlight_version0_t *)malloc( g_pBSPHeader->lumps[lumpnum].filelen );
  2186. count = CopyLump( lumpnum, pOldWorldlights );
  2187. for ( int i = 0; i < count; i++ )
  2188. {
  2189. pWorldlights[i].origin = pOldWorldlights[i].origin;
  2190. pWorldlights[i].intensity = pOldWorldlights[i].intensity;
  2191. pWorldlights[i].normal = pOldWorldlights[i].normal;
  2192. pWorldlights[i].shadow_cast_offset.Init( 0.0f, 0.0f, 0.0f );
  2193. pWorldlights[i].cluster = pOldWorldlights[i].cluster;
  2194. pWorldlights[i].type = pOldWorldlights[i].type;
  2195. pWorldlights[i].style = pOldWorldlights[i].style;
  2196. pWorldlights[i].stopdot = pOldWorldlights[i].stopdot;
  2197. pWorldlights[i].stopdot2 = pOldWorldlights[i].stopdot2;
  2198. pWorldlights[i].exponent = pOldWorldlights[i].exponent;
  2199. pWorldlights[i].radius = pOldWorldlights[i].radius;
  2200. pWorldlights[i].constant_attn = pOldWorldlights[i].constant_attn;
  2201. pWorldlights[i].linear_attn = pOldWorldlights[i].linear_attn;
  2202. pWorldlights[i].quadratic_attn = pOldWorldlights[i].quadratic_attn;
  2203. pWorldlights[i].flags = pOldWorldlights[i].flags;
  2204. pWorldlights[i].texinfo = pOldWorldlights[i].texinfo;
  2205. pWorldlights[i].owner = pOldWorldlights[i].owner;
  2206. }
  2207. free( pOldWorldlights );
  2208. }
  2209. else if ( version == LUMP_WORLDLIGHTS_VERSION )
  2210. {
  2211. count = CopyLump( lumpnum, pWorldlights );
  2212. }
  2213. else
  2214. {
  2215. Error( "Unexpected worldlights lump version %d\n", version );
  2216. }
  2217. return count;
  2218. }
  2219. void ValidateHeader( const char *filename, const BSPHeader_t *pHeader )
  2220. {
  2221. if ( pHeader->ident != IDBSPHEADER )
  2222. {
  2223. Error ("%s is not a IBSP file", filename);
  2224. }
  2225. if ( pHeader->m_nVersion < MINBSPVERSION || pHeader->m_nVersion > BSPVERSION )
  2226. {
  2227. Error ("%s is version %i, not %i", filename, pHeader->m_nVersion, BSPVERSION);
  2228. }
  2229. }
  2230. //-----------------------------------------------------------------------------
  2231. // Low level BSP opener for external parsing. Parses headers, but nothing else.
  2232. // You must close the BSP, via CloseBSPFile().
  2233. //-----------------------------------------------------------------------------
  2234. void OpenBSPFile( const char *filename )
  2235. {
  2236. Lumps_Init();
  2237. // load the file header
  2238. LoadFile( filename, (void **)&g_pBSPHeader );
  2239. if ( g_bSwapOnLoad )
  2240. {
  2241. g_Swap.ActivateByteSwapping( true );
  2242. g_Swap.SwapFieldsToTargetEndian( g_pBSPHeader );
  2243. }
  2244. ValidateHeader( filename, g_pBSPHeader );
  2245. g_MapRevision = g_pBSPHeader->mapRevision;
  2246. g_LevelFlags = 0;
  2247. if ( HasLump( LUMP_MAP_FLAGS ) )
  2248. {
  2249. dflagslump_t flagsLump;
  2250. memcpy( &flagsLump, (dflagslump_t *)((byte *)g_pBSPHeader + g_pBSPHeader->lumps[LUMP_MAP_FLAGS].fileofs ), sizeof( flagsLump ) );
  2251. if ( g_bSwapOnLoad )
  2252. {
  2253. g_Swap.SwapFieldsToTargetEndian( &flagsLump );
  2254. }
  2255. g_LevelFlags = flagsLump.m_LevelFlags;
  2256. }
  2257. }
  2258. //-----------------------------------------------------------------------------
  2259. // CloseBSPFile
  2260. //-----------------------------------------------------------------------------
  2261. void CloseBSPFile( void )
  2262. {
  2263. free( g_pBSPHeader );
  2264. g_pBSPHeader = NULL;
  2265. }
  2266. //-----------------------------------------------------------------------------
  2267. // LoadBSPFile
  2268. //-----------------------------------------------------------------------------
  2269. void LoadBSPFile( const char *filename )
  2270. {
  2271. OpenBSPFile( filename );
  2272. nummodels = CopyLump( LUMP_MODELS, dmodels );
  2273. numvertexes = CopyLump( LUMP_VERTEXES, dvertexes );
  2274. numplanes = CopyLump( LUMP_PLANES, dplanes );
  2275. numleafs = LoadLeafs();
  2276. numnodes = CopyLump( LUMP_NODES, dnodes );
  2277. CopyLump( LUMP_TEXINFO, texinfo );
  2278. numtexdata = CopyLump( LUMP_TEXDATA, dtexdata );
  2279. CopyLump( LUMP_DISPINFO, g_dispinfo );
  2280. CopyLump( LUMP_DISP_VERTS, g_DispVerts );
  2281. CopyLump( LUMP_DISP_TRIS, g_DispTris );
  2282. CopyLump( LUMP_DISP_MULTIBLEND, g_DispMultiBlend );
  2283. CopyLump( FIELD_CHARACTER, LUMP_DISP_LIGHTMAP_SAMPLE_POSITIONS, g_DispLightmapSamplePositions );
  2284. CopyLump( LUMP_FACE_MACRO_TEXTURE_INFO, g_FaceMacroTextureInfos );
  2285. numfaces = CopyLump(LUMP_FACES, dfaces, LUMP_FACES_VERSION);
  2286. if ( HasLump( LUMP_FACES_HDR ) )
  2287. numfaces_hdr = CopyLump( LUMP_FACES_HDR, dfaces_hdr, LUMP_FACES_VERSION );
  2288. else
  2289. numfaces_hdr = 0;
  2290. CopyOptionalLump( LUMP_FACEIDS, dfaceids );
  2291. g_numprimitives = CopyLump( LUMP_PRIMITIVES, g_primitives );
  2292. g_numprimverts = CopyLump( LUMP_PRIMVERTS, g_primverts );
  2293. g_numprimindices = CopyLump( FIELD_SHORT, LUMP_PRIMINDICES, g_primindices );
  2294. numorigfaces = CopyLump( LUMP_ORIGINALFACES, dorigfaces ); // original faces
  2295. numleaffaces = CopyLump( FIELD_SHORT, LUMP_LEAFFACES, dleaffaces );
  2296. numleafbrushes = CopyLump( FIELD_SHORT, LUMP_LEAFBRUSHES, dleafbrushes );
  2297. CopyLump( FIELD_SHORT, LUMP_FACEBRUSHES, dfacebrushes );
  2298. CopyLump( LUMP_FACEBRUSHLIST, dfacebrushlists );
  2299. numsurfedges = CopyLump( FIELD_INTEGER, LUMP_SURFEDGES, dsurfedges );
  2300. numedges = CopyLump( LUMP_EDGES, dedges );
  2301. numbrushes = CopyLump( LUMP_BRUSHES, dbrushes );
  2302. numbrushsides = CopyLump( LUMP_BRUSHSIDES, dbrushsides );
  2303. numareas = CopyLump( LUMP_AREAS, dareas );
  2304. numareaportals = CopyLump( LUMP_AREAPORTALS, dareaportals );
  2305. visdatasize = CopyLump ( FIELD_CHARACTER, LUMP_VISIBILITY, dvisdata );
  2306. CopyOptionalLump( FIELD_CHARACTER, LUMP_LIGHTING, dlightdataLDR, LUMP_LIGHTING_VERSION );
  2307. CopyOptionalLump( FIELD_CHARACTER, LUMP_LIGHTING_HDR, dlightdataHDR, LUMP_LIGHTING_VERSION );
  2308. LoadLeafAmbientLighting( numleafs );
  2309. CopyLump( FIELD_CHARACTER, LUMP_ENTITIES, dentdata );
  2310. numworldlightsLDR = LoadWorldLights( LUMP_WORLDLIGHTS, dworldlightsLDR );
  2311. numworldlightsHDR = LoadWorldLights( LUMP_WORLDLIGHTS_HDR, dworldlightsHDR );
  2312. numleafwaterdata = CopyLump( LUMP_LEAFWATERDATA, dleafwaterdata );
  2313. g_PhysCollideSize = CopyVariableLump<byte>( FIELD_CHARACTER, LUMP_PHYSCOLLIDE, (void**)&g_pPhysCollide );
  2314. g_PhysLevelSize = CopyVariableLump<byte>( FIELD_CHARACTER, LUMP_PHYSLEVEL, (void**)&g_pPhysLevel );
  2315. g_PhysDispSize = CopyVariableLump<byte>( FIELD_CHARACTER, LUMP_PHYSDISP, (void**)&g_pPhysDisp );
  2316. g_numvertnormals = CopyLump( FIELD_VECTOR, LUMP_VERTNORMALS, (float*)g_vertnormals );
  2317. g_numvertnormalindices = CopyLump( FIELD_SHORT, LUMP_VERTNORMALINDICES, g_vertnormalindices );
  2318. g_nClipPortalVerts = CopyLump( FIELD_VECTOR, LUMP_CLIPPORTALVERTS, (float*)g_ClipPortalVerts );
  2319. g_nCubemapSamples = CopyLump( LUMP_CUBEMAPS, g_CubemapSamples );
  2320. CopyLump( FIELD_CHARACTER, LUMP_TEXDATA_STRING_DATA, g_TexDataStringData );
  2321. CopyLump( FIELD_INTEGER, LUMP_TEXDATA_STRING_TABLE, g_TexDataStringTable );
  2322. g_nOverlayCount = CopyLump( LUMP_OVERLAYS, g_Overlays );
  2323. g_nWaterOverlayCount = CopyLump( LUMP_WATEROVERLAYS, g_WaterOverlays );
  2324. CopyLump( LUMP_OVERLAY_FADES, g_OverlayFades );
  2325. CopyLump( LUMP_OVERLAY_SYSTEM_LEVELS, g_OverlaySystemLevels );
  2326. dflagslump_t flags_lump;
  2327. if ( HasLump( LUMP_MAP_FLAGS ) )
  2328. CopyLump ( LUMP_MAP_FLAGS, &flags_lump );
  2329. else
  2330. memset( &flags_lump, 0, sizeof( flags_lump ) ); // default flags to 0
  2331. g_LevelFlags = flags_lump.m_LevelFlags;
  2332. LoadOcclusionLump();
  2333. CopyLump( FIELD_SHORT, LUMP_LEAFMINDISTTOWATER, g_LeafMinDistToWater );
  2334. /*
  2335. int crap;
  2336. for( crap = 0; crap < g_nBSPStringTable; crap++ )
  2337. {
  2338. Msg( "stringtable %d", ( int )crap );
  2339. Msg( " %d:", ( int )g_BSPStringTable[crap] );
  2340. puts( &g_BSPStringData[g_BSPStringTable[crap]] );
  2341. puts( "\n" );
  2342. }
  2343. */
  2344. // Load PAK file lump into appropriate data structure
  2345. byte *pakbuffer = NULL;
  2346. int paksize = CopyVariableLump<byte>( FIELD_CHARACTER, LUMP_PAKFILE, ( void ** )&pakbuffer );
  2347. if ( paksize > 0 )
  2348. {
  2349. GetPakFile()->ActivateByteSwapping( IsX360() );
  2350. GetPakFile()->ParseFromBuffer( pakbuffer, paksize );
  2351. }
  2352. else
  2353. {
  2354. GetPakFile()->Reset();
  2355. }
  2356. free( pakbuffer );
  2357. g_GameLumps.ParseGameLump( g_pBSPHeader );
  2358. // NOTE: Do NOT call CopyLump after Lumps_Parse() it parses all un-Copied lumps
  2359. // parse any additional lumps
  2360. Lumps_Parse();
  2361. // everything has been copied out
  2362. CloseBSPFile();
  2363. g_Swap.ActivateByteSwapping( false );
  2364. }
  2365. //-----------------------------------------------------------------------------
  2366. // Reset any state.
  2367. //-----------------------------------------------------------------------------
  2368. void UnloadBSPFile()
  2369. {
  2370. nummodels = 0;
  2371. numvertexes = 0;
  2372. numplanes = 0;
  2373. numleafs = 0;
  2374. #if defined( BSP_USE_LESS_MEMORY )
  2375. if ( dleafs )
  2376. {
  2377. free( dleafs );
  2378. dleafs = NULL;
  2379. }
  2380. #endif
  2381. numnodes = 0;
  2382. texinfo.Purge();
  2383. numtexdata = 0;
  2384. g_dispinfo.Purge();
  2385. g_DispVerts.Purge();
  2386. g_DispTris.Purge();
  2387. g_DispMultiBlend.Purge();
  2388. g_DispLightmapSamplePositions.Purge();
  2389. g_FaceMacroTextureInfos.Purge();
  2390. numfaces = 0;
  2391. numfaces_hdr = 0;
  2392. dfaceids.Purge();
  2393. dfacebrushes.Purge();
  2394. dfacebrushlists.Purge();
  2395. g_numprimitives = 0;
  2396. g_numprimverts = 0;
  2397. g_numprimindices = 0;
  2398. numorigfaces = 0;
  2399. numleaffaces = 0;
  2400. numleafbrushes = 0;
  2401. numsurfedges = 0;
  2402. numedges = 0;
  2403. numbrushes = 0;
  2404. numbrushsides = 0;
  2405. numareas = 0;
  2406. numareaportals = 0;
  2407. visdatasize = 0;
  2408. dlightdataLDR.Purge();
  2409. dlightdataHDR.Purge();
  2410. g_LeafAmbientLightingLDR.Purge();
  2411. g_LeafAmbientLightingHDR.Purge();
  2412. g_LeafAmbientIndexHDR.Purge();
  2413. g_LeafAmbientIndexLDR.Purge();
  2414. dentdata.Purge();
  2415. numworldlightsLDR = 0;
  2416. numworldlightsHDR = 0;
  2417. numleafwaterdata = 0;
  2418. if ( g_pPhysCollide )
  2419. {
  2420. free( g_pPhysCollide );
  2421. g_pPhysCollide = NULL;
  2422. }
  2423. g_PhysCollideSize = 0;
  2424. if ( g_pPhysDisp )
  2425. {
  2426. free( g_pPhysDisp );
  2427. g_pPhysDisp = NULL;
  2428. }
  2429. g_PhysDispSize = 0;
  2430. g_numvertnormals = 0;
  2431. g_numvertnormalindices = 0;
  2432. g_nClipPortalVerts = 0;
  2433. g_nCubemapSamples = 0;
  2434. g_TexDataStringData.Purge();
  2435. g_TexDataStringTable.Purge();
  2436. g_nOverlayCount = 0;
  2437. g_nWaterOverlayCount = 0;
  2438. g_LevelFlags = 0;
  2439. g_OccluderData.Purge();
  2440. g_OccluderPolyData.Purge();
  2441. g_OccluderVertexIndices.Purge();
  2442. g_GameLumps.DestroyAllGameLumps();
  2443. for ( int i = 0; i < HEADER_LUMPS; i++ )
  2444. {
  2445. if ( g_Lumps.pLumps[i] )
  2446. {
  2447. free( g_Lumps.pLumps[i] );
  2448. g_Lumps.pLumps[i] = NULL;
  2449. }
  2450. }
  2451. ReleasePakFileLumps();
  2452. }
  2453. //-----------------------------------------------------------------------------
  2454. // LoadBSPFileFilesystemOnly
  2455. //-----------------------------------------------------------------------------
  2456. void LoadBSPFile_FileSystemOnly( const char *filename )
  2457. {
  2458. Lumps_Init();
  2459. //
  2460. // load the file header
  2461. //
  2462. LoadFile( filename, (void **)&g_pBSPHeader );
  2463. ValidateHeader( filename, g_pBSPHeader );
  2464. // Load PAK file lump into appropriate data structure
  2465. byte *pakbuffer = NULL;
  2466. int paksize = CopyVariableLump<byte>( FIELD_CHARACTER, LUMP_PAKFILE, ( void ** )&pakbuffer, 1 );
  2467. if ( paksize > 0 )
  2468. {
  2469. GetPakFile()->ParseFromBuffer( pakbuffer, paksize );
  2470. }
  2471. else
  2472. {
  2473. GetPakFile()->Reset();
  2474. }
  2475. free( pakbuffer );
  2476. // everything has been copied out
  2477. free( g_pBSPHeader );
  2478. g_pBSPHeader = NULL;
  2479. }
  2480. void ExtractZipFileFromBSP( char *pBSPFileName, char *pZipFileName )
  2481. {
  2482. Lumps_Init();
  2483. //
  2484. // load the file header
  2485. //
  2486. LoadFile( pBSPFileName, (void **)&g_pBSPHeader);
  2487. ValidateHeader( pBSPFileName, g_pBSPHeader );
  2488. byte *pakbuffer = NULL;
  2489. int paksize = CopyVariableLump<byte>( FIELD_CHARACTER, LUMP_PAKFILE, ( void ** )&pakbuffer );
  2490. if ( paksize > 0 )
  2491. {
  2492. FILE *fp;
  2493. #if defined( POSIX )
  2494. fp = fopen( pZipFileName, "wb" );
  2495. #else
  2496. fopen_s( &fp, pZipFileName, "wb" );
  2497. #endif
  2498. if( !fp )
  2499. {
  2500. fprintf( stderr, "can't open %s\n", pZipFileName );
  2501. return;
  2502. }
  2503. fwrite( pakbuffer, paksize, 1, fp );
  2504. fclose( fp );
  2505. }
  2506. else
  2507. {
  2508. fprintf( stderr, "zip file is zero length!\n" );
  2509. }
  2510. }
  2511. /*
  2512. =============
  2513. LoadBSPFileTexinfo
  2514. Only loads the texinfo lump, so qdata can scan for textures
  2515. =============
  2516. */
  2517. void LoadBSPFileTexinfo( const char *filename )
  2518. {
  2519. FILE *f;
  2520. int length, ofs;
  2521. g_pBSPHeader = new BSPHeader_t;
  2522. #if defined( POSIX )
  2523. f = fopen( filename, "rb" );
  2524. #else
  2525. fopen_s( &f, filename, "rb" );
  2526. #endif
  2527. fread( g_pBSPHeader, sizeof( *g_pBSPHeader ), 1, f);
  2528. ValidateHeader( filename, g_pBSPHeader );
  2529. length = g_pBSPHeader->lumps[LUMP_TEXINFO].filelen;
  2530. ofs = g_pBSPHeader->lumps[LUMP_TEXINFO].fileofs;
  2531. int nCount = length / sizeof(texinfo_t);
  2532. texinfo.Purge();
  2533. texinfo.AddMultipleToTail( nCount );
  2534. fseek( f, ofs, SEEK_SET );
  2535. fread( texinfo.Base(), length, 1, f );
  2536. fclose( f );
  2537. // everything has been copied out
  2538. free( g_pBSPHeader );
  2539. g_pBSPHeader = NULL;
  2540. }
  2541. static void AddLumpInternal( int lumpnum, void *data, int len, int version, int nAlignment = 1 )
  2542. {
  2543. Assert( IsPowerOfTwo( nAlignment ) );
  2544. lump_t *lump;
  2545. g_Lumps.size[lumpnum] = 0; // mark it written
  2546. lump = &g_pBSPHeader->lumps[lumpnum];
  2547. // pre-align to desired write position
  2548. // this may be increased alignment as needed by lumps
  2549. AlignFilePosition( g_hBSPFile, nAlignment );
  2550. lump->fileofs = g_pFileSystem->Tell( g_hBSPFile );
  2551. lump->filelen = len;
  2552. lump->version = version;
  2553. lump->fourCC[0] = ( char )0;
  2554. lump->fourCC[1] = ( char )0;
  2555. lump->fourCC[2] = ( char )0;
  2556. lump->fourCC[3] = ( char )0;
  2557. SafeWrite( g_hBSPFile, data, len );
  2558. // pad out to the next default aligned position
  2559. AlignFilePosition( g_hBSPFile, LUMP_ALIGNMENT );
  2560. }
  2561. template< class T >
  2562. static void SwapInPlace( T *pData, int count )
  2563. {
  2564. if ( !pData )
  2565. return;
  2566. // use the datadesc to swap the fields in place
  2567. g_Swap.SwapFieldsToTargetEndian<T>( (T*)pData, pData, count );
  2568. }
  2569. template< class T >
  2570. static void SwapInPlace( int fieldType, T *pData, int count )
  2571. {
  2572. if ( !pData )
  2573. return;
  2574. // swap the data in place
  2575. g_Swap.SwapBufferToTargetEndian<T>( (T*)pData, (T*)pData, count );
  2576. }
  2577. //-----------------------------------------------------------------------------
  2578. // Add raw data chunk to file (not a lump)
  2579. //-----------------------------------------------------------------------------
  2580. template< class T >
  2581. static void WriteData( int fieldType, T *pData, int count )
  2582. {
  2583. if ( g_bSwapOnWrite )
  2584. {
  2585. SwapInPlace( fieldType, pData, count );
  2586. }
  2587. SafeWrite( g_hBSPFile, pData, count * sizeof(T) );
  2588. }
  2589. template< class T >
  2590. static void WriteData( T *pData, int count )
  2591. {
  2592. if ( g_bSwapOnWrite )
  2593. {
  2594. SwapInPlace( pData, count );
  2595. }
  2596. SafeWrite( g_hBSPFile, pData, count * sizeof(T) );
  2597. }
  2598. //-----------------------------------------------------------------------------
  2599. // Add Lump of object types with datadescs
  2600. //-----------------------------------------------------------------------------
  2601. template< class T >
  2602. static void AddLump( int lumpnum, T *pData, int count, int version, int nAlignment )
  2603. {
  2604. AddLumpInternal( lumpnum, pData, count * sizeof(T), version, nAlignment );
  2605. }
  2606. template< class T >
  2607. static void AddLump( int lumpnum, CUtlVector<T> &data, int version, int nAlignment )
  2608. {
  2609. AddLumpInternal( lumpnum, data.Base(), data.Count() * sizeof(T), version, nAlignment );
  2610. }
  2611. /*
  2612. =============
  2613. WriteBSPFile
  2614. Swaps the bsp file in place, so it should not be referenced again
  2615. =============
  2616. */
  2617. void WriteBSPFile( const char *filename, char *pUnused )
  2618. {
  2619. if ( texinfo.Count() > MAX_MAP_TEXINFO )
  2620. {
  2621. Error( "Map has too many texinfos (has %d, can have at most %d)\n", texinfo.Count(), MAX_MAP_TEXINFO );
  2622. return;
  2623. }
  2624. BSPHeader_t outHeader;
  2625. g_pBSPHeader = &outHeader;
  2626. memset( g_pBSPHeader, 0, sizeof( BSPHeader_t ) );
  2627. g_pBSPHeader->ident = IDBSPHEADER;
  2628. g_pBSPHeader->m_nVersion = BSPVERSION;
  2629. g_pBSPHeader->mapRevision = g_MapRevision;
  2630. g_hBSPFile = SafeOpenWrite( filename );
  2631. WriteData( g_pBSPHeader ); // overwritten later
  2632. // start on aligned boundary
  2633. AlignFilePosition( g_hBSPFile, LUMP_ALIGNMENT );
  2634. // NOTE: Write these in the order the engine will read them
  2635. dflagslump_t flags_lump;
  2636. flags_lump.m_LevelFlags = g_LevelFlags;
  2637. AddLump( LUMP_MAP_FLAGS, &flags_lump, 1 );
  2638. // first write texture data
  2639. AddLump( LUMP_TEXINFO, texinfo );
  2640. AddLump( LUMP_TEXDATA, dtexdata, numtexdata );
  2641. AddLump( LUMP_TEXDATA_STRING_DATA, g_TexDataStringData );
  2642. AddLump( LUMP_TEXDATA_STRING_TABLE, g_TexDataStringTable );
  2643. // Now write collision data
  2644. AddLump( LUMP_LEAFS, dleafs, numleafs, LUMP_LEAFS_VERSION );
  2645. AddLump( LUMP_LEAFBRUSHES, dleafbrushes, numleafbrushes );
  2646. AddLump( LUMP_PLANES, dplanes, numplanes );
  2647. AddLump( LUMP_BRUSHES, dbrushes, numbrushes );
  2648. AddLump( LUMP_BRUSHSIDES, dbrushsides, numbrushsides );
  2649. AddLump( LUMP_MODELS, dmodels, nummodels );
  2650. AddLump( LUMP_NODES, dnodes, numnodes );
  2651. // visibility data
  2652. AddLump( LUMP_AREAS, dareas, numareas );
  2653. AddLump( LUMP_AREAPORTALS, dareaportals, numareaportals );
  2654. AddLump( LUMP_VISIBILITY, dvisdata, visdatasize );
  2655. // entity text
  2656. AddLump( LUMP_ENTITIES, dentdata );
  2657. if ( g_pPhysCollide )
  2658. {
  2659. AddLump( LUMP_PHYSCOLLIDE, g_pPhysCollide, g_PhysCollideSize );
  2660. }
  2661. if ( g_pPhysLevel )
  2662. {
  2663. // PhysLevel is 16-byte aligned (will be 128-byte aligned for PS/3)
  2664. AddLump( LUMP_PHYSLEVEL, g_pPhysLevel, g_PhysLevelSize, LUMP_PHYSLEVEL_ALIGNMENT );
  2665. }
  2666. AddLump( LUMP_DISPINFO, g_dispinfo );
  2667. AddLump( LUMP_VERTEXES, dvertexes, numvertexes );
  2668. AddLump( LUMP_EDGES, dedges, numedges );
  2669. AddLump( LUMP_SURFEDGES, dsurfedges, numsurfedges );
  2670. AddLump( LUMP_FACES, dfaces, numfaces, LUMP_FACES_VERSION );
  2671. if ( numfaces_hdr )
  2672. {
  2673. AddLump( LUMP_FACES_HDR, dfaces_hdr, numfaces_hdr, LUMP_FACES_VERSION );
  2674. }
  2675. AddLump( LUMP_DISP_VERTS, g_DispVerts );
  2676. AddLump( LUMP_DISP_TRIS, g_DispTris );
  2677. AddLump( LUMP_DISP_MULTIBLEND, g_DispMultiBlend );
  2678. if ( g_pPhysDisp )
  2679. {
  2680. AddLump ( LUMP_PHYSDISP, g_pPhysDisp, g_PhysDispSize );
  2681. }
  2682. AddOcclusionLump();
  2683. AddLump( LUMP_LIGHTING, dlightdataLDR, LUMP_LIGHTING_VERSION );
  2684. AddLump( LUMP_LIGHTING_HDR, dlightdataHDR, LUMP_LIGHTING_VERSION );
  2685. AddLump( LUMP_PRIMITIVES, g_primitives, g_numprimitives );
  2686. AddLump( LUMP_PRIMVERTS, g_primverts, g_numprimverts );
  2687. AddLump( LUMP_PRIMINDICES, g_primindices, g_numprimindices );
  2688. AddLump( LUMP_VERTNORMALS, (float*)g_vertnormals, g_numvertnormals * 3 );
  2689. AddLump( LUMP_VERTNORMALINDICES, g_vertnormalindices, g_numvertnormalindices );
  2690. AddLump( LUMP_LEAF_AMBIENT_LIGHTING, g_LeafAmbientLightingLDR, LUMP_LEAF_AMBIENT_LIGHTING_VERSION );
  2691. AddLump( LUMP_LEAF_AMBIENT_INDEX, g_LeafAmbientIndexLDR );
  2692. AddLump( LUMP_LEAF_AMBIENT_INDEX_HDR, g_LeafAmbientIndexHDR );
  2693. AddLump( LUMP_LEAF_AMBIENT_LIGHTING_HDR, g_LeafAmbientLightingHDR, LUMP_LEAF_AMBIENT_LIGHTING_VERSION );
  2694. AddLump( LUMP_LEAFFACES, dleaffaces, numleaffaces );
  2695. AddLump( LUMP_LEAFWATERDATA, dleafwaterdata, numleafwaterdata );
  2696. AddLump( LUMP_OVERLAYS, g_Overlays, g_nOverlayCount );
  2697. AddLump( LUMP_WATEROVERLAYS, g_WaterOverlays, g_nWaterOverlayCount );
  2698. AddLump( LUMP_OVERLAY_FADES, g_OverlayFades, g_nOverlayCount );
  2699. AddLump( LUMP_OVERLAY_SYSTEM_LEVELS, g_OverlaySystemLevels, g_nOverlayCount );
  2700. AddLump( LUMP_LEAFMINDISTTOWATER, g_LeafMinDistToWater, numleafs );
  2701. AddLump( LUMP_CUBEMAPS, g_CubemapSamples, g_nCubemapSamples );
  2702. AddLump( LUMP_CLIPPORTALVERTS, (float*)g_ClipPortalVerts, g_nClipPortalVerts * 3 );
  2703. AddLump( LUMP_WORLDLIGHTS, dworldlightsLDR, numworldlightsLDR, LUMP_WORLDLIGHTS_VERSION );
  2704. AddLump( LUMP_WORLDLIGHTS_HDR, dworldlightsHDR, numworldlightsHDR, LUMP_WORLDLIGHTS_VERSION );
  2705. AddLump( LUMP_DISP_LIGHTMAP_SAMPLE_POSITIONS, g_DispLightmapSamplePositions );
  2706. AddLump( LUMP_FACE_MACRO_TEXTURE_INFO, g_FaceMacroTextureInfos );
  2707. AddLump ( LUMP_FACEIDS, dfaceids, numfaceids );
  2708. AddLump ( LUMP_FACEBRUSHES, dfacebrushes );
  2709. AddLump ( LUMP_FACEBRUSHLIST, dfacebrushlists );
  2710. AddLump( LUMP_ORIGINALFACES, dorigfaces, numorigfaces ); // original faces lump
  2711. // NOTE: This is just for debugging, so it is disabled in release maps
  2712. #if 0
  2713. // add the vis portals to the BSP for visualization
  2714. AddLump( LUMP_PORTALS, dportals, numportals );
  2715. AddLump( LUMP_CLUSTERS, dclusters, numclusters );
  2716. AddLump( LUMP_PORTALVERTS, dportalverts, numportalverts );
  2717. AddLump( LUMP_CLUSTERPORTALS, dclusterportals, numclusterportals );
  2718. #endif
  2719. AddGameLumps();
  2720. // Write pakfile lump to disk
  2721. WritePakFileLump();
  2722. // NOTE: Do NOT call AddLump after Lumps_Write() it writes all un-Added lumps
  2723. // write any additional lumps
  2724. Lumps_Write();
  2725. g_pFileSystem->Seek( g_hBSPFile, 0, FILESYSTEM_SEEK_HEAD );
  2726. WriteData( g_pBSPHeader );
  2727. g_pFileSystem->Close( g_hBSPFile );
  2728. }
  2729. // Generate the next clear lump filename for the bsp file
  2730. bool GenerateNextLumpFileName( const char *bspfilename, char *lumpfilename, int buffsize )
  2731. {
  2732. for (int i = 0; i < MAX_LUMPFILES; i++)
  2733. {
  2734. GenerateLumpFileName( bspfilename, lumpfilename, buffsize, i );
  2735. if ( !g_pFileSystem->FileExists( lumpfilename ) )
  2736. return true;
  2737. }
  2738. return false;
  2739. }
  2740. void WriteLumpToFile( char *filename, int lump )
  2741. {
  2742. if ( !HasLump(lump) )
  2743. return;
  2744. char lumppre[MAX_PATH];
  2745. if ( !GenerateNextLumpFileName( filename, lumppre, MAX_PATH ) )
  2746. {
  2747. Warning( "Failed to find valid lump filename for bsp %s.\n", filename );
  2748. return;
  2749. }
  2750. // Open the file
  2751. FileHandle_t lumpfile = g_pFileSystem->Open(lumppre, "wb");
  2752. if ( !lumpfile )
  2753. {
  2754. Error ("Error opening %s! (Check for write enable)\n",filename);
  2755. return;
  2756. }
  2757. int ofs = g_pBSPHeader->lumps[lump].fileofs;
  2758. int length = g_pBSPHeader->lumps[lump].filelen;
  2759. // Write the header
  2760. lumpfileheader_t lumpHeader;
  2761. lumpHeader.lumpID = lump;
  2762. lumpHeader.lumpVersion = LumpVersion(lump);
  2763. lumpHeader.lumpLength = length;
  2764. lumpHeader.mapRevision = LittleLong( g_MapRevision );
  2765. lumpHeader.lumpOffset = sizeof(lumpfileheader_t); // Lump starts after the header
  2766. SafeWrite (lumpfile, &lumpHeader, sizeof(lumpfileheader_t));
  2767. // Write the lump
  2768. SafeWrite (lumpfile, (byte *)g_pBSPHeader + ofs, length);
  2769. }
  2770. //============================================================================
  2771. #define ENTRIES(a) (sizeof(a)/sizeof(*(a)))
  2772. #define ENTRYSIZE(a) (sizeof(*(a)))
  2773. int ArrayUsage( char *szItem, int items, int maxitems, int itemsize )
  2774. {
  2775. float percentage = maxitems ? items * 100.0 / maxitems : 0.0;
  2776. Msg("%-17.17s %8i/%-8i %8i/%-8i (%4.1f%%) ",
  2777. szItem, items, maxitems, items * itemsize, maxitems * itemsize, percentage );
  2778. if ( percentage > 80.0 )
  2779. Msg( "VERY FULL!\n" );
  2780. else if ( percentage > 95.0 )
  2781. Msg( "SIZE DANGER!\n" );
  2782. else if ( percentage > 99.9 )
  2783. Msg( "SIZE OVERFLOW!!!\n" );
  2784. else
  2785. Msg( "\n" );
  2786. return items * itemsize;
  2787. }
  2788. int GlobUsage( char *szItem, int itemstorage, int maxstorage )
  2789. {
  2790. float percentage = maxstorage ? itemstorage * 100.0 / maxstorage : 0.0;
  2791. Msg("%-17.17s [variable] %8i/%-8i (%4.1f%%) ",
  2792. szItem, itemstorage, maxstorage, percentage );
  2793. if ( percentage > 80.0 )
  2794. Msg( "VERY FULL!\n" );
  2795. else if ( percentage > 95.0 )
  2796. Msg( "SIZE DANGER!\n" );
  2797. else if ( percentage > 99.9 )
  2798. Msg( "SIZE OVERFLOW!!!\n" );
  2799. else
  2800. Msg( "\n" );
  2801. return itemstorage;
  2802. }
  2803. /*
  2804. =============
  2805. PrintBSPFileSizes
  2806. Dumps info about current file
  2807. =============
  2808. */
  2809. void PrintBSPFileSizes (void)
  2810. {
  2811. int totalmemory = 0;
  2812. // if (!num_entities)
  2813. // ParseEntities ();
  2814. Msg("\n");
  2815. Msg( "%-17s %16s %16s %9s \n", "Object names", "Objects/Maxobjs", "Memory / Maxmem", "Fullness" );
  2816. Msg( "%-17s %16s %16s %9s \n", "------------", "---------------", "---------------", "--------" );
  2817. totalmemory += ArrayUsage( "models", nummodels, ENTRIES(dmodels), ENTRYSIZE(dmodels) );
  2818. totalmemory += ArrayUsage( "brushes", numbrushes, ENTRIES(dbrushes), ENTRYSIZE(dbrushes) );
  2819. totalmemory += ArrayUsage( "brushsides", numbrushsides, ENTRIES(dbrushsides), ENTRYSIZE(dbrushsides) );
  2820. totalmemory += ArrayUsage( "planes", numplanes, ENTRIES(dplanes), ENTRYSIZE(dplanes) );
  2821. totalmemory += ArrayUsage( "vertexes", numvertexes, ENTRIES(dvertexes), ENTRYSIZE(dvertexes) );
  2822. totalmemory += ArrayUsage( "nodes", numnodes, ENTRIES(dnodes), ENTRYSIZE(dnodes) );
  2823. totalmemory += ArrayUsage( "texinfos", texinfo.Count(),MAX_MAP_TEXINFO, sizeof(texinfo_t) );
  2824. totalmemory += ArrayUsage( "texdata", numtexdata, ENTRIES(dtexdata), ENTRYSIZE(dtexdata) );
  2825. totalmemory += ArrayUsage( "dispinfos", g_dispinfo.Count(), 0, sizeof( ddispinfo_t ) );
  2826. totalmemory += ArrayUsage( "disp_verts", g_DispVerts.Count(), 0, sizeof( g_DispVerts[0] ) );
  2827. totalmemory += ArrayUsage( "disp_tris", g_DispTris.Count(), 0, sizeof( g_DispTris[0] ) );
  2828. totalmemory += ArrayUsage( "disp_multiblend", g_DispMultiBlend.Count(), 0, sizeof( g_DispMultiBlend[0] ) );
  2829. totalmemory += ArrayUsage( "disp_lmsamples", g_DispLightmapSamplePositions.Count(),0,sizeof( g_DispLightmapSamplePositions[0] ) );
  2830. totalmemory += ArrayUsage( "faces", numfaces, ENTRIES(dfaces), ENTRYSIZE(dfaces) );
  2831. totalmemory += ArrayUsage( "hdr faces", numfaces_hdr, ENTRIES(dfaces_hdr), ENTRYSIZE(dfaces_hdr) );
  2832. totalmemory += ArrayUsage( "origfaces", numorigfaces, ENTRIES(dorigfaces), ENTRYSIZE(dorigfaces) ); // original faces
  2833. totalmemory += ArrayUsage( "facebrushes", dfacebrushes.Count(), 0, ENTRYSIZE(dfacebrushes.Base()) );
  2834. totalmemory += ArrayUsage( "facebrushlists",dfacebrushlists.Count(), 0, ENTRYSIZE(dfacebrushlists.Base()) );
  2835. totalmemory += ArrayUsage( "leaves", numleafs, ENTRIES(dleafs), ENTRYSIZE(dleafs) );
  2836. totalmemory += ArrayUsage( "leaffaces", numleaffaces, ENTRIES(dleaffaces), ENTRYSIZE(dleaffaces) );
  2837. totalmemory += ArrayUsage( "leafbrushes", numleafbrushes, ENTRIES(dleafbrushes), ENTRYSIZE(dleafbrushes) );
  2838. totalmemory += ArrayUsage( "areas", numareas, ENTRIES(dareas), ENTRYSIZE(dareas) );
  2839. totalmemory += ArrayUsage( "surfedges", numsurfedges, ENTRIES(dsurfedges), ENTRYSIZE(dsurfedges) );
  2840. totalmemory += ArrayUsage( "edges", numedges, ENTRIES(dedges), ENTRYSIZE(dedges) );
  2841. totalmemory += ArrayUsage( "LDR worldlights", numworldlightsLDR, ENTRIES(dworldlightsLDR), ENTRYSIZE(dworldlightsLDR) );
  2842. totalmemory += ArrayUsage( "HDR worldlights", numworldlightsHDR, ENTRIES(dworldlightsHDR), ENTRYSIZE(dworldlightsHDR) );
  2843. totalmemory += ArrayUsage( "leafwaterdata", numleafwaterdata,ENTRIES(dleafwaterdata), ENTRYSIZE(dleafwaterdata) );
  2844. totalmemory += ArrayUsage( "waterstrips", g_numprimitives,ENTRIES(g_primitives), ENTRYSIZE(g_primitives) );
  2845. totalmemory += ArrayUsage( "waterverts", g_numprimverts, ENTRIES(g_primverts), ENTRYSIZE(g_primverts) );
  2846. totalmemory += ArrayUsage( "waterindices", g_numprimindices,ENTRIES(g_primindices),ENTRYSIZE(g_primindices) );
  2847. totalmemory += ArrayUsage( "cubemapsamples", g_nCubemapSamples,ENTRIES(g_CubemapSamples),ENTRYSIZE(g_CubemapSamples) );
  2848. totalmemory += ArrayUsage( "overlays", g_nOverlayCount, ENTRIES(g_Overlays), ENTRYSIZE(g_Overlays) );
  2849. totalmemory += GlobUsage( "LDR lightdata", dlightdataLDR.Count(), 0 );
  2850. totalmemory += GlobUsage( "HDR lightdata", dlightdataHDR.Count(), 0 );
  2851. totalmemory += GlobUsage( "visdata", visdatasize, sizeof(dvisdata) );
  2852. totalmemory += GlobUsage( "entdata", dentdata.Count(), 384*1024 ); // goal is <384K
  2853. totalmemory += ArrayUsage( "LDR ambient table", g_LeafAmbientIndexLDR.Count(), MAX_MAP_LEAFS, sizeof( g_LeafAmbientIndexLDR[0] ) );
  2854. totalmemory += ArrayUsage( "HDR ambient table", g_LeafAmbientIndexHDR.Count(), MAX_MAP_LEAFS, sizeof( g_LeafAmbientIndexHDR[0] ) );
  2855. totalmemory += ArrayUsage( "LDR leaf ambient lighting", g_LeafAmbientLightingLDR.Count(), MAX_MAP_LEAFS, sizeof( g_LeafAmbientLightingLDR[0] ) );
  2856. totalmemory += ArrayUsage( "HDR leaf ambient lighting", g_LeafAmbientLightingHDR.Count(), MAX_MAP_LEAFS, sizeof( g_LeafAmbientLightingHDR[0] ) );
  2857. totalmemory += ArrayUsage( "occluders", g_OccluderData.Count(), 0, sizeof( g_OccluderData[0] ) );
  2858. totalmemory += ArrayUsage( "occluder polygons", g_OccluderPolyData.Count(), 0, sizeof( g_OccluderPolyData[0] ) );
  2859. totalmemory += ArrayUsage( "occluder vert ind",g_OccluderVertexIndices.Count(),0, sizeof( g_OccluderVertexIndices[0] ) );
  2860. GameLumpHandle_t h = g_GameLumps.GetGameLumpHandle( GAMELUMP_DETAIL_PROPS );
  2861. if (h != g_GameLumps.InvalidGameLump())
  2862. totalmemory += GlobUsage( "detail props", 1, g_GameLumps.GameLumpSize(h) );
  2863. h = g_GameLumps.GetGameLumpHandle( GAMELUMP_DETAIL_PROP_LIGHTING );
  2864. if (h != g_GameLumps.InvalidGameLump())
  2865. totalmemory += GlobUsage( "dtl prp lght", 1, g_GameLumps.GameLumpSize(h) );
  2866. h = g_GameLumps.GetGameLumpHandle( GAMELUMP_DETAIL_PROP_LIGHTING_HDR );
  2867. if (h != g_GameLumps.InvalidGameLump())
  2868. totalmemory += GlobUsage( "HDR dtl prp lght", 1, g_GameLumps.GameLumpSize(h) );
  2869. h = g_GameLumps.GetGameLumpHandle( GAMELUMP_STATIC_PROPS );
  2870. if (h != g_GameLumps.InvalidGameLump())
  2871. totalmemory += GlobUsage( "static props", 1, g_GameLumps.GameLumpSize(h) );
  2872. totalmemory += GlobUsage( "pakfile", GetPakFile()->EstimateSize(), 0 );
  2873. // HACKHACK: Set physics limit at 4MB, in reality this is totally dynamic
  2874. totalmemory += GlobUsage( "physics", g_PhysCollideSize, 4*1024*1024 );
  2875. totalmemory += GlobUsage( "physics terrain", g_PhysDispSize, 1*1024*1024 );
  2876. Msg( "\nLevel flags = %x\n", g_LevelFlags );
  2877. Msg( "\n" );
  2878. int triangleCount = 0;
  2879. for ( int i = 0; i < numfaces; i++ )
  2880. {
  2881. // face tris = numedges - 2
  2882. triangleCount += dfaces[i].numedges - 2;
  2883. }
  2884. Msg("Total triangle count: %d\n", triangleCount );
  2885. // UNDONE:
  2886. // areaportals, portals, texdata, clusters, worldlights, portalverts
  2887. }
  2888. /*
  2889. =============
  2890. PrintBSPPackDirectory
  2891. Dumps a list of files stored in the bsp pack.
  2892. =============
  2893. */
  2894. void PrintBSPPackDirectory( void )
  2895. {
  2896. GetPakFile()->PrintDirectory();
  2897. }
  2898. //============================================
  2899. int num_entities;
  2900. entity_t entities[MAX_MAP_ENTITIES];
  2901. void StripTrailing (char *e)
  2902. {
  2903. char *s;
  2904. s = e + strlen(e)-1;
  2905. while (s >= e && *s <= 32)
  2906. {
  2907. *s = 0;
  2908. s--;
  2909. }
  2910. }
  2911. /*
  2912. =================
  2913. ParseEpair
  2914. =================
  2915. */
  2916. epair_t *ParseEpair (void)
  2917. {
  2918. epair_t *e;
  2919. e = (epair_t*)malloc (sizeof(epair_t));
  2920. memset (e, 0, sizeof(epair_t));
  2921. StripTrailing( token );
  2922. if (strlen(token) >= MAX_KEY-1)
  2923. Error ("ParseEpar: key token too long [%s]", token);
  2924. e->key = copystring(token);
  2925. GetToken (false);
  2926. StripTrailing( token );
  2927. if (strlen(token) >= MAX_VALUE-1)
  2928. Error ("ParseEpar: value token too long [%s]", token);
  2929. e->value = copystring(token);
  2930. return e;
  2931. }
  2932. void RemoveKey( entity_t *pMapEnt, const char *pKey )
  2933. {
  2934. epair_t **pPrev = &pMapEnt->epairs;
  2935. for ( epair_t *pSearch = pMapEnt->epairs; pSearch != NULL; pPrev = &pSearch->next, pSearch = pSearch->next)
  2936. {
  2937. if (!Q_stricmp( pSearch->key, pKey ) )
  2938. {
  2939. (*pPrev) = pSearch->next;
  2940. free( pSearch );
  2941. return;
  2942. }
  2943. }
  2944. }
  2945. /*
  2946. ================
  2947. ParseEntity
  2948. ================
  2949. */
  2950. qboolean ParseEntity (void)
  2951. {
  2952. epair_t *e;
  2953. entity_t *mapent;
  2954. if (!GetToken (true))
  2955. return false;
  2956. if (Q_stricmp (token, "{") )
  2957. Error ("ParseEntity: { not found");
  2958. if (num_entities == MAX_MAP_ENTITIES)
  2959. Error ("num_entities == MAX_MAP_ENTITIES");
  2960. mapent = &entities[num_entities];
  2961. num_entities++;
  2962. do
  2963. {
  2964. if (!GetToken (true))
  2965. Error ("ParseEntity: EOF without closing brace");
  2966. if (!Q_stricmp (token, "}") )
  2967. break;
  2968. e = ParseEpair ();
  2969. e->next = mapent->epairs;
  2970. mapent->epairs = e;
  2971. } while (1);
  2972. return true;
  2973. }
  2974. /*
  2975. ================
  2976. ParseEntities
  2977. Parses the dentdata string into entities
  2978. ================
  2979. */
  2980. void ParseEntities (void)
  2981. {
  2982. num_entities = 0;
  2983. ParseFromMemory (dentdata.Base(), dentdata.Count());
  2984. while (ParseEntity ())
  2985. {
  2986. }
  2987. }
  2988. /*
  2989. ================
  2990. UnparseEntities
  2991. Generates the dentdata string from all the entities
  2992. ================
  2993. */
  2994. void UnparseEntities (void)
  2995. {
  2996. epair_t *ep;
  2997. char line[2048];
  2998. int i;
  2999. char key[1024], value[1024];
  3000. CUtlBuffer buffer( 0, 0, CUtlBuffer::TEXT_BUFFER );
  3001. buffer.EnsureCapacity( 256 * 1024 );
  3002. for (i=0 ; i<num_entities ; i++)
  3003. {
  3004. ep = entities[i].epairs;
  3005. if (!ep)
  3006. continue; // ent got removed
  3007. buffer.PutString( "{\n" );
  3008. for (ep = entities[i].epairs ; ep ; ep=ep->next)
  3009. {
  3010. if ( ep->key[ 0 ] == 0 )
  3011. {
  3012. continue;
  3013. }
  3014. strcpy (key, ep->key);
  3015. StripTrailing (key);
  3016. strcpy (value, ep->value);
  3017. StripTrailing (value);
  3018. V_sprintf_safe(line, "\"%s\" \"%s\"\n", key, value);
  3019. buffer.PutString( line );
  3020. }
  3021. buffer.PutString("}\n");
  3022. }
  3023. int entdatasize = buffer.TellPut()+1;
  3024. dentdata.SetSize( entdatasize );
  3025. memcpy( dentdata.Base(), buffer.Base(), entdatasize-1 );
  3026. dentdata[entdatasize-1] = 0;
  3027. }
  3028. void PrintEntity (entity_t *ent)
  3029. {
  3030. epair_t *ep;
  3031. Msg ("------- entity %p -------\n", ent);
  3032. for (ep=ent->epairs ; ep ; ep=ep->next)
  3033. {
  3034. Msg ("%s = %s\n", ep->key, ep->value);
  3035. }
  3036. }
  3037. epair_t *SetKeyValue( entity_t *ent, const char *key, const char *value, bool bAllowDuplicates )
  3038. {
  3039. epair_t *ep;
  3040. if ( bAllowDuplicates == false )
  3041. {
  3042. for (ep=ent->epairs ; ep ; ep=ep->next)
  3043. {
  3044. if (!Q_stricmp (ep->key, key) )
  3045. {
  3046. free (ep->value);
  3047. ep->value = copystring(value);
  3048. return ep;
  3049. }
  3050. }
  3051. }
  3052. ep = (epair_t*)malloc (sizeof(*ep));
  3053. ep->next = ent->epairs;
  3054. ent->epairs = ep;
  3055. ep->key = copystring(key);
  3056. ep->value = copystring(value);
  3057. return ep;
  3058. }
  3059. char *ValueForKey (entity_t *ent, const char *key)
  3060. {
  3061. for (epair_t *ep=ent->epairs ; ep ; ep=ep->next)
  3062. if (!Q_stricmp (ep->key, key) )
  3063. return ep->value;
  3064. return "";
  3065. }
  3066. vec_t FloatForKey (entity_t *ent, const char *key)
  3067. {
  3068. char *k = ValueForKey (ent, key);
  3069. return atof(k);
  3070. }
  3071. vec_t FloatForKeyWithDefault (entity_t *ent, const char *key, float default_value)
  3072. {
  3073. for (epair_t *ep=ent->epairs ; ep ; ep=ep->next)
  3074. if (!Q_stricmp (ep->key, key) )
  3075. return atof( ep->value );
  3076. return default_value;
  3077. }
  3078. int IntForKey (entity_t *ent, const char *key)
  3079. {
  3080. char *k = ValueForKey (ent, key);
  3081. return atol(k);
  3082. }
  3083. void GetVectorForKey (entity_t *ent, const char *key, Vector& vec)
  3084. {
  3085. char *k = ValueForKey (ent, key);
  3086. // scanf into doubles, then assign, so it is vec_t size independent
  3087. double v1, v2, v3;
  3088. v1 = v2 = v3 = 0;
  3089. sscanf (k, "%lf %lf %lf", &v1, &v2, &v3);
  3090. vec[0] = v1;
  3091. vec[1] = v2;
  3092. vec[2] = v3;
  3093. }
  3094. void GetVector2DForKey (entity_t *ent, const char *key, Vector2D& vec)
  3095. {
  3096. double v1, v2;
  3097. char *k = ValueForKey (ent, key);
  3098. // scanf into doubles, then assign, so it is vec_t size independent
  3099. v1 = v2 = 0;
  3100. sscanf (k, "%lf %lf", &v1, &v2);
  3101. vec[0] = v1;
  3102. vec[1] = v2;
  3103. }
  3104. void GetAnglesForKey (entity_t *ent, const char *key, QAngle& angle)
  3105. {
  3106. char *k;
  3107. double v1, v2, v3;
  3108. k = ValueForKey (ent, key);
  3109. // scanf into doubles, then assign, so it is vec_t size independent
  3110. v1 = v2 = v3 = 0;
  3111. sscanf (k, "%lf %lf %lf", &v1, &v2, &v3);
  3112. angle[0] = v1;
  3113. angle[1] = v2;
  3114. angle[2] = v3;
  3115. }
  3116. //-----------------------------------------------------------------------------
  3117. //-----------------------------------------------------------------------------
  3118. void BuildFaceCalcWindingData( dface_t *pFace, int *points )
  3119. {
  3120. for( int i = 0; i < pFace->numedges; i++ )
  3121. {
  3122. int eIndex = dsurfedges[pFace->firstedge+i];
  3123. if( eIndex < 0 )
  3124. {
  3125. points[i] = dedges[-eIndex].v[1];
  3126. }
  3127. else
  3128. {
  3129. points[i] = dedges[eIndex].v[0];
  3130. }
  3131. }
  3132. }
  3133. void TriStripToTriList(
  3134. unsigned short const *pTriStripIndices,
  3135. int nTriStripIndices,
  3136. unsigned short **pTriListIndices,
  3137. int *pnTriListIndices )
  3138. {
  3139. int nMaxTriListIndices = (nTriStripIndices - 2) * 3;
  3140. *pTriListIndices = new unsigned short[ nMaxTriListIndices ];
  3141. *pnTriListIndices = 0;
  3142. for( int i=0; i < nTriStripIndices - 2; i++ )
  3143. {
  3144. if( pTriStripIndices[i] == pTriStripIndices[i+1] ||
  3145. pTriStripIndices[i] == pTriStripIndices[i+2] ||
  3146. pTriStripIndices[i+1] == pTriStripIndices[i+2] )
  3147. {
  3148. }
  3149. else
  3150. {
  3151. // Flip odd numbered tris..
  3152. if( i & 1 )
  3153. {
  3154. (*pTriListIndices)[(*pnTriListIndices)++] = pTriStripIndices[i+2];
  3155. (*pTriListIndices)[(*pnTriListIndices)++] = pTriStripIndices[i+1];
  3156. (*pTriListIndices)[(*pnTriListIndices)++] = pTriStripIndices[i];
  3157. }
  3158. else
  3159. {
  3160. (*pTriListIndices)[(*pnTriListIndices)++] = pTriStripIndices[i];
  3161. (*pTriListIndices)[(*pnTriListIndices)++] = pTriStripIndices[i+1];
  3162. (*pTriListIndices)[(*pnTriListIndices)++] = pTriStripIndices[i+2];
  3163. }
  3164. }
  3165. }
  3166. }
  3167. void CalcTextureCoordsAtPoints(
  3168. float const texelsPerWorldUnits[2][4],
  3169. int const subtractOffset[2],
  3170. const Vector *pPoints,
  3171. int const nPoints,
  3172. Vector2D *pCoords )
  3173. {
  3174. for( int i=0; i < nPoints; i++ )
  3175. {
  3176. for( int iCoord=0; iCoord < 2; iCoord++ )
  3177. {
  3178. float *pDestCoord = &pCoords[i][iCoord];
  3179. *pDestCoord = 0;
  3180. for( int iDot=0; iDot < 3; iDot++ )
  3181. *pDestCoord += pPoints[i][iDot] * texelsPerWorldUnits[iCoord][iDot];
  3182. *pDestCoord += texelsPerWorldUnits[iCoord][3];
  3183. *pDestCoord -= subtractOffset[iCoord];
  3184. }
  3185. }
  3186. }
  3187. /*
  3188. ================
  3189. CalcFaceExtents
  3190. Fills in s->texmins[] and s->texsize[]
  3191. ================
  3192. */
  3193. void CalcFaceExtents(dface_t *s, int lightmapTextureMinsInLuxels[2], int lightmapTextureSizeInLuxels[2])
  3194. {
  3195. vec_t mins[2], maxs[2], val=0;
  3196. int i,j, e=0;
  3197. dvertex_t *v=NULL;
  3198. texinfo_t *tex=NULL;
  3199. mins[0] = mins[1] = 1e24;
  3200. maxs[0] = maxs[1] = -1e24;
  3201. tex = &texinfo[s->texinfo];
  3202. for (i=0 ; i<s->numedges ; i++)
  3203. {
  3204. e = dsurfedges[s->firstedge+i];
  3205. if (e >= 0)
  3206. v = dvertexes + dedges[e].v[0];
  3207. else
  3208. v = dvertexes + dedges[-e].v[1];
  3209. for (j=0 ; j<2 ; j++)
  3210. {
  3211. val = v->point[0] * tex->lightmapVecsLuxelsPerWorldUnits[j][0] +
  3212. v->point[1] * tex->lightmapVecsLuxelsPerWorldUnits[j][1] +
  3213. v->point[2] * tex->lightmapVecsLuxelsPerWorldUnits[j][2] +
  3214. tex->lightmapVecsLuxelsPerWorldUnits[j][3];
  3215. if (val < mins[j])
  3216. mins[j] = val;
  3217. if (val > maxs[j])
  3218. maxs[j] = val;
  3219. }
  3220. }
  3221. int nMaxLightmapDim = (s->dispinfo == -1) ? MAX_LIGHTMAP_DIM_WITHOUT_BORDER : MAX_DISP_LIGHTMAP_DIM_WITHOUT_BORDER;
  3222. for (i=0 ; i<2 ; i++)
  3223. {
  3224. mins[i] = ( float )floor( mins[i] );
  3225. maxs[i] = ( float )ceil( maxs[i] );
  3226. lightmapTextureMinsInLuxels[i] = ( int )mins[i];
  3227. lightmapTextureSizeInLuxels[i] = ( int )( maxs[i] - mins[i] );
  3228. if( lightmapTextureSizeInLuxels[i] > nMaxLightmapDim + 1 )
  3229. {
  3230. Vector point = vec3_origin;
  3231. for (int j=0 ; j<s->numedges ; j++)
  3232. {
  3233. e = dsurfedges[s->firstedge+j];
  3234. v = (e<0)?dvertexes + dedges[-e].v[1] : dvertexes + dedges[e].v[0];
  3235. point += v->point;
  3236. Warning( "Bad surface extents point: %f %f %f\n", v->point.x, v->point.y, v->point.z );
  3237. }
  3238. point *= 1.0f/s->numedges;
  3239. Error( "Bad surface extents - surface is too big to have a lightmap\n\tmaterial %s around point (%.1f %.1f %.1f)\n\t(dimension: %d, %d>%d)\n",
  3240. TexDataStringTable_GetString( dtexdata[texinfo[s->texinfo].texdata].nameStringTableID ),
  3241. point.x, point.y, point.z,
  3242. ( int )i,
  3243. ( int )lightmapTextureSizeInLuxels[i],
  3244. ( int )( nMaxLightmapDim + 1 )
  3245. );
  3246. }
  3247. }
  3248. }
  3249. void UpdateAllFaceLightmapExtents()
  3250. {
  3251. for( int i=0; i < numfaces; i++ )
  3252. {
  3253. dface_t *pFace = &dfaces[i];
  3254. if ( texinfo[pFace->texinfo].flags & (SURF_SKY|SURF_NOLIGHT) )
  3255. continue; // non-lit texture
  3256. CalcFaceExtents( pFace, pFace->m_LightmapTextureMinsInLuxels, pFace->m_LightmapTextureSizeInLuxels );
  3257. }
  3258. }
  3259. //-----------------------------------------------------------------------------
  3260. //
  3261. // Helper class to iterate over leaves, used by tools
  3262. //
  3263. //-----------------------------------------------------------------------------
  3264. #define TEST_EPSILON (0.03125)
  3265. class CToolBSPTree : public ISpatialQuery
  3266. {
  3267. public:
  3268. // Returns the number of leaves
  3269. int LeafCount() const;
  3270. // Enumerates the leaves along a ray, box, etc.
  3271. bool EnumerateLeavesAtPoint( const Vector& pt, ISpatialLeafEnumerator* pEnum, intp context );
  3272. bool EnumerateLeavesInBox( const Vector& mins, const Vector& maxs, ISpatialLeafEnumerator* pEnum, intp context );
  3273. bool EnumerateLeavesInSphere( const Vector& center, float radius, ISpatialLeafEnumerator* pEnum, intp context );
  3274. bool EnumerateLeavesAlongRay( Ray_t const& ray, ISpatialLeafEnumerator* pEnum, intp context );
  3275. bool EnumerateLeavesInSphereWithFlagSet( const Vector& center, float radius, ISpatialLeafEnumerator* pEnum, intp context, int nFlagsMask )
  3276. {
  3277. // engine flags not supported. Callers of this are supposed to examine the node anyway
  3278. return EnumerateLeavesInSphere( center, radius, pEnum, context );
  3279. }
  3280. int ListLeavesInBox( const Vector& mins, const Vector& maxs, unsigned short *pList, int listMax );
  3281. virtual int ListLeavesInSphereWithFlagSet( int *pLeafsInSphere, const Vector& vecCenter, float flRadius, int nLeafCount, const uint16 *pLeafs, int nLeafStride, int nFlagsCheck );
  3282. };
  3283. //-----------------------------------------------------------------------------
  3284. // Returns the number of leaves
  3285. //-----------------------------------------------------------------------------
  3286. int CToolBSPTree::LeafCount() const
  3287. {
  3288. return numleafs;
  3289. }
  3290. //-----------------------------------------------------------------------------
  3291. // Enumerates the leaves at a point
  3292. //-----------------------------------------------------------------------------
  3293. bool CToolBSPTree::EnumerateLeavesAtPoint( const Vector& pt,
  3294. ISpatialLeafEnumerator* pEnum, intp context )
  3295. {
  3296. int node = 0;
  3297. while( node >= 0 )
  3298. {
  3299. dnode_t* pNode = &dnodes[node];
  3300. dplane_t* pPlane = &dplanes[pNode->planenum];
  3301. if (DotProduct( pPlane->normal, pt ) <= pPlane->dist)
  3302. {
  3303. node = pNode->children[1];
  3304. }
  3305. else
  3306. {
  3307. node = pNode->children[0];
  3308. }
  3309. }
  3310. return pEnum->EnumerateLeaf( - node - 1, context );
  3311. }
  3312. //-----------------------------------------------------------------------------
  3313. // Enumerates the leaves in a box
  3314. //-----------------------------------------------------------------------------
  3315. static bool EnumerateLeavesInBox_R( int node, const Vector& mins,
  3316. const Vector& maxs, ISpatialLeafEnumerator* pEnum, intp context )
  3317. {
  3318. Vector cornermin, cornermax;
  3319. while( node >= 0 )
  3320. {
  3321. dnode_t* pNode = &dnodes[node];
  3322. dplane_t* pPlane = &dplanes[pNode->planenum];
  3323. // Arbitrary split plane here
  3324. for (int i = 0; i < 3; ++i)
  3325. {
  3326. if (pPlane->normal[i] >= 0)
  3327. {
  3328. cornermin[i] = mins[i];
  3329. cornermax[i] = maxs[i];
  3330. }
  3331. else
  3332. {
  3333. cornermin[i] = maxs[i];
  3334. cornermax[i] = mins[i];
  3335. }
  3336. }
  3337. if ( (DotProduct( pPlane->normal, cornermax ) - pPlane->dist) <= -TEST_EPSILON )
  3338. {
  3339. node = pNode->children[1];
  3340. }
  3341. else if ( (DotProduct( pPlane->normal, cornermin ) - pPlane->dist) >= TEST_EPSILON )
  3342. {
  3343. node = pNode->children[0];
  3344. }
  3345. else
  3346. {
  3347. if (!EnumerateLeavesInBox_R( pNode->children[0], mins, maxs, pEnum, context ))
  3348. {
  3349. return false;
  3350. }
  3351. return EnumerateLeavesInBox_R( pNode->children[1], mins, maxs, pEnum, context );
  3352. }
  3353. }
  3354. return pEnum->EnumerateLeaf( - node - 1, context );
  3355. }
  3356. bool CToolBSPTree::EnumerateLeavesInBox( const Vector& mins, const Vector& maxs,
  3357. ISpatialLeafEnumerator* pEnum, intp context )
  3358. {
  3359. return EnumerateLeavesInBox_R( 0, mins, maxs, pEnum, context );
  3360. }
  3361. // a little helper class to implement this interface for tools - engine uses this as a more efficient path
  3362. class CLeafMakeList : public ISpatialLeafEnumerator
  3363. {
  3364. public:
  3365. CLeafMakeList( unsigned short *pListIn, int listMaxIn )
  3366. : m_pList(pListIn), m_listMax(listMaxIn), m_count(0)
  3367. {
  3368. }
  3369. virtual bool EnumerateLeaf( int leaf, intp context )
  3370. {
  3371. if ( m_count < m_listMax )
  3372. {
  3373. m_pList[m_count] = leaf;
  3374. m_count++;
  3375. return true;
  3376. }
  3377. return false;
  3378. }
  3379. unsigned short *m_pList;
  3380. int m_listMax;
  3381. int m_count;
  3382. };
  3383. int CToolBSPTree::ListLeavesInBox( const Vector& mins, const Vector& maxs, unsigned short *pList, int listMax )
  3384. {
  3385. CLeafMakeList list(pList, listMax);
  3386. EnumerateLeavesInBox(mins, maxs, &list, 0 );
  3387. return list.m_count;
  3388. }
  3389. int CToolBSPTree::ListLeavesInSphereWithFlagSet( int *pLeafsInSphere, const Vector& vecCenter, float flRadius, int nLeafCount, const uint16 *pLeafs, int nLeafStride, int nFlagsCheck )
  3390. {
  3391. // NOTE: We ignore flags here
  3392. Vector vecMins, vecMaxs;
  3393. int nLeavesFound = 0;
  3394. const uint16 *pLeaf = pLeafs;
  3395. for ( int i = 0; i < nLeafCount; ++i, pLeaf = (const uint16*)( (const uint8*)pLeaf + nLeafStride ) )
  3396. {
  3397. dleaf_t &leaf = dleafs[ *pLeaf ];
  3398. VECTOR_COPY( leaf.mins, vecMins );
  3399. VECTOR_COPY( leaf.maxs, vecMaxs );
  3400. if ( !IsBoxIntersectingSphere( vecMins, vecMaxs, vecCenter, flRadius ) )
  3401. continue;
  3402. pLeafsInSphere[nLeavesFound++] = i;
  3403. }
  3404. return nLeavesFound;
  3405. }
  3406. //-----------------------------------------------------------------------------
  3407. // Enumerate leaves within a sphere
  3408. //-----------------------------------------------------------------------------
  3409. static bool EnumerateLeavesInSphere_R( int node, const Vector& origin,
  3410. float radius, ISpatialLeafEnumerator* pEnum, intp context )
  3411. {
  3412. while( node >= 0 )
  3413. {
  3414. dnode_t* pNode = &dnodes[node];
  3415. dplane_t* pPlane = &dplanes[pNode->planenum];
  3416. if (DotProduct( pPlane->normal, origin ) + radius - pPlane->dist <= -TEST_EPSILON )
  3417. {
  3418. node = pNode->children[1];
  3419. }
  3420. else if (DotProduct( pPlane->normal, origin ) - radius - pPlane->dist >= TEST_EPSILON )
  3421. {
  3422. node = pNode->children[0];
  3423. }
  3424. else
  3425. {
  3426. if (!EnumerateLeavesInSphere_R( pNode->children[0],
  3427. origin, radius, pEnum, context ))
  3428. {
  3429. return false;
  3430. }
  3431. return EnumerateLeavesInSphere_R( pNode->children[1],
  3432. origin, radius, pEnum, context );
  3433. }
  3434. }
  3435. return pEnum->EnumerateLeaf( - node - 1, context );
  3436. }
  3437. bool CToolBSPTree::EnumerateLeavesInSphere( const Vector& center, float radius, ISpatialLeafEnumerator* pEnum, intp context )
  3438. {
  3439. return EnumerateLeavesInSphere_R( 0, center, radius, pEnum, context );
  3440. }
  3441. //-----------------------------------------------------------------------------
  3442. // Enumerate leaves along a ray
  3443. //-----------------------------------------------------------------------------
  3444. static bool EnumerateLeavesAlongRay_R( int node, Ray_t const& ray,
  3445. const Vector& start, const Vector& end, ISpatialLeafEnumerator* pEnum, intp context )
  3446. {
  3447. float front,back;
  3448. while (node >= 0)
  3449. {
  3450. dnode_t* pNode = &dnodes[node];
  3451. dplane_t* pPlane = &dplanes[pNode->planenum];
  3452. if ( pPlane->type <= PLANE_Z )
  3453. {
  3454. front = start[pPlane->type] - pPlane->dist;
  3455. back = end[pPlane->type] - pPlane->dist;
  3456. }
  3457. else
  3458. {
  3459. front = DotProduct(start, pPlane->normal) - pPlane->dist;
  3460. back = DotProduct(end, pPlane->normal) - pPlane->dist;
  3461. }
  3462. if (front <= -TEST_EPSILON && back <= -TEST_EPSILON)
  3463. {
  3464. node = pNode->children[1];
  3465. }
  3466. else if (front >= TEST_EPSILON && back >= TEST_EPSILON)
  3467. {
  3468. node = pNode->children[0];
  3469. }
  3470. else
  3471. {
  3472. // test the front side first
  3473. bool side = front < 0;
  3474. // Compute intersection point based on the original ray
  3475. float splitfrac;
  3476. float denom = DotProduct( ray.m_Delta, pPlane->normal );
  3477. if ( denom == 0.0f )
  3478. {
  3479. splitfrac = 1.0f;
  3480. }
  3481. else
  3482. {
  3483. splitfrac = ( pPlane->dist - DotProduct( ray.m_Start, pPlane->normal ) ) / denom;
  3484. if (splitfrac < 0)
  3485. splitfrac = 0;
  3486. else if (splitfrac > 1)
  3487. splitfrac = 1;
  3488. }
  3489. // Compute the split point
  3490. Vector split;
  3491. VectorMA( ray.m_Start, splitfrac, ray.m_Delta, split );
  3492. bool r = EnumerateLeavesAlongRay_R (pNode->children[side], ray, start, split, pEnum, context );
  3493. if (!r)
  3494. return r;
  3495. return EnumerateLeavesAlongRay_R (pNode->children[!side], ray, split, end, pEnum, context);
  3496. }
  3497. }
  3498. return pEnum->EnumerateLeaf( - node - 1, context );
  3499. }
  3500. bool CToolBSPTree::EnumerateLeavesAlongRay( Ray_t const& ray, ISpatialLeafEnumerator* pEnum, intp context )
  3501. {
  3502. if (!ray.m_IsSwept)
  3503. {
  3504. Vector mins, maxs;
  3505. VectorAdd( ray.m_Start, ray.m_Extents, maxs );
  3506. VectorSubtract( ray.m_Start, ray.m_Extents, mins );
  3507. return EnumerateLeavesInBox_R( 0, mins, maxs, pEnum, context );
  3508. }
  3509. // FIXME: Extruded ray not implemented yet
  3510. Assert( ray.m_IsRay );
  3511. Vector end;
  3512. VectorAdd( ray.m_Start, ray.m_Delta, end );
  3513. return EnumerateLeavesAlongRay_R( 0, ray, ray.m_Start, end, pEnum, context );
  3514. }
  3515. //-----------------------------------------------------------------------------
  3516. // Singleton accessor
  3517. //-----------------------------------------------------------------------------
  3518. ISpatialQuery* ToolBSPTree()
  3519. {
  3520. static CToolBSPTree s_ToolBSPTree;
  3521. return &s_ToolBSPTree;
  3522. }
  3523. //-----------------------------------------------------------------------------
  3524. // Enumerates nodes in front to back order...
  3525. //-----------------------------------------------------------------------------
  3526. // FIXME: Do we want this in the IBSPTree interface?
  3527. static bool EnumerateNodesAlongRay_R( int node, Ray_t const& ray, float start, float end,
  3528. IBSPNodeEnumerator* pEnum, intp context )
  3529. {
  3530. float front, back;
  3531. float startDotN, deltaDotN;
  3532. while (node >= 0)
  3533. {
  3534. dnode_t* pNode = &dnodes[node];
  3535. dplane_t* pPlane = &dplanes[pNode->planenum];
  3536. if ( pPlane->type <= PLANE_Z )
  3537. {
  3538. startDotN = ray.m_Start[pPlane->type];
  3539. deltaDotN = ray.m_Delta[pPlane->type];
  3540. }
  3541. else
  3542. {
  3543. startDotN = DotProduct( ray.m_Start, pPlane->normal );
  3544. deltaDotN = DotProduct( ray.m_Delta, pPlane->normal );
  3545. }
  3546. front = startDotN + start * deltaDotN - pPlane->dist;
  3547. back = startDotN + end * deltaDotN - pPlane->dist;
  3548. if (front <= -TEST_EPSILON && back <= -TEST_EPSILON)
  3549. {
  3550. node = pNode->children[1];
  3551. }
  3552. else if (front >= TEST_EPSILON && back >= TEST_EPSILON)
  3553. {
  3554. node = pNode->children[0];
  3555. }
  3556. else
  3557. {
  3558. // test the front side first
  3559. bool side = front < 0;
  3560. // Compute intersection point based on the original ray
  3561. float splitfrac;
  3562. if ( deltaDotN == 0.0f )
  3563. {
  3564. splitfrac = 1.0f;
  3565. }
  3566. else
  3567. {
  3568. splitfrac = ( pPlane->dist - startDotN ) / deltaDotN;
  3569. if (splitfrac < 0.0f)
  3570. splitfrac = 0.0f;
  3571. else if (splitfrac > 1.0f)
  3572. splitfrac = 1.0f;
  3573. }
  3574. bool r = EnumerateNodesAlongRay_R (pNode->children[side], ray, start, splitfrac, pEnum, context );
  3575. if (!r)
  3576. return r;
  3577. // Visit the node...
  3578. if (!pEnum->EnumerateNode( node, ray, splitfrac, context ))
  3579. return false;
  3580. return EnumerateNodesAlongRay_R (pNode->children[!side], ray, splitfrac, end, pEnum, context);
  3581. }
  3582. }
  3583. // Visit the leaf...
  3584. return pEnum->EnumerateLeaf( - node - 1, ray, start, end, context );
  3585. }
  3586. bool EnumerateNodesAlongRay( Ray_t const& ray, IBSPNodeEnumerator* pEnum, intp context )
  3587. {
  3588. Vector end;
  3589. VectorAdd( ray.m_Start, ray.m_Delta, end );
  3590. return EnumerateNodesAlongRay_R( 0, ray, 0.0f, 1.0f, pEnum, context );
  3591. }
  3592. //-----------------------------------------------------------------------------
  3593. // Helps us find all leaves associated with a particular cluster
  3594. //-----------------------------------------------------------------------------
  3595. CUtlVector<clusterlist_t> g_ClusterLeaves;
  3596. void BuildClusterTable( void )
  3597. {
  3598. int i, j;
  3599. int leafCount;
  3600. int leafList[MAX_MAP_LEAFS];
  3601. g_ClusterLeaves.SetCount( dvis->numclusters );
  3602. for ( i = 0; i < dvis->numclusters; i++ )
  3603. {
  3604. leafCount = 0;
  3605. for ( j = 0; j < numleafs; j++ )
  3606. {
  3607. if ( dleafs[j].cluster == i )
  3608. {
  3609. leafList[ leafCount ] = j;
  3610. leafCount++;
  3611. }
  3612. }
  3613. g_ClusterLeaves[i].leafCount = leafCount;
  3614. if ( leafCount )
  3615. {
  3616. g_ClusterLeaves[i].leafs.SetCount( leafCount );
  3617. memcpy( g_ClusterLeaves[i].leafs.Base(), leafList, sizeof(int) * leafCount );
  3618. }
  3619. }
  3620. }
  3621. // There's a version of this in host.cpp!!! Make sure that they match.
  3622. void GetPlatformMapPath( const char *pMapPath, char *pPlatformMapPath, int dxlevel, int maxLength )
  3623. {
  3624. Q_StripExtension( pMapPath, pPlatformMapPath, maxLength );
  3625. // if( dxlevel <= 60 )
  3626. // {
  3627. // Q_strncat( pPlatformMapPath, "_dx60", maxLength, COPY_ALL_CHARACTERS );
  3628. // }
  3629. Q_strncat( pPlatformMapPath, ".bsp", maxLength, COPY_ALL_CHARACTERS );
  3630. }
  3631. // There's a version of this in checksum_engine.cpp!!! Make sure that they match.
  3632. static bool CRC_MapFile(CRC32_t *crcvalue, const char *pszFileName)
  3633. {
  3634. byte chunk[1024];
  3635. lump_t *curLump;
  3636. FileHandle_t fp = g_pFileSystem->Open( pszFileName, "rb" );
  3637. if ( !fp )
  3638. return false;
  3639. // CRC across all lumps except for the Entities lump
  3640. for ( int l = 0; l < HEADER_LUMPS; ++l )
  3641. {
  3642. if (l == LUMP_ENTITIES)
  3643. continue;
  3644. curLump = &g_pBSPHeader->lumps[l];
  3645. unsigned int nSize = curLump->filelen;
  3646. g_pFileSystem->Seek( fp, curLump->fileofs, FILESYSTEM_SEEK_HEAD );
  3647. // Now read in 1K chunks
  3648. while ( nSize > 0 )
  3649. {
  3650. int nBytesRead = 0;
  3651. if ( nSize > 1024 )
  3652. nBytesRead = g_pFileSystem->Read( chunk, 1024, fp );
  3653. else
  3654. nBytesRead = g_pFileSystem->Read( chunk, nSize, fp );
  3655. // If any data was received, CRC it.
  3656. if ( nBytesRead > 0 )
  3657. {
  3658. nSize -= nBytesRead;
  3659. CRC32_ProcessBuffer( crcvalue, chunk, nBytesRead );
  3660. }
  3661. else
  3662. {
  3663. g_pFileSystem->Close( fp );
  3664. return false;
  3665. }
  3666. }
  3667. }
  3668. g_pFileSystem->Close( fp );
  3669. return true;
  3670. }
  3671. void SetHDRMode( bool bHDR )
  3672. {
  3673. g_bHDR = bHDR;
  3674. if ( bHDR )
  3675. {
  3676. pdlightdata = &dlightdataHDR;
  3677. g_pLeafAmbientLighting = &g_LeafAmbientLightingHDR;
  3678. g_pLeafAmbientIndex = &g_LeafAmbientIndexHDR;
  3679. pNumworldlights = &numworldlightsHDR;
  3680. dworldlights = dworldlightsHDR;
  3681. #ifdef VRAD
  3682. extern void VRadDetailProps_SetHDRMode( bool bHDR );
  3683. VRadDetailProps_SetHDRMode( bHDR );
  3684. #endif
  3685. }
  3686. else
  3687. {
  3688. pdlightdata = &dlightdataLDR;
  3689. g_pLeafAmbientLighting = &g_LeafAmbientLightingLDR;
  3690. g_pLeafAmbientIndex = &g_LeafAmbientIndexLDR;
  3691. pNumworldlights = &numworldlightsLDR;
  3692. dworldlights = dworldlightsLDR;
  3693. #ifdef VRAD
  3694. extern void VRadDetailProps_SetHDRMode( bool bHDR );
  3695. VRadDetailProps_SetHDRMode( bHDR );
  3696. #endif
  3697. }
  3698. }
  3699. bool SwapVHV( void *pDestBase, void *pSrcBase )
  3700. {
  3701. byte *pDest = (byte*)pDestBase;
  3702. byte *pSrc = (byte*)pSrcBase;
  3703. HardwareVerts::FileHeader_t *pHdr = (HardwareVerts::FileHeader_t*)( g_bSwapOnLoad ? pDest : pSrc );
  3704. g_Swap.SwapFieldsToTargetEndian<HardwareVerts::FileHeader_t>( (HardwareVerts::FileHeader_t*)pDest, (HardwareVerts::FileHeader_t*)pSrc );
  3705. pSrc += sizeof(HardwareVerts::FileHeader_t);
  3706. pDest += sizeof(HardwareVerts::FileHeader_t);
  3707. // This swap is pretty format specific
  3708. Assert( pHdr->m_nVersion == VHV_VERSION );
  3709. if ( pHdr->m_nVersion != VHV_VERSION )
  3710. return false;
  3711. HardwareVerts::MeshHeader_t *pSrcMesh = (HardwareVerts::MeshHeader_t*)pSrc;
  3712. HardwareVerts::MeshHeader_t *pDestMesh = (HardwareVerts::MeshHeader_t*)pDest;
  3713. HardwareVerts::MeshHeader_t *pMesh = (HardwareVerts::MeshHeader_t*)( g_bSwapOnLoad ? pDest : pSrc );
  3714. for ( int i = 0; i < pHdr->m_nMeshes; ++i, ++pMesh, ++pSrcMesh, ++pDestMesh )
  3715. {
  3716. g_Swap.SwapFieldsToTargetEndian( pDestMesh, pSrcMesh );
  3717. pSrc = (byte*)pSrcBase + pMesh->m_nOffset;
  3718. pDest = (byte*)pDestBase + pMesh->m_nOffset;
  3719. // Swap as a buffer of integers
  3720. // (source is bgra for an Intel swap to argb. PowerPC won't swap, so we need argb source.
  3721. g_Swap.SwapBufferToTargetEndian<int>( (int*)pDest, (int*)pSrc, pMesh->m_nVertexes );
  3722. }
  3723. return true;
  3724. }
  3725. const char *ResolveStaticPropToModel( const char *pPropName )
  3726. {
  3727. // resolve back to static prop
  3728. int iProp = -1;
  3729. // filename should be sp_???.vhv or sp_hdr_???.vhv
  3730. if ( V_strnicmp( pPropName, "sp_", 3 ) )
  3731. {
  3732. return NULL;
  3733. }
  3734. const char *pPropNumber = V_strrchr( pPropName, '_' );
  3735. if ( pPropNumber )
  3736. {
  3737. sscanf( pPropNumber+1, "%d.vhv", &iProp );
  3738. }
  3739. else
  3740. {
  3741. return NULL;
  3742. }
  3743. // look up the prop to get to the actual model
  3744. if ( iProp < 0 || iProp >= g_StaticPropInstances.Count() )
  3745. {
  3746. // prop out of range
  3747. return NULL;
  3748. }
  3749. int iModel = g_StaticPropInstances[iProp];
  3750. if ( iModel < 0 || iModel >= g_StaticPropNames.Count() )
  3751. {
  3752. // model out of range
  3753. return NULL;
  3754. }
  3755. return g_StaticPropNames[iModel].String();
  3756. }
  3757. //-----------------------------------------------------------------------------
  3758. // Iterate files in pak file, distribute to converters
  3759. // pak file will be ready for serialization upon completion
  3760. //-----------------------------------------------------------------------------
  3761. void ConvertPakFileContents( const char *pInFilename, char const *szPlatform )
  3762. {
  3763. bool bIsXbox360 = ( V_stricmp( szPlatform, "360" ) == 0 );
  3764. IZip *newPakFile = IZip::CreateZip( NULL );
  3765. CUtlBuffer sourceBuf;
  3766. CUtlBuffer targetBuf;
  3767. bool bConverted;
  3768. CUtlVector< CUtlString > hdrFiles;
  3769. int id = -1;
  3770. int fileSize;
  3771. while ( 1 )
  3772. {
  3773. char relativeName[MAX_PATH];
  3774. id = GetNextFilename( GetPakFile(), id, relativeName, sizeof( relativeName ), fileSize );
  3775. if ( id == -1)
  3776. break;
  3777. bConverted = false;
  3778. sourceBuf.Purge();
  3779. targetBuf.Purge();
  3780. const char* pExtension = V_GetFileExtension( relativeName );
  3781. const char* pExt = 0;
  3782. bool bOK = ReadFileFromPak( GetPakFile(), relativeName, false, sourceBuf );
  3783. if ( !bOK )
  3784. {
  3785. Warning( "Failed to load '%s' from lump pak for conversion or copy in '%s'.\n", relativeName, pInFilename );
  3786. continue;
  3787. }
  3788. if ( pExtension && !V_stricmp( pExtension, "vtf" ) )
  3789. {
  3790. bOK = g_pVTFConvertFunc( relativeName, sourceBuf, targetBuf, g_pCompressFunc, false );
  3791. if ( !bOK )
  3792. {
  3793. Warning( "Failed to convert '%s' in '%s'.\n", relativeName, pInFilename );
  3794. continue;
  3795. }
  3796. // handle simpleworldmodel decorated VTFs
  3797. if ( V_stristr( relativeName, "simpleworldmodel" ) )
  3798. {
  3799. if ( V_stristr( relativeName, ".pwl.vtf" ) )
  3800. {
  3801. // We always want to skip the pwl files since we do the gamma conversion in the shader on the 360.
  3802. // if ( !bIsXbox360 )
  3803. {
  3804. // pwl culled for all other platforms
  3805. continue;
  3806. }
  3807. // the .pwl concept is never exposed to the game directly
  3808. // no longer needed, remove it from the filename
  3809. // the below code will further fixup the filename for platform
  3810. CUtlString nameCopy = relativeName;
  3811. V_StrSubst( nameCopy.Get(), ".pwl.vtf", ".vtf", relativeName, sizeof( relativeName ), false );
  3812. }
  3813. else
  3814. {
  3815. // We always want to keep the non-pwl files since we do the gamma conversion in the shader on the 360.
  3816. if ( bIsXbox360 )
  3817. {
  3818. // xbox360 only wants the pwl versions
  3819. // continue;
  3820. }
  3821. }
  3822. }
  3823. bConverted = true;
  3824. pExt = ".vtf";
  3825. }
  3826. else if ( pExtension && !V_stricmp( pExtension, "vhv" ) )
  3827. {
  3828. CUtlBuffer tempBuffer;
  3829. if ( g_pVHVFixupFunc )
  3830. {
  3831. // caller supplied a fixup
  3832. const char *pModelName = ResolveStaticPropToModel( relativeName );
  3833. if ( !pModelName )
  3834. {
  3835. Warning( "Static Prop '%s' failed to resolve actual model in '%s'.\n", relativeName, pInFilename );
  3836. continue;
  3837. }
  3838. // output temp buffer may shrink, must use TellPut() to determine size
  3839. bOK = g_pVHVFixupFunc( relativeName, pModelName, sourceBuf, tempBuffer );
  3840. if ( !bOK )
  3841. {
  3842. Warning( "Failed to convert '%s' in '%s'.\n", relativeName, pInFilename );
  3843. continue;
  3844. }
  3845. }
  3846. else
  3847. {
  3848. // use the source buffer as-is
  3849. tempBuffer.EnsureCapacity( sourceBuf.TellMaxPut() );
  3850. tempBuffer.Put( sourceBuf.Base(), sourceBuf.TellMaxPut() );
  3851. }
  3852. // swap the VHV
  3853. targetBuf.EnsureCapacity( tempBuffer.TellPut() );
  3854. bOK = SwapVHV( targetBuf.Base(), tempBuffer.Base() );
  3855. if ( !bOK )
  3856. {
  3857. Warning( "Failed to swap '%s' in '%s'.\n", relativeName, pInFilename );
  3858. continue;
  3859. }
  3860. targetBuf.SeekPut( CUtlBuffer::SEEK_HEAD, tempBuffer.TellPut() );
  3861. if ( g_pCompressFunc )
  3862. {
  3863. CUtlBuffer compressedBuffer;
  3864. targetBuf.SeekGet( CUtlBuffer::SEEK_HEAD, sizeof( HardwareVerts::FileHeader_t ) );
  3865. bool bCompressed = g_pCompressFunc( targetBuf, compressedBuffer );
  3866. if ( bCompressed )
  3867. {
  3868. // copy all the header data off
  3869. CUtlBuffer headerBuffer;
  3870. headerBuffer.EnsureCapacity( sizeof( HardwareVerts::FileHeader_t ) );
  3871. headerBuffer.Put( targetBuf.Base(), sizeof( HardwareVerts::FileHeader_t ) );
  3872. // reform the target with the header and then the compressed data
  3873. targetBuf.Clear();
  3874. targetBuf.Put( headerBuffer.Base(), sizeof( HardwareVerts::FileHeader_t ) );
  3875. targetBuf.Put( compressedBuffer.Base(), compressedBuffer.TellPut() );
  3876. }
  3877. targetBuf.SeekGet( CUtlBuffer::SEEK_HEAD, 0 );
  3878. }
  3879. bConverted = true;
  3880. pExt = ".vhv";
  3881. }
  3882. else if ( pExtension && !V_stricmp( pExtension, "dct" ) )
  3883. {
  3884. #if defined( PORTAL2 )
  3885. // not supporting for Portal2
  3886. // strip all
  3887. continue;
  3888. #endif
  3889. // take as-is no conversion necessary
  3890. if ( !V_stristr( relativeName, "_xbox.dct" ) )
  3891. {
  3892. // strip the pc version
  3893. continue;
  3894. }
  3895. }
  3896. else if ( pExtension && ( V_stricmp( pExtension, "mdl" ) == 0 ) )
  3897. {
  3898. // Do just enough of model conversion to get the simple world model static prop through.
  3899. // It's the only mdl file that is in the bsp zip file.
  3900. // NOTE: not doing compression! Will want to do this if we move other models into here.
  3901. if ( !Studio_ConvertStudioHdrToNewVersion( ( studiohdr_t * )sourceBuf.Base() ) )
  3902. {
  3903. Warning( "%s needs to be recompiled\n", relativeName );
  3904. }
  3905. g_pStudioConvertFunc( relativeName, sourceBuf, targetBuf );
  3906. bConverted = true;
  3907. pExt = ".mdl";
  3908. }
  3909. else if ( pExtension && ( V_stricmp( pExtension, "vtx" ) == 0 ) )
  3910. {
  3911. // Do just enough of model conversion to get the simple world model static prop through.
  3912. // It's the only mdl file that is in the bsp zip file.
  3913. // NOTE: not doing compression! Will want to do this if we move other models into here.
  3914. g_pStudioConvertFunc( relativeName, sourceBuf, targetBuf );
  3915. bConverted = true;
  3916. pExt = ".vtx";
  3917. }
  3918. else if ( pExtension && ( V_stricmp( pExtension, "vvd" ) == 0 ) )
  3919. {
  3920. // Do just enough of model conversion to get the simple world model static prop through.
  3921. // It's the only mdl file that is in the bsp zip file.
  3922. // NOTE: not doing compression! Will want to do this if we move other models into here.
  3923. g_pStudioConvertFunc( relativeName, sourceBuf, targetBuf );
  3924. bConverted = true;
  3925. pExt = ".vvd";
  3926. }
  3927. else if ( !V_stricmp( relativeName, "stringtable_dictionary.dat" ) ||
  3928. !V_stricmp( relativeName, "stringtable_dictionary.360.dat" ) ||
  3929. !V_stricmp( relativeName, "stringtable_dictionary.ps3.dat" ) )
  3930. {
  3931. // sigh, causes other system problems as these aren't conversions
  3932. // these were a mistake that leaked in during the "dct" transition
  3933. continue;
  3934. }
  3935. if ( !bConverted )
  3936. {
  3937. // straight copy
  3938. AddBufferToPak( newPakFile, relativeName, sourceBuf.Base(), sourceBuf.TellMaxPut(), false );
  3939. }
  3940. else
  3941. {
  3942. // converted filename
  3943. V_StripExtension( relativeName, relativeName, sizeof( relativeName ) );
  3944. V_strcat( relativeName, ".", sizeof( relativeName ) );
  3945. V_strcat( relativeName, szPlatform, sizeof( relativeName ) );
  3946. V_strcat( relativeName, pExt, sizeof( relativeName ) );
  3947. AddBufferToPak( newPakFile, relativeName, targetBuf.Base(), targetBuf.TellMaxPut(), false );
  3948. }
  3949. if ( V_stristr( relativeName, ".hdr" ) || V_stristr( relativeName, "_hdr" ) )
  3950. {
  3951. hdrFiles.AddToTail( relativeName );
  3952. }
  3953. DevMsg( "Created '%s' in lump pak in '%s'.\n", relativeName, pInFilename );
  3954. }
  3955. // strip ldr version of hdr files
  3956. for ( int i=0; i<hdrFiles.Count(); i++ )
  3957. {
  3958. char ldrFileName[MAX_PATH];
  3959. strcpy( ldrFileName, hdrFiles[i].String() );
  3960. char *pHDRExtension = V_stristr( ldrFileName, ".hdr" );
  3961. if ( !pHDRExtension )
  3962. {
  3963. pHDRExtension = V_stristr( ldrFileName, "_hdr" );
  3964. }
  3965. if ( pHDRExtension )
  3966. {
  3967. // strip .hdr or _hdr to get ldr filename
  3968. memcpy( pHDRExtension, pHDRExtension+4, strlen( pHDRExtension+4 )+1 );
  3969. DevMsg( "Stripping LDR: %s\n", ldrFileName );
  3970. newPakFile->RemoveFileFromZip( ldrFileName );
  3971. }
  3972. }
  3973. // discard old pak in favor of new pak
  3974. IZip::ReleaseZip( s_pakFile );
  3975. s_pakFile = newPakFile;
  3976. }
  3977. void SetAlignedLumpPosition( int lumpnum, int alignment = LUMP_ALIGNMENT )
  3978. {
  3979. g_pBSPHeader->lumps[lumpnum].fileofs = AlignFilePosition( g_hBSPFile, alignment );
  3980. }
  3981. template< class T >
  3982. int SwapLumpToDisk( int fieldType, int lumpnum )
  3983. {
  3984. if ( g_pBSPHeader->lumps[lumpnum].filelen == 0 )
  3985. return 0;
  3986. DevMsg( "Swapping %s\n", GetLumpName( lumpnum ) );
  3987. int nLumpSize = g_pBSPHeader->lumps[lumpnum].filelen;
  3988. if ( g_Lumps.bLumpFixed[lumpnum] )
  3989. {
  3990. nLumpSize = g_Lumps.size[lumpnum];
  3991. }
  3992. // lump swap may expand, allocate enough expansion room
  3993. int maxExpand = 2 * nLumpSize;
  3994. void *pBuffer = malloc( maxExpand );
  3995. // CopyLumpInternal will handle the swap on load case
  3996. unsigned int fieldSize = ( fieldType == FIELD_VECTOR ) ? sizeof(Vector) : sizeof(T);
  3997. unsigned int count = CopyLumpInternal<T>( fieldType, lumpnum, (T*)pBuffer, g_pBSPHeader->lumps[lumpnum].version );
  3998. g_pBSPHeader->lumps[lumpnum].filelen = count * fieldSize;
  3999. int nAlignment = LUMP_ALIGNMENT;
  4000. if ( g_bSwapOnWrite )
  4001. {
  4002. // Swap the lump in place before writing
  4003. switch( lumpnum )
  4004. {
  4005. case LUMP_VISIBILITY:
  4006. SwapVisibilityLump( (byte*)pBuffer, (byte*)pBuffer, count );
  4007. break;
  4008. case LUMP_PHYSCOLLIDE:
  4009. // SwapPhyscollideLump may change size
  4010. SwapPhyscollideLump( (byte*)pBuffer, (byte*)pBuffer, count );
  4011. g_pBSPHeader->lumps[lumpnum].filelen = count;
  4012. break;
  4013. case LUMP_PHYSDISP:
  4014. SwapPhysdispLump( (byte*)pBuffer, (byte*)pBuffer, count );
  4015. break;
  4016. case LUMP_PHYSLEVEL:
  4017. // this may change the file size
  4018. SwapPhyslevelLump( (byte*)pBuffer, (byte*)pBuffer, count, maxExpand );
  4019. g_pBSPHeader->lumps[lumpnum].filelen = count;
  4020. // needs to be 16 byte aligned
  4021. nAlignment = LUMP_PHYSLEVEL_ALIGNMENT;
  4022. break;
  4023. default:
  4024. g_Swap.SwapBufferToTargetEndian( (T*)pBuffer, (T*)pBuffer, g_pBSPHeader->lumps[lumpnum].filelen / sizeof(T) );
  4025. break;
  4026. }
  4027. }
  4028. SetAlignedLumpPosition( lumpnum, nAlignment );
  4029. SafeWrite( g_hBSPFile, pBuffer, g_pBSPHeader->lumps[lumpnum].filelen );
  4030. free( pBuffer );
  4031. return g_pBSPHeader->lumps[lumpnum].filelen;
  4032. }
  4033. template< class T >
  4034. int SwapLumpToDisk( int lumpnum )
  4035. {
  4036. if ( g_pBSPHeader->lumps[lumpnum].filelen == 0 || g_Lumps.bLumpParsed[lumpnum] )
  4037. return 0;
  4038. DevMsg( "Swapping %s\n", GetLumpName( lumpnum ) );
  4039. int nLumpSize = g_pBSPHeader->lumps[lumpnum].filelen;
  4040. if ( g_Lumps.bLumpFixed[lumpnum] )
  4041. {
  4042. // use the fixed version as input to swap
  4043. nLumpSize = g_Lumps.size[lumpnum];
  4044. }
  4045. // lump swap may expand, allocate enough room
  4046. Assert( nLumpSize > 0 );
  4047. void *pBuffer = malloc( 2 * nLumpSize );
  4048. // CopyLumpInternal will handle the swap on load case
  4049. int count = CopyLumpInternal<T>( lumpnum, (T*)pBuffer, g_pBSPHeader->lumps[lumpnum].version );
  4050. g_pBSPHeader->lumps[lumpnum].filelen = count * sizeof( T );
  4051. if ( g_bSwapOnWrite )
  4052. {
  4053. // Swap the lump in place before writing
  4054. g_Swap.SwapFieldsToTargetEndian( (T*)pBuffer, (T*)pBuffer, count );
  4055. }
  4056. SetAlignedLumpPosition( lumpnum );
  4057. SafeWrite( g_hBSPFile, pBuffer, g_pBSPHeader->lumps[lumpnum].filelen );
  4058. free( pBuffer );
  4059. return g_pBSPHeader->lumps[lumpnum].filelen;
  4060. }
  4061. void SwapLeafAmbientLightingLumpToDisk()
  4062. {
  4063. if ( HasLump( LUMP_LEAF_AMBIENT_INDEX ) || HasLump( LUMP_LEAF_AMBIENT_INDEX_HDR ) )
  4064. {
  4065. // current version, swap in place
  4066. if ( HasLump( LUMP_LEAF_AMBIENT_INDEX_HDR ) )
  4067. {
  4068. // write HDR
  4069. SwapLumpToDisk< dleafambientlighting_t >( LUMP_LEAF_AMBIENT_LIGHTING_HDR );
  4070. SwapLumpToDisk< dleafambientindex_t >( LUMP_LEAF_AMBIENT_INDEX_HDR );
  4071. // cull LDR
  4072. g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_LIGHTING].filelen = 0;
  4073. g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_INDEX].filelen = 0;
  4074. }
  4075. else
  4076. {
  4077. // no HDR, keep LDR version
  4078. SwapLumpToDisk< dleafambientlighting_t >( LUMP_LEAF_AMBIENT_LIGHTING );
  4079. SwapLumpToDisk< dleafambientindex_t >( LUMP_LEAF_AMBIENT_INDEX );
  4080. }
  4081. }
  4082. else
  4083. {
  4084. // older ambient lighting version (before index)
  4085. // load older ambient lighting into memory and build ambient/index
  4086. // an older leaf version would have already built the new LDR leaf ambient/index
  4087. int numLeafs = g_pBSPHeader->lumps[LUMP_LEAFS].filelen / sizeof( dleaf_t );
  4088. LoadLeafAmbientLighting( numLeafs );
  4089. if ( HasLump( LUMP_LEAF_AMBIENT_LIGHTING_HDR ) )
  4090. {
  4091. DevMsg( "Swapping %s\n", GetLumpName( LUMP_LEAF_AMBIENT_LIGHTING_HDR ) );
  4092. DevMsg( "Swapping %s\n", GetLumpName( LUMP_LEAF_AMBIENT_INDEX_HDR ) );
  4093. // write HDR
  4094. if ( g_bSwapOnWrite )
  4095. {
  4096. g_Swap.SwapFieldsToTargetEndian( g_LeafAmbientLightingHDR.Base(), g_LeafAmbientLightingHDR.Count() );
  4097. g_Swap.SwapFieldsToTargetEndian( g_LeafAmbientIndexHDR.Base(), g_LeafAmbientIndexHDR.Count() );
  4098. }
  4099. SetAlignedLumpPosition( LUMP_LEAF_AMBIENT_LIGHTING_HDR );
  4100. g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_LIGHTING_HDR].version = LUMP_LEAF_AMBIENT_LIGHTING_VERSION;
  4101. g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_LIGHTING_HDR].filelen = g_LeafAmbientLightingHDR.Count() * sizeof( dleafambientlighting_t );
  4102. SafeWrite( g_hBSPFile, g_LeafAmbientLightingHDR.Base(), g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_LIGHTING_HDR].filelen );
  4103. SetAlignedLumpPosition( LUMP_LEAF_AMBIENT_INDEX_HDR );
  4104. g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_INDEX_HDR].filelen = g_LeafAmbientIndexHDR.Count() * sizeof( dleafambientindex_t );
  4105. SafeWrite( g_hBSPFile, g_LeafAmbientIndexHDR.Base(), g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_INDEX_HDR].filelen );
  4106. // mark as processed
  4107. g_Lumps.bLumpParsed[LUMP_LEAF_AMBIENT_LIGHTING_HDR] = true;
  4108. g_Lumps.bLumpParsed[LUMP_LEAF_AMBIENT_INDEX_HDR] = true;
  4109. // cull LDR
  4110. g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_LIGHTING].filelen = 0;
  4111. g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_INDEX].filelen = 0;
  4112. }
  4113. else
  4114. {
  4115. // no HDR, keep LDR version
  4116. DevMsg( "Swapping %s\n", GetLumpName( LUMP_LEAF_AMBIENT_LIGHTING ) );
  4117. DevMsg( "Swapping %s\n", GetLumpName( LUMP_LEAF_AMBIENT_INDEX ) );
  4118. if ( g_bSwapOnWrite )
  4119. {
  4120. g_Swap.SwapFieldsToTargetEndian( g_LeafAmbientLightingLDR.Base(), g_LeafAmbientLightingLDR.Count() );
  4121. g_Swap.SwapFieldsToTargetEndian( g_LeafAmbientIndexLDR.Base(), g_LeafAmbientIndexLDR.Count() );
  4122. }
  4123. SetAlignedLumpPosition( LUMP_LEAF_AMBIENT_LIGHTING );
  4124. g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_LIGHTING].version = LUMP_LEAF_AMBIENT_LIGHTING_VERSION;
  4125. g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_LIGHTING].filelen = g_LeafAmbientLightingLDR.Count() * sizeof( dleafambientlighting_t );
  4126. SafeWrite( g_hBSPFile, g_LeafAmbientLightingLDR.Base(), g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_LIGHTING].filelen );
  4127. SetAlignedLumpPosition( LUMP_LEAF_AMBIENT_INDEX );
  4128. g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_INDEX].filelen = g_LeafAmbientIndexLDR.Count() * sizeof( dleafambientindex_t );
  4129. SafeWrite( g_hBSPFile, g_LeafAmbientIndexLDR.Base(), g_pBSPHeader->lumps[LUMP_LEAF_AMBIENT_INDEX].filelen );
  4130. // mark as processed
  4131. g_Lumps.bLumpParsed[LUMP_LEAF_AMBIENT_LIGHTING] = true;
  4132. g_Lumps.bLumpParsed[LUMP_LEAF_AMBIENT_INDEX] = true;
  4133. }
  4134. g_LeafAmbientLightingLDR.Purge();
  4135. g_LeafAmbientIndexLDR.Purge();
  4136. g_LeafAmbientLightingHDR.Purge();
  4137. g_LeafAmbientIndexHDR.Purge();
  4138. }
  4139. }
  4140. void SwapLeafLumpToDisk( void )
  4141. {
  4142. DevMsg( "Swapping %s\n", GetLumpName( LUMP_LEAFS ) );
  4143. // load the leafs
  4144. int count = LoadLeafs();
  4145. if ( g_bSwapOnWrite )
  4146. {
  4147. g_Swap.SwapFieldsToTargetEndian( dleafs, count );
  4148. }
  4149. bool bOldLeafVersion = ( LumpVersion( LUMP_LEAFS ) == 0 );
  4150. if ( bOldLeafVersion )
  4151. {
  4152. // version has been converted in the load process
  4153. // not updating the version yet, SwapLeafAmbientLightingLumpToDisk() can detect
  4154. g_pBSPHeader->lumps[LUMP_LEAFS].filelen = count * sizeof( dleaf_t );
  4155. }
  4156. SetAlignedLumpPosition( LUMP_LEAFS );
  4157. SafeWrite( g_hBSPFile, dleafs, g_pBSPHeader->lumps[LUMP_LEAFS].filelen );
  4158. SwapLeafAmbientLightingLumpToDisk();
  4159. if ( bOldLeafVersion )
  4160. {
  4161. // version has been converted in the load process
  4162. // can now safely change
  4163. g_pBSPHeader->lumps[LUMP_LEAFS].version = 1;
  4164. }
  4165. #if defined( BSP_USE_LESS_MEMORY )
  4166. if ( dleafs )
  4167. {
  4168. free( dleafs );
  4169. dleafs = NULL;
  4170. }
  4171. #endif
  4172. }
  4173. void SwapOcclusionLumpToDisk( void )
  4174. {
  4175. DevMsg( "Swapping %s\n", GetLumpName( LUMP_OCCLUSION ) );
  4176. LoadOcclusionLump();
  4177. SetAlignedLumpPosition( LUMP_OCCLUSION );
  4178. AddOcclusionLump();
  4179. }
  4180. void SwapPakfileLumpToDisk( const char *pInFilename, char const *szPlatform )
  4181. {
  4182. DevMsg( "Swapping %s\n", GetLumpName( LUMP_PAKFILE ) );
  4183. byte *pakbuffer = NULL;
  4184. int paksize = CopyVariableLump<byte>( FIELD_CHARACTER, LUMP_PAKFILE, ( void ** )&pakbuffer );
  4185. if ( paksize > 0 )
  4186. {
  4187. GetPakFile()->ActivateByteSwapping( IsX360() );
  4188. GetPakFile()->ParseFromBuffer( pakbuffer, paksize );
  4189. ConvertPakFileContents( pInFilename, szPlatform );
  4190. }
  4191. free( pakbuffer );
  4192. SetAlignedLumpPosition( LUMP_PAKFILE, XBOX_DVD_SECTORSIZE );
  4193. WritePakFileLump();
  4194. ReleasePakFileLumps();
  4195. }
  4196. void SwapGameLumpsToDisk( void )
  4197. {
  4198. DevMsg( "Swapping %s\n", GetLumpName( LUMP_GAME_LUMP ) );
  4199. g_GameLumps.ParseGameLump( g_pBSPHeader );
  4200. SetAlignedLumpPosition( LUMP_GAME_LUMP );
  4201. AddGameLumps();
  4202. }
  4203. void SwapWorldLightsToDisk()
  4204. {
  4205. bool bHasHDR = true;
  4206. if ( g_pBSPHeader->lumps[LUMP_WORLDLIGHTS_HDR].filelen == 0 || g_Lumps.bLumpParsed[LUMP_WORLDLIGHTS_HDR] )
  4207. {
  4208. bHasHDR = false;
  4209. }
  4210. int lumpnum = bHasHDR ? LUMP_WORLDLIGHTS_HDR : LUMP_WORLDLIGHTS;
  4211. DevMsg( "Swapping %s\n", GetLumpName( lumpnum ) );
  4212. dworldlight_version0_t *pOldWorldlights;
  4213. dworldlight_t *pWorldlights = NULL;
  4214. int count = 0;
  4215. // handle version difference
  4216. if ( g_pBSPHeader->lumps[lumpnum].version == 0 )
  4217. {
  4218. pOldWorldlights = (dworldlight_version0_t *)malloc( g_pBSPHeader->lumps[lumpnum].filelen );
  4219. count = CopyLumpInternal( lumpnum, pOldWorldlights, g_pBSPHeader->lumps[lumpnum].version );
  4220. pWorldlights = (dworldlight_t *)malloc( count * sizeof( dworldlight_t ) );
  4221. // translate forward
  4222. for ( int i = 0; i < count; i++ )
  4223. {
  4224. pWorldlights[i].origin = pOldWorldlights[i].origin;
  4225. pWorldlights[i].intensity = pOldWorldlights[i].intensity;
  4226. pWorldlights[i].normal = pOldWorldlights[i].normal;
  4227. pWorldlights[i].shadow_cast_offset.Init( 0.0f, 0.0f, 0.0f );
  4228. pWorldlights[i].cluster = pOldWorldlights[i].cluster;
  4229. pWorldlights[i].type = pOldWorldlights[i].type;
  4230. pWorldlights[i].style = pOldWorldlights[i].style;
  4231. pWorldlights[i].stopdot = pOldWorldlights[i].stopdot;
  4232. pWorldlights[i].stopdot2 = pOldWorldlights[i].stopdot2;
  4233. pWorldlights[i].exponent = pOldWorldlights[i].exponent;
  4234. pWorldlights[i].radius = pOldWorldlights[i].radius;
  4235. pWorldlights[i].constant_attn = pOldWorldlights[i].constant_attn;
  4236. pWorldlights[i].linear_attn = pOldWorldlights[i].linear_attn;
  4237. pWorldlights[i].quadratic_attn = pOldWorldlights[i].quadratic_attn;
  4238. pWorldlights[i].flags = pOldWorldlights[i].flags;
  4239. pWorldlights[i].texinfo = pOldWorldlights[i].texinfo;
  4240. pWorldlights[i].owner = pOldWorldlights[i].owner;
  4241. }
  4242. free( pOldWorldlights );
  4243. g_pBSPHeader->lumps[lumpnum].filelen = count * sizeof( dworldlight_t );
  4244. g_pBSPHeader->lumps[lumpnum].version = LUMP_WORLDLIGHTS_VERSION;
  4245. }
  4246. else if ( g_pBSPHeader->lumps[lumpnum].version == LUMP_WORLDLIGHTS_VERSION )
  4247. {
  4248. pWorldlights = (dworldlight_t *)malloc( g_pBSPHeader->lumps[lumpnum].filelen );
  4249. count = CopyLumpInternal( lumpnum, pWorldlights, g_pBSPHeader->lumps[lumpnum].version );
  4250. }
  4251. else
  4252. {
  4253. Error( "Unknown World Lights Lump version %d!\n", g_pBSPHeader->lumps[lumpnum].version );
  4254. }
  4255. if ( g_bSwapOnWrite )
  4256. {
  4257. // Swap the lump in place before writing
  4258. g_Swap.SwapFieldsToTargetEndian( (dworldlight_t*)pWorldlights, (dworldlight_t*)pWorldlights, count );
  4259. }
  4260. SetAlignedLumpPosition( lumpnum );
  4261. SafeWrite( g_hBSPFile, pWorldlights, g_pBSPHeader->lumps[lumpnum].filelen );
  4262. free( pWorldlights );
  4263. if ( bHasHDR )
  4264. {
  4265. // has HDR, strip obsolete LDR in favor of HDR
  4266. g_pBSPHeader->lumps[LUMP_WORLDLIGHTS].filelen = 0;
  4267. }
  4268. }
  4269. //-----------------------------------------------------------------------------
  4270. // Generate a table of all static props, used for resolving static prop lighting
  4271. // files back to their actual mdl.
  4272. //-----------------------------------------------------------------------------
  4273. void BuildStaticPropNameTable()
  4274. {
  4275. g_StaticPropNames.Purge();
  4276. g_StaticPropInstances.Purge();
  4277. g_GameLumps.ParseGameLump( g_pBSPHeader );
  4278. GameLumpHandle_t hGameLump = g_GameLumps.GetGameLumpHandle( GAMELUMP_STATIC_PROPS );
  4279. if ( hGameLump != g_GameLumps.InvalidGameLump() )
  4280. {
  4281. int nVersion = g_GameLumps.GetGameLumpVersion( hGameLump );
  4282. if ( nVersion < 4 )
  4283. {
  4284. // old unsupported version
  4285. return;
  4286. }
  4287. if ( nVersion < GAMELUMP_STATIC_PROPS_MIN_VERSION || nVersion > GAMELUMP_STATIC_PROPS_VERSION )
  4288. {
  4289. Error( "Unknown Static Prop Lump version %d!\n", nVersion );
  4290. }
  4291. byte *pGameLumpData = (byte *)g_GameLumps.GetGameLump( hGameLump );
  4292. if ( pGameLumpData && g_GameLumps.GameLumpSize( hGameLump ) )
  4293. {
  4294. // get the model dictionary
  4295. int count = ((int *)pGameLumpData)[0];
  4296. pGameLumpData += sizeof( int );
  4297. StaticPropDictLump_t *pStaticPropDictLump = (StaticPropDictLump_t *)pGameLumpData;
  4298. for ( int i = 0; i < count; i++ )
  4299. {
  4300. g_StaticPropNames.AddToTail( pStaticPropDictLump[i].m_Name );
  4301. }
  4302. pGameLumpData += count * sizeof( StaticPropDictLump_t );
  4303. // skip the leaf list
  4304. count = ((int *)pGameLumpData)[0];
  4305. pGameLumpData += sizeof( int );
  4306. pGameLumpData += count * sizeof( StaticPropLeafLump_t );
  4307. // get the instances
  4308. count = ((int *)pGameLumpData)[0];
  4309. pGameLumpData += sizeof( int );
  4310. for ( int i = 0; i < count; i++ )
  4311. {
  4312. int propType;
  4313. if ( nVersion == 4 )
  4314. {
  4315. propType = ((StaticPropLumpV4_t *)pGameLumpData)->m_PropType;
  4316. pGameLumpData += sizeof( StaticPropLumpV4_t );
  4317. }
  4318. else if ( nVersion == 5 )
  4319. {
  4320. propType = ((StaticPropLumpV5_t *)pGameLumpData)->m_PropType;
  4321. pGameLumpData += sizeof( StaticPropLumpV5_t );
  4322. }
  4323. else if ( nVersion == 6 )
  4324. {
  4325. propType = ( ( StaticPropLumpV6_t * )pGameLumpData )->m_PropType;
  4326. pGameLumpData += sizeof( StaticPropLumpV6_t );
  4327. }
  4328. else if ( nVersion == 7 )
  4329. {
  4330. propType = ((StaticPropLumpV7_t *)pGameLumpData)->m_PropType;
  4331. pGameLumpData += sizeof( StaticPropLumpV7_t );
  4332. }
  4333. else if ( nVersion == 8 )
  4334. {
  4335. propType = ((StaticPropLumpV8_t *)pGameLumpData)->m_PropType;
  4336. pGameLumpData += sizeof( StaticPropLumpV8_t );
  4337. }
  4338. else if ( nVersion == 9 )
  4339. {
  4340. propType = ((StaticPropLumpV9_t *)pGameLumpData)->m_PropType;
  4341. pGameLumpData += sizeof( StaticPropLumpV9_t );
  4342. }
  4343. else
  4344. {
  4345. if ( nVersion != 10 )
  4346. {
  4347. Error( "BuildStaticPropNameTable: Unknown Static Prop Lump version %d!\n", nVersion );
  4348. }
  4349. propType = ((StaticPropLump_t *)pGameLumpData)->m_PropType;
  4350. pGameLumpData += sizeof( StaticPropLump_t );
  4351. }
  4352. g_StaticPropInstances.AddToTail( propType );
  4353. }
  4354. }
  4355. }
  4356. g_GameLumps.DestroyAllGameLumps();
  4357. }
  4358. int ComputeLightmapSize( dface_t *pFace, texinfo_t *pTexInfos )
  4359. {
  4360. if ( pFace->lightofs == -1 )
  4361. {
  4362. // no lighting data on this face
  4363. return 0;
  4364. }
  4365. bool bNeedsBumpmap = false;
  4366. if ( pTexInfos[pFace->texinfo].flags & SURF_BUMPLIGHT )
  4367. {
  4368. bNeedsBumpmap = true;
  4369. }
  4370. // determine how many lightstyles this face has
  4371. int nLightstyles;
  4372. for ( nLightstyles = 0; nLightstyles < MAXLIGHTMAPS; nLightstyles++ )
  4373. {
  4374. if ( pFace->styles[nLightstyles] == 255 )
  4375. break;
  4376. }
  4377. int nLuxels = ( pFace->m_LightmapTextureSizeInLuxels[0] + 1 ) * ( pFace->m_LightmapTextureSizeInLuxels[1] + 1 );
  4378. if ( bNeedsBumpmap )
  4379. {
  4380. return nLuxels * 4 * nLightstyles * ( NUM_BUMP_VECTS + 1 );
  4381. }
  4382. return nLuxels * 4 * nLightstyles;
  4383. }
  4384. int ComputeLightmapPrefixSize( dface_t *pFace )
  4385. {
  4386. if ( pFace->lightofs == -1 )
  4387. {
  4388. // no lighting data on this face
  4389. return 0;
  4390. }
  4391. // determine how many lightstyles this face has
  4392. int nLightstyles;
  4393. for ( nLightstyles = 0; nLightstyles < MAXLIGHTMAPS; nLightstyles++ )
  4394. {
  4395. if ( pFace->styles[nLightstyles] == 255 )
  4396. break;
  4397. }
  4398. int nHdrBytes = nLightstyles * sizeof( ColorRGBExp32 );
  4399. return nHdrBytes;
  4400. }
  4401. void StripUnusedLightmapAlphaData()
  4402. {
  4403. // 7LS CSM's now working on console => we need the lightmap alpha data
  4404. #if 0
  4405. if ( ( g_LevelFlags & LVLFLAGS_LIGHTMAP_ALPHA ) == 0 )
  4406. {
  4407. // not applicable, this map does not have the extra data
  4408. return;
  4409. }
  4410. if ( g_pBSPHeader->lumps[LUMP_FACES_HDR].filelen == 0 || g_pBSPHeader->lumps[LUMP_LIGHTING_HDR].filelen == 0 )
  4411. {
  4412. // only care about fixing shipping maps built properly for HDR
  4413. // expected data is missing, nothing to do
  4414. return;
  4415. }
  4416. // get the texinfo
  4417. texinfo_t *pTexInfos = (texinfo_t *)malloc( g_pBSPHeader->lumps[LUMP_TEXINFO].filelen );
  4418. CopyLumpInternal( LUMP_TEXINFO, pTexInfos, g_pBSPHeader->lumps[LUMP_TEXINFO].version );
  4419. // get the current lighting
  4420. int nOldTotalLightmapSize = g_pBSPHeader->lumps[LUMP_LIGHTING_HDR].filelen;
  4421. byte *pOldLightingBase = (byte *)malloc( nOldTotalLightmapSize );
  4422. CopyLumpInternal( FIELD_CHARACTER, LUMP_LIGHTING_HDR, pOldLightingBase, g_pBSPHeader->lumps[LUMP_LIGHTING_HDR].version );
  4423. // create new lighting data
  4424. // the new lighting data can only be the same size or smaller
  4425. byte *pNewLightingBase = (byte *)malloc( g_pBSPHeader->lumps[LUMP_LIGHTING_HDR].filelen );
  4426. memset( pNewLightingBase, 0, g_pBSPHeader->lumps[LUMP_LIGHTING_HDR].filelen );
  4427. byte *pNewLighting = pNewLightingBase;
  4428. // there is no guarantee that the face order has anything to do with their luxel placement
  4429. // the face order will remain unchanged, but the relevant luxels will be gathered and re-serialized
  4430. dface_t *pFaces = (dface_t *)malloc( g_pBSPHeader->lumps[LUMP_FACES_HDR].filelen );
  4431. int nNumFaces = CopyLumpInternal( LUMP_FACES_HDR, pFaces, g_pBSPHeader->lumps[LUMP_FACES_HDR].version );
  4432. int nTotalNewLightmapSize = 0;
  4433. for ( int i = 0; i < nNumFaces; i++ )
  4434. {
  4435. // matches the logic in modelloader.cpp
  4436. int nLightmapSize = ComputeLightmapSize( &pFaces[i], pTexInfos );
  4437. // there are prefix bytes (avgcolors) stored prior to the lighting offset
  4438. int nLightmapPrefixSize = ComputeLightmapPrefixSize( &pFaces[i] );
  4439. if ( nLightmapSize )
  4440. {
  4441. if ( nTotalNewLightmapSize + nLightmapPrefixSize + nLightmapSize > nOldTotalLightmapSize )
  4442. {
  4443. // very bad, unexpected misalignment of data
  4444. // would have caused memory corruption
  4445. Error( "StripUnusedLightmapAlphaData: lightmap size:%d at offset:%d on face:%d causes an unexpected inflation past %d bytes\n", nLightmapSize, pFaces[i].lightofs, i, nOldTotalLightmapSize );
  4446. }
  4447. else
  4448. {
  4449. // transfer the prefix avgcolor data
  4450. memcpy( pNewLighting, pOldLightingBase + pFaces[i].lightofs - nLightmapPrefixSize, nLightmapPrefixSize );
  4451. pNewLighting += nLightmapPrefixSize;
  4452. // advance past the avgcolor prefix data, all other code expects to BACK up to get to it
  4453. nTotalNewLightmapSize += nLightmapPrefixSize;
  4454. // transfer the luxels
  4455. memcpy( pNewLighting, pOldLightingBase + pFaces[i].lightofs, nLightmapSize );
  4456. pNewLighting += nLightmapSize;
  4457. // update (in place) to the packed new luxel offset
  4458. // this face's prior luxels will not be revisited, so update is destructive
  4459. pFaces[i].lightofs = nTotalNewLightmapSize;
  4460. // advance past the luxels
  4461. nTotalNewLightmapSize += nLightmapSize;
  4462. }
  4463. }
  4464. }
  4465. free( pOldLightingBase );
  4466. free( pTexInfos );
  4467. // can't distort unexpected use of helper functions
  4468. g_Lumps.bLumpParsed[LUMP_LIGHTING_HDR] = false;
  4469. g_Lumps.bLumpParsed[LUMP_TEXINFO] = false;
  4470. g_Lumps.bLumpParsed[LUMP_FACES_HDR] = false;
  4471. if ( nTotalNewLightmapSize < nOldTotalLightmapSize )
  4472. {
  4473. // update the lumps
  4474. Msg( "Strip unused lightmap data removed %s.\n", V_pretifymem( nOldTotalLightmapSize - nTotalNewLightmapSize, 2, true ) );
  4475. // altered faces
  4476. g_Lumps.size[LUMP_FACES_HDR] = g_pBSPHeader->lumps[LUMP_FACES_HDR].filelen;
  4477. if ( g_Lumps.pLumps[LUMP_FACES_HDR] )
  4478. {
  4479. free( g_Lumps.pLumps[LUMP_FACES_HDR] );
  4480. g_Lumps.pLumps[LUMP_FACES_HDR] = NULL;
  4481. }
  4482. g_Lumps.pLumps[LUMP_FACES_HDR] = pFaces;
  4483. g_Lumps.bLumpFixed[LUMP_FACES_HDR] = true;
  4484. // altered lighting
  4485. g_Lumps.size[LUMP_LIGHTING_HDR] = nTotalNewLightmapSize;
  4486. if ( g_Lumps.pLumps[LUMP_LIGHTING_HDR] )
  4487. {
  4488. free( g_Lumps.pLumps[LUMP_LIGHTING_HDR] );
  4489. g_Lumps.pLumps[LUMP_LIGHTING_HDR] = NULL;
  4490. }
  4491. g_Lumps.pLumps[LUMP_LIGHTING_HDR] = pNewLightingBase;
  4492. g_Lumps.bLumpFixed[LUMP_LIGHTING_HDR] = true;
  4493. }
  4494. else
  4495. {
  4496. free( pNewLightingBase );
  4497. free( pFaces );
  4498. }
  4499. #endif
  4500. }
  4501. int AlignBuffer( CUtlBuffer &buffer, int alignment )
  4502. {
  4503. unsigned int newPosition = AlignValue( buffer.TellPut(), alignment );
  4504. int padLength = newPosition - buffer.TellPut();
  4505. for ( int i = 0; i<padLength; i++ )
  4506. {
  4507. buffer.PutChar( '\0' );
  4508. }
  4509. return buffer.TellPut();
  4510. }
  4511. struct SortedLump_t
  4512. {
  4513. int lumpNum;
  4514. lump_t *pLump;
  4515. };
  4516. int SortLumpsByOffset( const SortedLump_t *pSortedLumpA, const SortedLump_t *pSortedLumpB )
  4517. {
  4518. int fileOffsetA = pSortedLumpA->pLump->fileofs;
  4519. int fileOffsetB = pSortedLumpB->pLump->fileofs;
  4520. int fileSizeA = pSortedLumpA->pLump->filelen;
  4521. int fileSizeB = pSortedLumpB->pLump->filelen;
  4522. // invalid or empty lumps get sorted together
  4523. if ( !fileSizeA )
  4524. {
  4525. fileOffsetA = 0;
  4526. }
  4527. if ( !fileSizeB )
  4528. {
  4529. fileOffsetB = 0;
  4530. }
  4531. // compare by offset, want ascending
  4532. if ( fileOffsetA < fileOffsetB )
  4533. {
  4534. return -1;
  4535. }
  4536. else if ( fileOffsetA > fileOffsetB )
  4537. {
  4538. return 1;
  4539. }
  4540. return 0;
  4541. }
  4542. bool CompressGameLump( BSPHeader_t *pInBSPHeader, BSPHeader_t *pOutBSPHeader, CUtlBuffer &outputBuffer, CompressFunc_t pCompressFunc )
  4543. {
  4544. CByteswap byteSwap;
  4545. dgamelumpheader_t* pInGameLumpHeader = (dgamelumpheader_t*)(((byte *)pInBSPHeader) + pInBSPHeader->lumps[LUMP_GAME_LUMP].fileofs);
  4546. dgamelump_t* pInGameLump = (dgamelump_t*)(pInGameLumpHeader + 1);
  4547. byteSwap.ActivateByteSwapping( true );
  4548. byteSwap.SwapFieldsToTargetEndian( pInGameLumpHeader );
  4549. byteSwap.SwapFieldsToTargetEndian( pInGameLump, pInGameLumpHeader->lumpCount );
  4550. unsigned int newOffset = outputBuffer.TellPut();
  4551. outputBuffer.Put( pInGameLumpHeader, sizeof( dgamelumpheader_t ) );
  4552. outputBuffer.Put( pInGameLump, pInGameLumpHeader->lumpCount * sizeof( dgamelump_t ) );
  4553. dgamelumpheader_t* pOutGameLumpHeader = (dgamelumpheader_t*)((byte *)outputBuffer.Base() + newOffset );
  4554. dgamelump_t* pOutGameLump = (dgamelump_t*)( pOutGameLumpHeader + 1 );
  4555. // add a dummy terminal gamelump
  4556. // purposely NOT updating the .filelen to reflect the compressed size, but leaving as original size
  4557. // callers use the next entry offset to determine compressed size
  4558. pOutGameLumpHeader->lumpCount++;
  4559. dgamelump_t dummyLump = { 0 };
  4560. outputBuffer.Put( &dummyLump, sizeof( dgamelump_t ) );
  4561. for ( int i = 0; i < pInGameLumpHeader->lumpCount; i++ )
  4562. {
  4563. CUtlBuffer inputBuffer;
  4564. CUtlBuffer compressedBuffer;
  4565. // each sub game lump is relative to the LUMP_GAME_LUMP
  4566. // this allows the 360 to naively reorder and align the lumps around without trashing embedded offsets
  4567. pOutGameLump[i].fileofs = AlignBuffer( outputBuffer, 4 ) - newOffset;
  4568. if ( pInGameLump[i].filelen )
  4569. {
  4570. inputBuffer.SetExternalBuffer( ((byte *)pInBSPHeader) + pInGameLump[i].fileofs, pInGameLump[i].filelen, pInGameLump[i].filelen );
  4571. bool bCompressed = pCompressFunc( inputBuffer, compressedBuffer );
  4572. if ( bCompressed )
  4573. {
  4574. pOutGameLump[i].flags |= GAMELUMPFLAG_COMPRESSED;
  4575. outputBuffer.Put( compressedBuffer.Base(), compressedBuffer.TellPut() );
  4576. compressedBuffer.Purge();
  4577. }
  4578. else
  4579. {
  4580. // as is
  4581. outputBuffer.Put( inputBuffer.Base(), inputBuffer.TellPut() );
  4582. }
  4583. }
  4584. }
  4585. // fix the dummy terminal lump
  4586. int lastLump = pOutGameLumpHeader->lumpCount-1;
  4587. pOutGameLump[lastLump].fileofs = outputBuffer.TellPut() - newOffset;
  4588. // fix the output for 360, swapping it back
  4589. byteSwap.SwapFieldsToTargetEndian( pOutGameLump, pOutGameLumpHeader->lumpCount );
  4590. byteSwap.SwapFieldsToTargetEndian( pOutGameLumpHeader );
  4591. pOutBSPHeader->lumps[LUMP_GAME_LUMP].fileofs = newOffset;
  4592. pOutBSPHeader->lumps[LUMP_GAME_LUMP].filelen = outputBuffer.TellPut() - newOffset;
  4593. return true;
  4594. }
  4595. bool CompressBSP( CUtlBuffer &inputBuffer, CUtlBuffer &outputBuffer, CompressFunc_t pCompressFunc )
  4596. {
  4597. CByteswap byteSwap;
  4598. BSPHeader_t *pInBSPHeader = (BSPHeader_t *)inputBuffer.Base();
  4599. if ( pInBSPHeader->ident != BigLong( IDBSPHEADER ) || !pCompressFunc )
  4600. {
  4601. // only compress 360 bsp's
  4602. return false;
  4603. }
  4604. // bsp is 360, swap the header back
  4605. byteSwap.ActivateByteSwapping( true );
  4606. byteSwap.SwapFieldsToTargetEndian( pInBSPHeader );
  4607. // output will be smaller, use input size as upper bound
  4608. outputBuffer.EnsureCapacity( inputBuffer.TellMaxPut() );
  4609. outputBuffer.Put( pInBSPHeader, sizeof( BSPHeader_t ) );
  4610. BSPHeader_t *pOutBSPHeader = (BSPHeader_t *)outputBuffer.Base();
  4611. // must adhere to input lump's offset order and process according to that, NOT lump num
  4612. // sort by offset order
  4613. CUtlVector< SortedLump_t > sortedLumps;
  4614. for ( int i = 0; i < HEADER_LUMPS; i++ )
  4615. {
  4616. int iIndex = sortedLumps.AddToTail();
  4617. sortedLumps[iIndex].lumpNum = i;
  4618. sortedLumps[iIndex].pLump = &pInBSPHeader->lumps[i];
  4619. }
  4620. sortedLumps.Sort( SortLumpsByOffset );
  4621. // iterate in sorted order
  4622. for ( int i = 0; i < HEADER_LUMPS; ++i )
  4623. {
  4624. SortedLump_t *pSortedLump = &sortedLumps[i];
  4625. int lumpNum = pSortedLump->lumpNum;
  4626. if ( !pSortedLump->pLump->filelen )
  4627. {
  4628. // degenerate
  4629. pOutBSPHeader->lumps[lumpNum].fileofs = 0;
  4630. }
  4631. else
  4632. {
  4633. int alignment = LUMP_ALIGNMENT;
  4634. if ( lumpNum == LUMP_PAKFILE )
  4635. {
  4636. alignment = XBOX_DVD_SECTORSIZE;
  4637. }
  4638. else if ( lumpNum == LUMP_PHYSLEVEL )
  4639. {
  4640. alignment = LUMP_PHYSLEVEL_ALIGNMENT;
  4641. }
  4642. unsigned int newOffset = AlignBuffer( outputBuffer, alignment );
  4643. // only set by compressed lumps, hides the uncompressed size
  4644. *((unsigned int *)pOutBSPHeader->lumps[lumpNum].fourCC) = 0;
  4645. CUtlBuffer inputBuffer;
  4646. inputBuffer.SetExternalBuffer( ((byte *)pInBSPHeader) + pSortedLump->pLump->fileofs, pSortedLump->pLump->filelen, pSortedLump->pLump->filelen );
  4647. if ( lumpNum == LUMP_GAME_LUMP )
  4648. {
  4649. // the game lump has to have each of its components individually compressed
  4650. CompressGameLump( pInBSPHeader, pOutBSPHeader, outputBuffer, pCompressFunc );
  4651. }
  4652. else if ( lumpNum == LUMP_PAKFILE )
  4653. {
  4654. // add as is, compression needs to occur in a seperate pass
  4655. pOutBSPHeader->lumps[lumpNum].fileofs = newOffset;
  4656. outputBuffer.Put( inputBuffer.Base(), inputBuffer.TellPut() );
  4657. }
  4658. else
  4659. {
  4660. CUtlBuffer compressedBuffer;
  4661. bool bCompressed = pCompressFunc( inputBuffer, compressedBuffer );
  4662. if ( bCompressed )
  4663. {
  4664. // placing the uncompressed size in the unused fourCC, will decode at runtime
  4665. *((unsigned int *)pOutBSPHeader->lumps[lumpNum].fourCC) = BigLong( inputBuffer.TellPut() );
  4666. pOutBSPHeader->lumps[lumpNum].filelen = compressedBuffer.TellPut();
  4667. pOutBSPHeader->lumps[lumpNum].fileofs = newOffset;
  4668. outputBuffer.Put( compressedBuffer.Base(), compressedBuffer.TellPut() );
  4669. compressedBuffer.Purge();
  4670. }
  4671. else
  4672. {
  4673. // add as is
  4674. pOutBSPHeader->lumps[lumpNum].fileofs = newOffset;
  4675. outputBuffer.Put( inputBuffer.Base(), inputBuffer.TellPut() );
  4676. }
  4677. }
  4678. }
  4679. }
  4680. // fix the output for 360, swapping it back
  4681. byteSwap.SetTargetBigEndian( true );
  4682. byteSwap.SwapFieldsToTargetEndian( pOutBSPHeader );
  4683. return true;
  4684. }
  4685. //-----------------------------------------------------------------------------
  4686. // For all lumps in a bsp: Loads the lump from file A, swaps it, writes it to file B.
  4687. // This limits the memory used for the swap process which helps the Xbox 360.
  4688. //
  4689. // NOTE: These lumps will be written to the file in exactly the order they appear here,
  4690. // so they can be shifted around if desired for file access optimization.
  4691. //-----------------------------------------------------------------------------
  4692. bool SwapBSPFile( const char *pInFilename, const char *pOutFilename, bool bSwapOnLoad, VTFConvertFunc_t pVTFConvertFunc, VHVFixupFunc_t pVHVFixupFunc, StudioConvertFunc_t pStudioConvertFunc, CompressFunc_t pCompressFunc, char const *szPlatform )
  4693. {
  4694. DevMsg( "Creating %s\n", pOutFilename );
  4695. if ( !g_pFileSystem->FileExists( pInFilename ) )
  4696. {
  4697. Warning( "Error! Couldn't open input file %s - BSP swap failed!\n", pInFilename );
  4698. return false;
  4699. }
  4700. g_hBSPFile = SafeOpenWrite( pOutFilename );
  4701. if ( !g_hBSPFile )
  4702. {
  4703. Warning( "Error! Couldn't open output file %s - BSP swap failed!\n", pOutFilename );
  4704. return false;
  4705. }
  4706. if ( !pVTFConvertFunc )
  4707. {
  4708. Warning( "Error! Missing VTF Conversion function\n" );
  4709. return false;
  4710. }
  4711. g_pVTFConvertFunc = pVTFConvertFunc;
  4712. // studio mdl file (mdl, vhv, vtx) swapper
  4713. g_pStudioConvertFunc = pStudioConvertFunc;
  4714. // optional VHV fixup
  4715. g_pVHVFixupFunc = pVHVFixupFunc;
  4716. // optional compression callback
  4717. g_pCompressFunc = pCompressFunc;
  4718. // These must be mutually exclusive
  4719. g_bSwapOnLoad = bSwapOnLoad;
  4720. g_bSwapOnWrite = !bSwapOnLoad;
  4721. g_Swap.ActivateByteSwapping( true );
  4722. OpenBSPFile( pInFilename );
  4723. // CRC the bsp first
  4724. CRC32_t mapCRC;
  4725. CRC32_Init(&mapCRC);
  4726. if ( !CRC_MapFile( &mapCRC, pInFilename ) )
  4727. {
  4728. Warning( "Failed to CRC the bsp\n" );
  4729. return false;
  4730. }
  4731. // PC bloats the lightmap data for sun shadow support ~10-20% bloat
  4732. // the 360 does not ship with this feature
  4733. // the extra data burdens the loading footprint
  4734. // strip and fixup prior to packing
  4735. // !!!
  4736. // !!! The non obvious fact of this pre-fixup is that downstream code CANNOT rely on the BSP version of these "fixed" lumps.
  4737. // !!! and must read from the "fixed" store to perform any further swap work.
  4738. // !!! This function only runs ***ONCE*** as part of the first pass of the two-pass BSP swap (first pass swaps, second pass fixes pak file).
  4739. // !!!
  4740. StripUnusedLightmapAlphaData();
  4741. // hold a dictionary of all the static prop names
  4742. // this is needed to properly convert any VHV files inside the pak lump
  4743. BuildStaticPropNameTable();
  4744. // Set the output file pointer after the header
  4745. BSPHeader_t dummyHeader = { 0 };
  4746. SafeWrite( g_hBSPFile, &dummyHeader, sizeof( BSPHeader_t ) );
  4747. // To allow for alignment fixups, the lumps will be written to the
  4748. // output file in the order they appear in this function.
  4749. // NOTE: Flags for 360 !!!MUST!!! be first
  4750. SwapLumpToDisk< dflagslump_t >( LUMP_MAP_FLAGS );
  4751. // NOTE: Order critical for the 360
  4752. // complex lump swaps first or for later contingent data
  4753. {
  4754. SwapLeafLumpToDisk();
  4755. SwapOcclusionLumpToDisk();
  4756. // Game lumps embed an absolute offset, and must occur now
  4757. // before other lumps that perform alignment bloating (i.e. lump_physlevel)
  4758. SwapGameLumpsToDisk();
  4759. }
  4760. // Strip dead or non relevant lumps
  4761. g_pBSPHeader->lumps[LUMP_DISP_LIGHTMAP_ALPHAS].filelen = 0;
  4762. g_pBSPHeader->lumps[LUMP_FACEIDS].filelen = 0;
  4763. g_pBSPHeader->lumps[LUMP_ORIGINALFACES].filelen = 0;
  4764. g_pBSPHeader->lumps[LUMP_FACE_MACRO_TEXTURE_INFO].filelen = 0;
  4765. g_pBSPHeader->lumps[LUMP_PROP_BLOB].filelen = 0;
  4766. g_pBSPHeader->lumps[LUMP_XZIPPAKFILE].filelen = 0;
  4767. g_pBSPHeader->lumps[LUMP_DISP_MULTIBLEND].filelen = 0;
  4768. // For PORTAL2 Only:
  4769. // Removing any support for Dlights, so the displacement data is not needed
  4770. g_pBSPHeader->lumps[LUMP_DISP_LIGHTMAP_SAMPLE_POSITIONS].filelen = 0;
  4771. if ( !g_pPhysics2 )
  4772. {
  4773. g_pBSPHeader->lumps[LUMP_PHYSLEVEL].filelen = 0;
  4774. }
  4775. if ( SwapLumpToDisk<dface_t>( LUMP_FACES_HDR ) )
  4776. {
  4777. // has HDR, strip obsolete LDR in favor of HDR
  4778. g_pBSPHeader->lumps[LUMP_FACES].filelen = 0;
  4779. }
  4780. else
  4781. {
  4782. // no HDR, keep LDR version
  4783. SwapLumpToDisk<dface_t>( LUMP_FACES );
  4784. }
  4785. SwapWorldLightsToDisk();
  4786. // Simple lump swaps
  4787. SwapLumpToDisk<byte>( FIELD_CHARACTER, LUMP_PHYSDISP );
  4788. SwapLumpToDisk<byte>( FIELD_CHARACTER, LUMP_PHYSCOLLIDE );
  4789. SwapLumpToDisk<byte>( FIELD_CHARACTER, LUMP_PHYSLEVEL );
  4790. SwapLumpToDisk<byte>( FIELD_CHARACTER, LUMP_VISIBILITY );
  4791. SwapLumpToDisk<dmodel_t>( LUMP_MODELS );
  4792. SwapLumpToDisk<dvertex_t>( LUMP_VERTEXES );
  4793. SwapLumpToDisk<dplane_t>( LUMP_PLANES );
  4794. SwapLumpToDisk<dnode_t>( LUMP_NODES );
  4795. SwapLumpToDisk<texinfo_t>( LUMP_TEXINFO );
  4796. SwapLumpToDisk<dtexdata_t>( LUMP_TEXDATA );
  4797. SwapLumpToDisk<ddispinfo_t>( LUMP_DISPINFO );
  4798. SwapLumpToDisk<CDispVert>( LUMP_DISP_VERTS );
  4799. SwapLumpToDisk<CDispTri>( LUMP_DISP_TRIS );
  4800. SwapLumpToDisk<char>( FIELD_CHARACTER, LUMP_DISP_LIGHTMAP_SAMPLE_POSITIONS );
  4801. SwapLumpToDisk<CFaceMacroTextureInfo>( LUMP_FACE_MACRO_TEXTURE_INFO );
  4802. SwapLumpToDisk<dprimitive_t>( LUMP_PRIMITIVES );
  4803. SwapLumpToDisk<dprimvert_t>( LUMP_PRIMVERTS );
  4804. SwapLumpToDisk<unsigned short>( FIELD_SHORT, LUMP_PRIMINDICES );
  4805. SwapLumpToDisk<dface_t>( LUMP_ORIGINALFACES );
  4806. SwapLumpToDisk<unsigned short>( FIELD_SHORT, LUMP_LEAFFACES );
  4807. SwapLumpToDisk<unsigned short>( FIELD_SHORT, LUMP_LEAFBRUSHES );
  4808. SwapLumpToDisk<unsigned short>( FIELD_SHORT, LUMP_FACEBRUSHES );
  4809. SwapLumpToDisk<dfacebrushlist_t>( LUMP_FACEBRUSHLIST );
  4810. SwapLumpToDisk<int>( FIELD_INTEGER, LUMP_SURFEDGES );
  4811. SwapLumpToDisk<dedge_t>( LUMP_EDGES );
  4812. SwapLumpToDisk<dbrush_t>( LUMP_BRUSHES );
  4813. SwapLumpToDisk<dbrushside_t>( LUMP_BRUSHSIDES );
  4814. SwapLumpToDisk<darea_t>( LUMP_AREAS );
  4815. SwapLumpToDisk<dareaportal_t>( LUMP_AREAPORTALS );
  4816. SwapLumpToDisk<char>( FIELD_CHARACTER, LUMP_ENTITIES );
  4817. SwapLumpToDisk<dleafwaterdata_t>( LUMP_LEAFWATERDATA );
  4818. SwapLumpToDisk<float>( FIELD_VECTOR, LUMP_VERTNORMALS );
  4819. SwapLumpToDisk<short>( FIELD_SHORT, LUMP_VERTNORMALINDICES );
  4820. SwapLumpToDisk<float>( FIELD_VECTOR, LUMP_CLIPPORTALVERTS );
  4821. SwapLumpToDisk<dcubemapsample_t>( LUMP_CUBEMAPS );
  4822. SwapLumpToDisk<char>( FIELD_CHARACTER, LUMP_TEXDATA_STRING_DATA );
  4823. SwapLumpToDisk<int>( FIELD_INTEGER, LUMP_TEXDATA_STRING_TABLE );
  4824. SwapLumpToDisk<doverlay_t>( LUMP_OVERLAYS );
  4825. SwapLumpToDisk<dwateroverlay_t>( LUMP_WATEROVERLAYS );
  4826. SwapLumpToDisk<unsigned short>( FIELD_SHORT, LUMP_LEAFMINDISTTOWATER );
  4827. SwapLumpToDisk<doverlayfade_t>( LUMP_OVERLAY_FADES );
  4828. SwapLumpToDisk<doverlaysystemlevel_t>( LUMP_OVERLAY_SYSTEM_LEVELS );
  4829. // NOTE: this data placed at the end specifically and expected by the 360:
  4830. {
  4831. // NOTE: lighting must be the penultimate lump
  4832. // (allows 360 to free this memory part-way through map loading)
  4833. if ( SwapLumpToDisk<byte>( FIELD_CHARACTER, LUMP_LIGHTING_HDR ) )
  4834. {
  4835. g_pBSPHeader->lumps[LUMP_LIGHTING].filelen = 0;
  4836. }
  4837. else
  4838. {
  4839. // no HDR, keep LDR version
  4840. SwapLumpToDisk<byte>( FIELD_CHARACTER, LUMP_LIGHTING );
  4841. }
  4842. // NOTE: Pakfile for 360 !!!MUST!!! be last
  4843. SwapPakfileLumpToDisk( pInFilename, szPlatform );
  4844. }
  4845. // Store the crc in the flags lump version field
  4846. g_pBSPHeader->lumps[LUMP_MAP_FLAGS].version = mapCRC;
  4847. // Pad out the end of the file to a sector boundary for optimal IO
  4848. AlignFilePosition( g_hBSPFile, XBOX_DVD_SECTORSIZE );
  4849. // Warn of any lumps that didn't get swapped
  4850. for ( int i = 0; i < HEADER_LUMPS; ++i )
  4851. {
  4852. if ( HasLump( i ) && !g_Lumps.bLumpParsed[i] )
  4853. {
  4854. // a new lump got added that needs to have a swap function
  4855. Warning( "BSP: '%s', lump #%d: %s has no swap or copy function. Discarding!\n", pInFilename, i, GetLumpName(i) );
  4856. // the data didn't get copied, so don't reference garbage
  4857. g_pBSPHeader->lumps[i].filelen = 0;
  4858. }
  4859. }
  4860. // Write the updated header
  4861. g_pFileSystem->Seek( g_hBSPFile, 0, FILESYSTEM_SEEK_HEAD );
  4862. WriteData( g_pBSPHeader );
  4863. g_pFileSystem->Close( g_hBSPFile );
  4864. g_hBSPFile = 0;
  4865. // Cleanup
  4866. g_Swap.ActivateByteSwapping( false );
  4867. CloseBSPFile();
  4868. g_StaticPropNames.Purge();
  4869. g_StaticPropInstances.Purge();
  4870. DevMsg( "Finished BSP Swap\n" );
  4871. // caller provided compress func will further compress compatible lumps
  4872. if ( pCompressFunc )
  4873. {
  4874. CUtlBuffer inputBuffer;
  4875. if ( !g_pFileSystem->ReadFile( pOutFilename, NULL, inputBuffer ) )
  4876. {
  4877. Warning( "Error! Couldn't read file %s - final BSP compression failed!\n", pOutFilename );
  4878. return false;
  4879. }
  4880. CUtlBuffer outputBuffer;
  4881. if ( !CompressBSP( inputBuffer, outputBuffer, pCompressFunc ) )
  4882. {
  4883. Warning( "Error! Failed to compress BSP '%s'!\n", pOutFilename );
  4884. return false;
  4885. }
  4886. g_hBSPFile = SafeOpenWrite( pOutFilename );
  4887. if ( !g_hBSPFile )
  4888. {
  4889. Warning( "Error! Couldn't open output file %s - BSP swap failed!\n", pOutFilename );
  4890. return false;
  4891. }
  4892. SafeWrite( g_hBSPFile, outputBuffer.Base(), outputBuffer.TellPut() );
  4893. g_pFileSystem->Close( g_hBSPFile );
  4894. g_hBSPFile = 0;
  4895. }
  4896. return true;
  4897. }
  4898. //-----------------------------------------------------------------------------
  4899. // Get the pak lump from a BSP
  4900. //-----------------------------------------------------------------------------
  4901. bool GetPakFileLump( const char *pBSPFilename, void **pPakData, int *pPakSize )
  4902. {
  4903. *pPakData = NULL;
  4904. *pPakSize = 0;
  4905. if ( !g_pFileSystem->FileExists( pBSPFilename ) )
  4906. {
  4907. Warning( "Error! Couldn't open file %s!\n", pBSPFilename );
  4908. return false;
  4909. }
  4910. // determine endian nature
  4911. BSPHeader_t *pHeader;
  4912. LoadFile( pBSPFilename, (void **)&pHeader );
  4913. bool bSwap = ( pHeader->ident == BigLong( IDBSPHEADER ) );
  4914. free( pHeader );
  4915. g_bSwapOnLoad = bSwap;
  4916. g_bSwapOnWrite = !bSwap;
  4917. OpenBSPFile( pBSPFilename );
  4918. if ( g_pBSPHeader->lumps[LUMP_PAKFILE].filelen )
  4919. {
  4920. *pPakSize = CopyVariableLump<byte>( FIELD_CHARACTER, LUMP_PAKFILE, pPakData );
  4921. }
  4922. CloseBSPFile();
  4923. return true;
  4924. }
  4925. // compare function for qsort below
  4926. static int LumpOffsetCompare( const void *pElem1, const void *pElem2 )
  4927. {
  4928. int lump1 = *(byte *)pElem1;
  4929. int lump2 = *(byte *)pElem2;
  4930. if ( lump1 != lump2 )
  4931. {
  4932. // force LUMP_MAP_FLAGS to be first, always
  4933. if ( lump1 == LUMP_MAP_FLAGS )
  4934. {
  4935. return -1;
  4936. }
  4937. else if ( lump2 == LUMP_MAP_FLAGS )
  4938. {
  4939. return 1;
  4940. }
  4941. // force LUMP_PAKFILE to be last, always
  4942. if ( lump1 == LUMP_PAKFILE )
  4943. {
  4944. return 1;
  4945. }
  4946. else if ( lump2 == LUMP_PAKFILE )
  4947. {
  4948. return -1;
  4949. }
  4950. }
  4951. int fileOffset1 = g_pBSPHeader->lumps[lump1].fileofs;
  4952. int fileOffset2 = g_pBSPHeader->lumps[lump2].fileofs;
  4953. // invalid or empty lumps will get sorted together
  4954. if ( !g_pBSPHeader->lumps[lump1].filelen )
  4955. {
  4956. fileOffset1 = 0;
  4957. }
  4958. if ( !g_pBSPHeader->lumps[lump2].filelen )
  4959. {
  4960. fileOffset2 = 0;
  4961. }
  4962. // compare by offset
  4963. if ( fileOffset1 < fileOffset2 )
  4964. {
  4965. return -1;
  4966. }
  4967. else if ( fileOffset1 > fileOffset2 )
  4968. {
  4969. return 1;
  4970. }
  4971. return 0;
  4972. }
  4973. //-----------------------------------------------------------------------------
  4974. // Replace the pak lump in a BSP. This is strictly for the 360 conversion process
  4975. // and encodes expected properties of the BSP w.r.t lumps, their positions, and
  4976. // alignments.
  4977. //-----------------------------------------------------------------------------
  4978. bool SetPakFileLump( const char *pBSPFilename, const char *pNewFilename, void *pPakData, int pakSize )
  4979. {
  4980. if ( !g_pFileSystem->FileExists( pBSPFilename ) )
  4981. {
  4982. Warning( "Error! Couldn't open file %s!\n", pBSPFilename );
  4983. return false;
  4984. }
  4985. // determine endian nature
  4986. BSPHeader_t *pHeader;
  4987. LoadFile( pBSPFilename, (void **)&pHeader );
  4988. bool bSwap = ( pHeader->ident == BigLong( IDBSPHEADER ) );
  4989. free( pHeader );
  4990. g_bSwapOnLoad = bSwap;
  4991. g_bSwapOnWrite = bSwap;
  4992. OpenBSPFile( pBSPFilename );
  4993. // save a copy of the old header
  4994. // generating a new bsp is a destructive operation
  4995. BSPHeader_t oldHeader;
  4996. oldHeader = *g_pBSPHeader;
  4997. g_hBSPFile = SafeOpenWrite( pNewFilename );
  4998. if ( !g_hBSPFile )
  4999. {
  5000. return false;
  5001. }
  5002. // placeholder only, reset at conclusion
  5003. WriteData( &oldHeader );
  5004. // lumps must be reserialized in same relative offset order
  5005. // build sorted order table
  5006. int readOrder[HEADER_LUMPS];
  5007. for ( int i=0; i<HEADER_LUMPS; i++ )
  5008. {
  5009. readOrder[i] = i;
  5010. }
  5011. qsort( readOrder, HEADER_LUMPS, sizeof( int ), LumpOffsetCompare );
  5012. for ( int i = 0; i < HEADER_LUMPS; i++ )
  5013. {
  5014. int lump = readOrder[i];
  5015. if ( lump == LUMP_PAKFILE )
  5016. {
  5017. // pak lump always written last, with special alignment
  5018. continue;
  5019. }
  5020. int length = g_pBSPHeader->lumps[lump].filelen;
  5021. if ( length )
  5022. {
  5023. // get the expected read position
  5024. int offset = g_pBSPHeader->lumps[lump].fileofs;
  5025. // set the write position
  5026. int nAlignment = LUMP_ALIGNMENT;
  5027. if ( lump == LUMP_PHYSLEVEL )
  5028. {
  5029. nAlignment = LUMP_PHYSLEVEL_ALIGNMENT;
  5030. }
  5031. SetAlignedLumpPosition( lump, nAlignment );
  5032. // save the data
  5033. SafeWrite( g_hBSPFile, (byte *)g_pBSPHeader + offset, length );
  5034. }
  5035. else
  5036. {
  5037. g_pBSPHeader->lumps[lump].fileofs = 0;
  5038. }
  5039. }
  5040. // Always write the pak file at the end
  5041. // Pad out the end of the file to a sector boundary for optimal IO
  5042. g_pBSPHeader->lumps[LUMP_PAKFILE].fileofs = AlignFilePosition( g_hBSPFile, XBOX_DVD_SECTORSIZE );
  5043. g_pBSPHeader->lumps[LUMP_PAKFILE].filelen = pakSize;
  5044. SafeWrite( g_hBSPFile, pPakData, pakSize );
  5045. // Pad out the end of the file to a sector boundary for optimal IO
  5046. AlignFilePosition( g_hBSPFile, XBOX_DVD_SECTORSIZE );
  5047. // Write the updated header
  5048. g_pFileSystem->Seek( g_hBSPFile, 0, FILESYSTEM_SEEK_HEAD );
  5049. WriteData( g_pBSPHeader );
  5050. g_pFileSystem->Close( g_hBSPFile );
  5051. CloseBSPFile();
  5052. return true;
  5053. }
  5054. //-----------------------------------------------------------------------------
  5055. // Build a list of files that BSP owns, world/cubemap materials, static props, etc.
  5056. //-----------------------------------------------------------------------------
  5057. bool GetBSPDependants( const char *pBSPFilename, CUtlVector< CUtlString > *pList )
  5058. {
  5059. if ( !g_pFileSystem->FileExists( pBSPFilename ) )
  5060. {
  5061. Warning( "Error! Couldn't open file %s!\n", pBSPFilename );
  5062. return false;
  5063. }
  5064. // must be set, but exact hdr not critical for dependant traversal
  5065. SetHDRMode( false );
  5066. LoadBSPFile( pBSPFilename );
  5067. char szBspName[MAX_PATH];
  5068. V_FileBase( pBSPFilename, szBspName, sizeof( szBspName ) );
  5069. V_SetExtension( szBspName, ".bsp", sizeof( szBspName ) );
  5070. // get embedded pak files, and internals
  5071. char szFilename[MAX_PATH];
  5072. int fileSize;
  5073. int fileId = -1;
  5074. for ( ;; )
  5075. {
  5076. fileId = GetPakFile()->GetNextFilename( fileId, szFilename, sizeof( szFilename ), fileSize );
  5077. if ( fileId == -1 )
  5078. {
  5079. break;
  5080. }
  5081. pList->AddToTail( szFilename );
  5082. }
  5083. // get all the world materials
  5084. for ( int i=0; i<numtexdata; i++ )
  5085. {
  5086. const char *pName = TexDataStringTable_GetString( dtexdata[i].nameStringTableID );
  5087. V_ComposeFileName( "materials", pName, szFilename, sizeof( szFilename ) );
  5088. V_SetExtension( szFilename, ".vmt", sizeof( szFilename ) );
  5089. pList->AddToTail( szFilename );
  5090. }
  5091. // get all the static props
  5092. GameLumpHandle_t hGameLump = g_GameLumps.GetGameLumpHandle( GAMELUMP_STATIC_PROPS );
  5093. if ( hGameLump != g_GameLumps.InvalidGameLump() )
  5094. {
  5095. byte *pGameLumpData = (byte *)g_GameLumps.GetGameLump( hGameLump );
  5096. if ( pGameLumpData && g_GameLumps.GameLumpSize( hGameLump ) )
  5097. {
  5098. int count = ((int *)pGameLumpData)[0];
  5099. pGameLumpData += sizeof( int );
  5100. StaticPropDictLump_t *pStaticPropDictLump = (StaticPropDictLump_t *)pGameLumpData;
  5101. for ( int i=0; i<count; i++ )
  5102. {
  5103. pList->AddToTail( pStaticPropDictLump[i].m_Name );
  5104. }
  5105. }
  5106. }
  5107. // get all the detail props
  5108. hGameLump = g_GameLumps.GetGameLumpHandle( GAMELUMP_DETAIL_PROPS );
  5109. if ( hGameLump != g_GameLumps.InvalidGameLump() )
  5110. {
  5111. byte *pGameLumpData = (byte *)g_GameLumps.GetGameLump( hGameLump );
  5112. if ( pGameLumpData && g_GameLumps.GameLumpSize( hGameLump ) )
  5113. {
  5114. int count = ((int *)pGameLumpData)[0];
  5115. pGameLumpData += sizeof( int );
  5116. DetailObjectDictLump_t *pDetailObjectDictLump = (DetailObjectDictLump_t *)pGameLumpData;
  5117. for ( int i=0; i<count; i++ )
  5118. {
  5119. pList->AddToTail( pDetailObjectDictLump[i].m_Name );
  5120. }
  5121. pGameLumpData += count * sizeof( DetailObjectDictLump_t );
  5122. if ( g_GameLumps.GetGameLumpVersion( hGameLump ) == 4 )
  5123. {
  5124. count = ((int *)pGameLumpData)[0];
  5125. pGameLumpData += sizeof( int );
  5126. if ( count )
  5127. {
  5128. // All detail prop sprites must lie in the material detail/detailsprites
  5129. pList->AddToTail( "materials/detail/detailsprites.vmt" );
  5130. }
  5131. }
  5132. }
  5133. }
  5134. // Get all the physics excludes
  5135. dphyslevelV0_t *pPhysLevelData = (dphyslevelV0_t *)g_pPhysLevel;
  5136. if ( g_PhysLevelSize && pPhysLevelData && pPhysLevelData->dataVersion == dphyslevelV0_t::DATA_VERSION )
  5137. {
  5138. char szFilename[MAX_PATH];
  5139. for( int i = 0; i < pPhysLevelData->levelStaticModels.size; ++i )
  5140. {
  5141. const char *pPhz = pPhysLevelData->levelStaticModels[i];
  5142. // These MDLs need to exclude their PHZs
  5143. V_strncpy( szFilename, pPhz, sizeof( szFilename ) );
  5144. V_SetExtension( szFilename, ".phz", sizeof( szFilename ) );
  5145. // add with prefix exclude token
  5146. pList->AddToTail( CFmtStr( "*%s", szFilename ).Access() );
  5147. }
  5148. }
  5149. UnloadBSPFile();
  5150. return true;
  5151. }