PageRenderTime 118ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 2ms

/model_brush.c

https://gitlab.com/xonotic/darkplaces
C | 8790 lines | 7317 code | 714 blank | 759 comment | 1736 complexity | bdcd1e0e15402d0330593af75e6a1f84 MD5 | raw file
Possible License(s): GPL-2.0
  1. /*
  2. Copyright (C) 1996-1997 Id Software, Inc.
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either version 2
  6. of the License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. See the GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  14. */
  15. #include "quakedef.h"
  16. #include "image.h"
  17. #include "r_shadow.h"
  18. #include "polygon.h"
  19. #include "curves.h"
  20. #include "wad.h"
  21. //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128", "how large water polygons should be (smaller values produce more polygons which give better warping effects)"};
  22. cvar_t mod_bsp_portalize = {0, "mod_bsp_portalize", "1", "enables portal generation from BSP tree (may take several seconds per map), used by r_drawportals, r_useportalculling, r_shadow_realtime_world_compileportalculling, sv_cullentities_portal"};
  23. cvar_t r_novis = {0, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
  24. cvar_t r_nosurftextures = {0, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
  25. cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4", "maximum error tolerance on curve subdivision for rendering purposes (in other words, the curves will be given as many polygons as necessary to represent curves at this quality)"};
  26. cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
  27. cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
  28. cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
  29. cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
  30. cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
  31. cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
  32. cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
  33. cvar_t r_trippy = {0, "r_trippy", "0", "easter egg"};
  34. cvar_t r_fxaa = {CVAR_SAVE, "r_fxaa", "0", "fast approximate anti aliasing"};
  35. cvar_t mod_noshader_default_offsetmapping = {CVAR_SAVE, "mod_noshader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are not using q3 shader files"};
  36. cvar_t mod_obj_orientation = {0, "mod_obj_orientation", "1", "fix orientation of OBJ models to the usual conventions (if zero, use coordinates as is)"};
  37. cvar_t mod_q2bsp_littransparentsurfaces = {0, "mod_q2bsp_littransparentsurfaces", "0", "allows lighting on rain in 3v3gloom3 and other cases of transparent surfaces that have lightmaps that were ignored by quake2"};
  38. cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
  39. cvar_t mod_q3bsp_curves_collisions_stride = {0, "mod_q3bsp_curves_collisions_stride", "16", "collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
  40. cvar_t mod_q3bsp_curves_stride = {0, "mod_q3bsp_curves_stride", "16", "particle effect collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
  41. cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
  42. cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
  43. cvar_t mod_q3bsp_lightmapmergepower = {CVAR_SAVE, "mod_q3bsp_lightmapmergepower", "4", "merges the quake3 128x128 lightmap textures into larger lightmap group textures to speed up rendering, 1 = 256x256, 2 = 512x512, 3 = 1024x1024, 4 = 2048x2048, 5 = 4096x4096, ..."};
  44. cvar_t mod_q3bsp_nolightmaps = {CVAR_SAVE, "mod_q3bsp_nolightmaps", "0", "do not load lightmaps in Q3BSP maps (to save video RAM, but be warned: it looks ugly)"};
  45. cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
  46. cvar_t mod_q3bsp_sRGBlightmaps = {0, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
  47. cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are using q3 shader files"};
  48. cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
  49. cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
  50. cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
  51. cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
  52. cvar_t mod_q3shader_force_addalpha = {0, "mod_q3shader_force_addalpha", "0", "treat GL_ONE GL_ONE (or add) blendfunc as GL_SRC_ALPHA GL_ONE for compatibility with older DarkPlaces releases"};
  53. cvar_t mod_q3shader_force_terrain_alphaflag = {0, "mod_q3shader_force_terrain_alphaflag", "0", "for multilayered terrain shaders force TEXF_ALPHA flag on both layers"};
  54. cvar_t mod_q1bsp_polygoncollisions = {0, "mod_q1bsp_polygoncollisions", "0", "disables use of precomputed cliphulls and instead collides with polygons (uses Bounding Interval Hierarchy optimizations)"};
  55. cvar_t mod_collision_bih = {0, "mod_collision_bih", "1", "enables use of generated Bounding Interval Hierarchy tree instead of compiled bsp tree in collision code"};
  56. cvar_t mod_recalculatenodeboxes = {0, "mod_recalculatenodeboxes", "1", "enables use of generated node bounding boxes based on BSP tree portal reconstruction, rather than the node boxes supplied by the map compiler"};
  57. static texture_t mod_q1bsp_texture_solid;
  58. static texture_t mod_q1bsp_texture_sky;
  59. static texture_t mod_q1bsp_texture_lava;
  60. static texture_t mod_q1bsp_texture_slime;
  61. static texture_t mod_q1bsp_texture_water;
  62. static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs);
  63. void Mod_BrushInit(void)
  64. {
  65. // Cvar_RegisterVariable(&r_subdivide_size);
  66. Cvar_RegisterVariable(&mod_bsp_portalize);
  67. Cvar_RegisterVariable(&r_novis);
  68. Cvar_RegisterVariable(&r_nosurftextures);
  69. Cvar_RegisterVariable(&r_subdivisions_tolerance);
  70. Cvar_RegisterVariable(&r_subdivisions_mintess);
  71. Cvar_RegisterVariable(&r_subdivisions_maxtess);
  72. Cvar_RegisterVariable(&r_subdivisions_maxvertices);
  73. Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
  74. Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
  75. Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
  76. Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
  77. Cvar_RegisterVariable(&r_trippy);
  78. Cvar_RegisterVariable(&r_fxaa);
  79. Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
  80. Cvar_RegisterVariable(&mod_obj_orientation);
  81. Cvar_RegisterVariable(&mod_q2bsp_littransparentsurfaces);
  82. Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
  83. Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
  84. Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
  85. Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
  86. Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
  87. Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
  88. Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
  89. Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
  90. Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
  91. Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
  92. Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
  93. Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
  94. Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
  95. Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
  96. Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
  97. Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
  98. Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
  99. Cvar_RegisterVariable(&mod_collision_bih);
  100. Cvar_RegisterVariable(&mod_recalculatenodeboxes);
  101. // these games were made for older DP engines and are no longer
  102. // maintained; use this hack to show their textures properly
  103. if(gamemode == GAME_NEXUIZ)
  104. Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
  105. memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
  106. strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
  107. mod_q1bsp_texture_solid.surfaceflags = 0;
  108. mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
  109. mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
  110. strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
  111. mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
  112. mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
  113. mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
  114. strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
  115. mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
  116. mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
  117. mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
  118. strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
  119. mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
  120. mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
  121. mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
  122. strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
  123. mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
  124. mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
  125. }
  126. static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
  127. {
  128. mnode_t *node;
  129. if (model == NULL)
  130. return NULL;
  131. // LordHavoc: modified to start at first clip node,
  132. // in other words: first node of the (sub)model
  133. node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
  134. while (node->plane)
  135. node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
  136. return (mleaf_t *)node;
  137. }
  138. static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
  139. {
  140. int i;
  141. mleaf_t *leaf;
  142. leaf = Mod_Q1BSP_PointInLeaf(model, p);
  143. if (leaf)
  144. {
  145. i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
  146. if (i)
  147. {
  148. memcpy(out, leaf->ambient_sound_level, i);
  149. out += i;
  150. outsize -= i;
  151. }
  152. }
  153. if (outsize)
  154. memset(out, 0, outsize);
  155. }
  156. static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
  157. {
  158. int numclusters = 0;
  159. int nodestackindex = 0;
  160. mnode_t *node, *nodestack[1024];
  161. if (!model->brush.num_pvsclusters)
  162. return -1;
  163. node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
  164. for (;;)
  165. {
  166. #if 1
  167. if (node->plane)
  168. {
  169. // node - recurse down the BSP tree
  170. int sides = BoxOnPlaneSide(mins, maxs, node->plane);
  171. if (sides < 3)
  172. {
  173. if (sides == 0)
  174. return -1; // ERROR: NAN bounding box!
  175. // box is on one side of plane, take that path
  176. node = node->children[sides-1];
  177. }
  178. else
  179. {
  180. // box crosses plane, take one path and remember the other
  181. if (nodestackindex < 1024)
  182. nodestack[nodestackindex++] = node->children[0];
  183. node = node->children[1];
  184. }
  185. continue;
  186. }
  187. else
  188. {
  189. // leaf - add clusterindex to list
  190. if (numclusters < maxclusters)
  191. clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
  192. numclusters++;
  193. }
  194. #else
  195. if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
  196. {
  197. if (node->plane)
  198. {
  199. if (nodestackindex < 1024)
  200. nodestack[nodestackindex++] = node->children[0];
  201. node = node->children[1];
  202. continue;
  203. }
  204. else
  205. {
  206. // leaf - add clusterindex to list
  207. if (numclusters < maxclusters)
  208. clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
  209. numclusters++;
  210. }
  211. }
  212. #endif
  213. // try another path we didn't take earlier
  214. if (nodestackindex == 0)
  215. break;
  216. node = nodestack[--nodestackindex];
  217. }
  218. // return number of clusters found (even if more than the maxclusters)
  219. return numclusters;
  220. }
  221. static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
  222. {
  223. int nodestackindex = 0;
  224. mnode_t *node, *nodestack[1024];
  225. if (!model->brush.num_pvsclusters)
  226. return true;
  227. node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
  228. for (;;)
  229. {
  230. #if 1
  231. if (node->plane)
  232. {
  233. // node - recurse down the BSP tree
  234. int sides = BoxOnPlaneSide(mins, maxs, node->plane);
  235. if (sides < 3)
  236. {
  237. if (sides == 0)
  238. return -1; // ERROR: NAN bounding box!
  239. // box is on one side of plane, take that path
  240. node = node->children[sides-1];
  241. }
  242. else
  243. {
  244. // box crosses plane, take one path and remember the other
  245. if (nodestackindex < 1024)
  246. nodestack[nodestackindex++] = node->children[0];
  247. node = node->children[1];
  248. }
  249. continue;
  250. }
  251. else
  252. {
  253. // leaf - check cluster bit
  254. int clusterindex = ((mleaf_t *)node)->clusterindex;
  255. if (CHECKPVSBIT(pvs, clusterindex))
  256. {
  257. // it is visible, return immediately with the news
  258. return true;
  259. }
  260. }
  261. #else
  262. if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
  263. {
  264. if (node->plane)
  265. {
  266. if (nodestackindex < 1024)
  267. nodestack[nodestackindex++] = node->children[0];
  268. node = node->children[1];
  269. continue;
  270. }
  271. else
  272. {
  273. // leaf - check cluster bit
  274. int clusterindex = ((mleaf_t *)node)->clusterindex;
  275. if (CHECKPVSBIT(pvs, clusterindex))
  276. {
  277. // it is visible, return immediately with the news
  278. return true;
  279. }
  280. }
  281. }
  282. #endif
  283. // nothing to see here, try another path we didn't take earlier
  284. if (nodestackindex == 0)
  285. break;
  286. node = nodestack[--nodestackindex];
  287. }
  288. // it is not visible
  289. return false;
  290. }
  291. static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
  292. {
  293. int nodestackindex = 0;
  294. mnode_t *node, *nodestack[1024];
  295. if (!model->brush.num_leafs)
  296. return true;
  297. node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
  298. for (;;)
  299. {
  300. #if 1
  301. if (node->plane)
  302. {
  303. // node - recurse down the BSP tree
  304. int sides = BoxOnPlaneSide(mins, maxs, node->plane);
  305. if (sides < 3)
  306. {
  307. if (sides == 0)
  308. return -1; // ERROR: NAN bounding box!
  309. // box is on one side of plane, take that path
  310. node = node->children[sides-1];
  311. }
  312. else
  313. {
  314. // box crosses plane, take one path and remember the other
  315. if (nodestackindex < 1024)
  316. nodestack[nodestackindex++] = node->children[0];
  317. node = node->children[1];
  318. }
  319. continue;
  320. }
  321. else
  322. {
  323. // leaf - check cluster bit
  324. int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
  325. if (CHECKPVSBIT(pvs, clusterindex))
  326. {
  327. // it is visible, return immediately with the news
  328. return true;
  329. }
  330. }
  331. #else
  332. if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
  333. {
  334. if (node->plane)
  335. {
  336. if (nodestackindex < 1024)
  337. nodestack[nodestackindex++] = node->children[0];
  338. node = node->children[1];
  339. continue;
  340. }
  341. else
  342. {
  343. // leaf - check cluster bit
  344. int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
  345. if (CHECKPVSBIT(pvs, clusterindex))
  346. {
  347. // it is visible, return immediately with the news
  348. return true;
  349. }
  350. }
  351. }
  352. #endif
  353. // nothing to see here, try another path we didn't take earlier
  354. if (nodestackindex == 0)
  355. break;
  356. node = nodestack[--nodestackindex];
  357. }
  358. // it is not visible
  359. return false;
  360. }
  361. static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
  362. {
  363. int nodestackindex = 0;
  364. mnode_t *node, *nodestack[1024];
  365. if (!model->brush.num_leafs)
  366. return true;
  367. node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
  368. for (;;)
  369. {
  370. #if 1
  371. if (node->plane)
  372. {
  373. // node - recurse down the BSP tree
  374. int sides = BoxOnPlaneSide(mins, maxs, node->plane);
  375. if (sides < 3)
  376. {
  377. if (sides == 0)
  378. return -1; // ERROR: NAN bounding box!
  379. // box is on one side of plane, take that path
  380. node = node->children[sides-1];
  381. }
  382. else
  383. {
  384. // box crosses plane, take one path and remember the other
  385. if (nodestackindex < 1024)
  386. nodestack[nodestackindex++] = node->children[0];
  387. node = node->children[1];
  388. }
  389. continue;
  390. }
  391. else
  392. {
  393. // leaf - check if it is visible
  394. if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
  395. {
  396. // it is visible, return immediately with the news
  397. return true;
  398. }
  399. }
  400. #else
  401. if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
  402. {
  403. if (node->plane)
  404. {
  405. if (nodestackindex < 1024)
  406. nodestack[nodestackindex++] = node->children[0];
  407. node = node->children[1];
  408. continue;
  409. }
  410. else
  411. {
  412. // leaf - check if it is visible
  413. if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
  414. {
  415. // it is visible, return immediately with the news
  416. return true;
  417. }
  418. }
  419. }
  420. #endif
  421. // nothing to see here, try another path we didn't take earlier
  422. if (nodestackindex == 0)
  423. break;
  424. node = nodestack[--nodestackindex];
  425. }
  426. // it is not visible
  427. return false;
  428. }
  429. typedef struct findnonsolidlocationinfo_s
  430. {
  431. vec3_t center;
  432. vec3_t absmin, absmax;
  433. vec_t radius;
  434. vec3_t nudge;
  435. vec_t bestdist;
  436. dp_model_t *model;
  437. }
  438. findnonsolidlocationinfo_t;
  439. static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
  440. {
  441. int i, *tri;
  442. float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
  443. tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
  444. VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
  445. VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
  446. VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
  447. VectorSubtract(vert[1], vert[0], edge[0]);
  448. VectorSubtract(vert[2], vert[1], edge[1]);
  449. CrossProduct(edge[1], edge[0], facenormal);
  450. if (facenormal[0] || facenormal[1] || facenormal[2])
  451. {
  452. VectorNormalize(facenormal);
  453. f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
  454. if (f <= info->bestdist && f >= -info->bestdist)
  455. {
  456. VectorSubtract(vert[0], vert[2], edge[2]);
  457. VectorNormalize(edge[0]);
  458. VectorNormalize(edge[1]);
  459. VectorNormalize(edge[2]);
  460. CrossProduct(facenormal, edge[0], edgenormal[0]);
  461. CrossProduct(facenormal, edge[1], edgenormal[1]);
  462. CrossProduct(facenormal, edge[2], edgenormal[2]);
  463. // face distance
  464. if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
  465. && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
  466. && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
  467. {
  468. // we got lucky, the center is within the face
  469. dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
  470. if (dist < 0)
  471. {
  472. dist = -dist;
  473. if (info->bestdist > dist)
  474. {
  475. info->bestdist = dist;
  476. VectorScale(facenormal, (info->radius - -dist), info->nudge);
  477. }
  478. }
  479. else
  480. {
  481. if (info->bestdist > dist)
  482. {
  483. info->bestdist = dist;
  484. VectorScale(facenormal, (info->radius - dist), info->nudge);
  485. }
  486. }
  487. }
  488. else
  489. {
  490. // check which edge or vertex the center is nearest
  491. for (i = 0;i < 3;i++)
  492. {
  493. f = DotProduct(info->center, edge[i]);
  494. if (f >= DotProduct(vert[0], edge[i])
  495. && f <= DotProduct(vert[1], edge[i]))
  496. {
  497. // on edge
  498. VectorMA(info->center, -f, edge[i], point);
  499. dist = sqrt(DotProduct(point, point));
  500. if (info->bestdist > dist)
  501. {
  502. info->bestdist = dist;
  503. VectorScale(point, (info->radius / dist), info->nudge);
  504. }
  505. // skip both vertex checks
  506. // (both are further away than this edge)
  507. i++;
  508. }
  509. else
  510. {
  511. // not on edge, check first vertex of edge
  512. VectorSubtract(info->center, vert[i], point);
  513. dist = sqrt(DotProduct(point, point));
  514. if (info->bestdist > dist)
  515. {
  516. info->bestdist = dist;
  517. VectorScale(point, (info->radius / dist), info->nudge);
  518. }
  519. }
  520. }
  521. }
  522. }
  523. }
  524. }
  525. static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
  526. {
  527. int surfacenum, k, *mark;
  528. msurface_t *surface;
  529. for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
  530. {
  531. surface = info->model->data_surfaces + *mark;
  532. if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
  533. {
  534. if(surface->deprecatedq3num_bboxstride > 0)
  535. {
  536. int i, cnt, tri;
  537. cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
  538. for(i = 0; i < cnt; ++i)
  539. {
  540. if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
  541. {
  542. for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
  543. {
  544. tri = i * surface->deprecatedq3num_bboxstride + k;
  545. if(tri >= surface->num_triangles)
  546. break;
  547. Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
  548. }
  549. }
  550. }
  551. }
  552. else
  553. {
  554. for (k = 0;k < surface->num_triangles;k++)
  555. {
  556. Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
  557. }
  558. }
  559. }
  560. }
  561. }
  562. static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
  563. {
  564. if (node->plane)
  565. {
  566. float f = PlaneDiff(info->center, node->plane);
  567. if (f >= -info->bestdist)
  568. Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
  569. if (f <= info->bestdist)
  570. Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
  571. }
  572. else
  573. {
  574. if (((mleaf_t *)node)->numleafsurfaces)
  575. Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
  576. }
  577. }
  578. static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
  579. {
  580. int i;
  581. findnonsolidlocationinfo_t info;
  582. if (model == NULL)
  583. {
  584. VectorCopy(in, out);
  585. return;
  586. }
  587. VectorCopy(in, info.center);
  588. info.radius = radius;
  589. info.model = model;
  590. i = 0;
  591. do
  592. {
  593. VectorClear(info.nudge);
  594. info.bestdist = radius;
  595. VectorCopy(info.center, info.absmin);
  596. VectorCopy(info.center, info.absmax);
  597. info.absmin[0] -= info.radius + 1;
  598. info.absmin[1] -= info.radius + 1;
  599. info.absmin[2] -= info.radius + 1;
  600. info.absmax[0] += info.radius + 1;
  601. info.absmax[1] += info.radius + 1;
  602. info.absmax[2] += info.radius + 1;
  603. Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
  604. VectorAdd(info.center, info.nudge, info.center);
  605. }
  606. while (info.bestdist < radius && ++i < 10);
  607. VectorCopy(info.center, out);
  608. }
  609. int Mod_Q1BSP_SuperContentsFromNativeContents(int nativecontents)
  610. {
  611. switch(nativecontents)
  612. {
  613. case CONTENTS_EMPTY:
  614. return 0;
  615. case CONTENTS_SOLID:
  616. return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
  617. case CONTENTS_WATER:
  618. return SUPERCONTENTS_WATER;
  619. case CONTENTS_SLIME:
  620. return SUPERCONTENTS_SLIME;
  621. case CONTENTS_LAVA:
  622. return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
  623. case CONTENTS_SKY:
  624. return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
  625. }
  626. return 0;
  627. }
  628. int Mod_Q1BSP_NativeContentsFromSuperContents(int supercontents)
  629. {
  630. if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
  631. return CONTENTS_SOLID;
  632. if (supercontents & SUPERCONTENTS_SKY)
  633. return CONTENTS_SKY;
  634. if (supercontents & SUPERCONTENTS_LAVA)
  635. return CONTENTS_LAVA;
  636. if (supercontents & SUPERCONTENTS_SLIME)
  637. return CONTENTS_SLIME;
  638. if (supercontents & SUPERCONTENTS_WATER)
  639. return CONTENTS_WATER;
  640. return CONTENTS_EMPTY;
  641. }
  642. typedef struct RecursiveHullCheckTraceInfo_s
  643. {
  644. // the hull we're tracing through
  645. const hull_t *hull;
  646. // the trace structure to fill in
  647. trace_t *trace;
  648. // start, end, and end - start (in model space)
  649. double start[3];
  650. double end[3];
  651. double dist[3];
  652. }
  653. RecursiveHullCheckTraceInfo_t;
  654. // 1/32 epsilon to keep floating point happy
  655. #define DIST_EPSILON (0.03125)
  656. #define HULLCHECKSTATE_EMPTY 0
  657. #define HULLCHECKSTATE_SOLID 1
  658. #define HULLCHECKSTATE_DONE 2
  659. static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
  660. {
  661. // status variables, these don't need to be saved on the stack when
  662. // recursing... but are because this should be thread-safe
  663. // (note: tracing against a bbox is not thread-safe, yet)
  664. int ret;
  665. mplane_t *plane;
  666. double t1, t2;
  667. // variables that need to be stored on the stack when recursing
  668. mclipnode_t *node;
  669. int p1side, p2side;
  670. double midf, mid[3];
  671. // keep looping until we hit a leaf
  672. while (num >= 0)
  673. {
  674. // find the point distances
  675. node = t->hull->clipnodes + num;
  676. plane = t->hull->planes + node->planenum;
  677. // axial planes can be calculated more quickly without the DotProduct
  678. if (plane->type < 3)
  679. {
  680. t1 = p1[plane->type] - plane->dist;
  681. t2 = p2[plane->type] - plane->dist;
  682. }
  683. else
  684. {
  685. t1 = DotProduct (plane->normal, p1) - plane->dist;
  686. t2 = DotProduct (plane->normal, p2) - plane->dist;
  687. }
  688. // negative plane distances indicate children[1] (behind plane)
  689. p1side = t1 < 0;
  690. p2side = t2 < 0;
  691. // if the line starts and ends on the same side of the plane, recurse
  692. // into that child instantly
  693. if (p1side == p2side)
  694. {
  695. #if COLLISIONPARANOID >= 3
  696. if (p1side)
  697. Con_Print("<");
  698. else
  699. Con_Print(">");
  700. #endif
  701. // loop back and process the start child
  702. num = node->children[p1side];
  703. }
  704. else
  705. {
  706. // find the midpoint where the line crosses the plane, use the
  707. // original line for best accuracy
  708. #if COLLISIONPARANOID >= 3
  709. Con_Print("M");
  710. #endif
  711. if (plane->type < 3)
  712. {
  713. t1 = t->start[plane->type] - plane->dist;
  714. t2 = t->end[plane->type] - plane->dist;
  715. }
  716. else
  717. {
  718. t1 = DotProduct (plane->normal, t->start) - plane->dist;
  719. t2 = DotProduct (plane->normal, t->end) - plane->dist;
  720. }
  721. midf = t1 / (t1 - t2);
  722. midf = bound(p1f, midf, p2f);
  723. VectorMA(t->start, midf, t->dist, mid);
  724. // we now have a mid point, essentially splitting the line into
  725. // the segments in the near child and the far child, we can now
  726. // recurse those in order and get their results
  727. // recurse both sides, front side first
  728. ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
  729. // if this side is not empty, return what it is (solid or done)
  730. if (ret != HULLCHECKSTATE_EMPTY)
  731. return ret;
  732. ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
  733. // if other side is not solid, return what it is (empty or done)
  734. if (ret != HULLCHECKSTATE_SOLID)
  735. return ret;
  736. // front is air and back is solid, this is the impact point...
  737. // copy the plane information, flipping it if needed
  738. if (p1side)
  739. {
  740. t->trace->plane.dist = -plane->dist;
  741. VectorNegate (plane->normal, t->trace->plane.normal);
  742. }
  743. else
  744. {
  745. t->trace->plane.dist = plane->dist;
  746. VectorCopy (plane->normal, t->trace->plane.normal);
  747. }
  748. // calculate the return fraction which is nudged off the surface a bit
  749. t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
  750. t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
  751. midf = (t1 - collision_impactnudge.value) / (t1 - t2);
  752. t->trace->fraction = bound(0, midf, 1);
  753. #if COLLISIONPARANOID >= 3
  754. Con_Print("D");
  755. #endif
  756. return HULLCHECKSTATE_DONE;
  757. }
  758. }
  759. // we reached a leaf contents
  760. // check for empty
  761. num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
  762. if (!t->trace->startfound)
  763. {
  764. t->trace->startfound = true;
  765. t->trace->startsupercontents |= num;
  766. }
  767. if (num & SUPERCONTENTS_LIQUIDSMASK)
  768. t->trace->inwater = true;
  769. if (num == 0)
  770. t->trace->inopen = true;
  771. if (num & SUPERCONTENTS_SOLID)
  772. t->trace->hittexture = &mod_q1bsp_texture_solid;
  773. else if (num & SUPERCONTENTS_SKY)
  774. t->trace->hittexture = &mod_q1bsp_texture_sky;
  775. else if (num & SUPERCONTENTS_LAVA)
  776. t->trace->hittexture = &mod_q1bsp_texture_lava;
  777. else if (num & SUPERCONTENTS_SLIME)
  778. t->trace->hittexture = &mod_q1bsp_texture_slime;
  779. else
  780. t->trace->hittexture = &mod_q1bsp_texture_water;
  781. t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
  782. t->trace->hitsupercontents = num;
  783. if (num & t->trace->hitsupercontentsmask)
  784. {
  785. // if the first leaf is solid, set startsolid
  786. if (t->trace->allsolid)
  787. t->trace->startsolid = true;
  788. #if COLLISIONPARANOID >= 3
  789. Con_Print("S");
  790. #endif
  791. return HULLCHECKSTATE_SOLID;
  792. }
  793. else
  794. {
  795. t->trace->allsolid = false;
  796. #if COLLISIONPARANOID >= 3
  797. Con_Print("E");
  798. #endif
  799. return HULLCHECKSTATE_EMPTY;
  800. }
  801. }
  802. //#if COLLISIONPARANOID < 2
  803. static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
  804. {
  805. mplane_t *plane;
  806. mclipnode_t *nodes = t->hull->clipnodes;
  807. mplane_t *planes = t->hull->planes;
  808. vec3_t point;
  809. VectorCopy(t->start, point);
  810. while (num >= 0)
  811. {
  812. plane = planes + nodes[num].planenum;
  813. num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
  814. }
  815. num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
  816. t->trace->startsupercontents |= num;
  817. if (num & SUPERCONTENTS_LIQUIDSMASK)
  818. t->trace->inwater = true;
  819. if (num == 0)
  820. t->trace->inopen = true;
  821. if (num & t->trace->hitsupercontentsmask)
  822. {
  823. t->trace->allsolid = t->trace->startsolid = true;
  824. return HULLCHECKSTATE_SOLID;
  825. }
  826. else
  827. {
  828. t->trace->allsolid = t->trace->startsolid = false;
  829. return HULLCHECKSTATE_EMPTY;
  830. }
  831. }
  832. //#endif
  833. static void Mod_Q1BSP_TracePoint(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  834. {
  835. RecursiveHullCheckTraceInfo_t rhc;
  836. memset(&rhc, 0, sizeof(rhc));
  837. memset(trace, 0, sizeof(trace_t));
  838. rhc.trace = trace;
  839. rhc.trace->fraction = 1;
  840. rhc.trace->allsolid = true;
  841. rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
  842. VectorCopy(start, rhc.start);
  843. VectorCopy(start, rhc.end);
  844. Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
  845. }
  846. static void Mod_Q1BSP_TraceLineAgainstSurfaces(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask);
  847. static void Mod_Q1BSP_TraceLine(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  848. {
  849. RecursiveHullCheckTraceInfo_t rhc;
  850. if (VectorCompare(start, end))
  851. {
  852. Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  853. return;
  854. }
  855. // sometimes we want to traceline against polygons so we can report the texture that was hit rather than merely a contents, but using this method breaks one of negke's maps so it must be a cvar check...
  856. if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
  857. {
  858. Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  859. return;
  860. }
  861. memset(&rhc, 0, sizeof(rhc));
  862. memset(trace, 0, sizeof(trace_t));
  863. rhc.trace = trace;
  864. rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
  865. rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
  866. rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
  867. rhc.trace->fraction = 1;
  868. rhc.trace->allsolid = true;
  869. rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
  870. VectorCopy(start, rhc.start);
  871. VectorCopy(end, rhc.end);
  872. VectorSubtract(rhc.end, rhc.start, rhc.dist);
  873. #if COLLISIONPARANOID >= 2
  874. Con_Printf("t(%f %f %f,%f %f %f)", rhc.start[0], rhc.start[1], rhc.start[2], rhc.end[0], rhc.end[1], rhc.end[2]);
  875. Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
  876. {
  877. double test[3];
  878. trace_t testtrace;
  879. VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
  880. memset(&testtrace, 0, sizeof(trace_t));
  881. rhc.trace = &testtrace;
  882. rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
  883. rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
  884. rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
  885. rhc.trace->fraction = 1;
  886. rhc.trace->allsolid = true;
  887. VectorCopy(test, rhc.start);
  888. VectorCopy(test, rhc.end);
  889. VectorClear(rhc.dist);
  890. Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
  891. //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
  892. if (!trace->startsolid && testtrace.startsolid)
  893. Con_Printf(" - ended in solid!\n");
  894. }
  895. Con_Print("\n");
  896. #else
  897. if (VectorLength2(rhc.dist))
  898. Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
  899. else
  900. Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
  901. #endif
  902. }
  903. static void Mod_Q1BSP_TraceBox(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  904. {
  905. // this function currently only supports same size start and end
  906. double boxsize[3];
  907. RecursiveHullCheckTraceInfo_t rhc;
  908. if (VectorCompare(boxmins, boxmaxs))
  909. {
  910. if (VectorCompare(start, end))
  911. Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  912. else
  913. Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  914. return;
  915. }
  916. memset(&rhc, 0, sizeof(rhc));
  917. memset(trace, 0, sizeof(trace_t));
  918. rhc.trace = trace;
  919. rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
  920. rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
  921. rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
  922. rhc.trace->fraction = 1;
  923. rhc.trace->allsolid = true;
  924. VectorSubtract(boxmaxs, boxmins, boxsize);
  925. if (boxsize[0] < 3)
  926. rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
  927. else if (model->brush.ishlbsp)
  928. {
  929. // LordHavoc: this has to have a minor tolerance (the .1) because of
  930. // minor float precision errors from the box being transformed around
  931. if (boxsize[0] < 32.1)
  932. {
  933. if (boxsize[2] < 54) // pick the nearest of 36 or 72
  934. rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
  935. else
  936. rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
  937. }
  938. else
  939. rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
  940. }
  941. else
  942. {
  943. // LordHavoc: this has to have a minor tolerance (the .1) because of
  944. // minor float precision errors from the box being transformed around
  945. if (boxsize[0] < 32.1)
  946. rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
  947. else
  948. rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
  949. }
  950. VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
  951. VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
  952. VectorSubtract(rhc.end, rhc.start, rhc.dist);
  953. #if COLLISIONPARANOID >= 2
  954. Con_Printf("t(%f %f %f,%f %f %f,%i %f %f %f)", rhc.start[0], rhc.start[1], rhc.start[2], rhc.end[0], rhc.end[1], rhc.end[2], rhc.hull - model->brushq1.hulls, rhc.hull->clip_mins[0], rhc.hull->clip_mins[1], rhc.hull->clip_mins[2]);
  955. Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
  956. {
  957. double test[3];
  958. trace_t testtrace;
  959. VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
  960. memset(&testtrace, 0, sizeof(trace_t));
  961. rhc.trace = &testtrace;
  962. rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
  963. rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
  964. rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
  965. rhc.trace->fraction = 1;
  966. rhc.trace->allsolid = true;
  967. VectorCopy(test, rhc.start);
  968. VectorCopy(test, rhc.end);
  969. VectorClear(rhc.dist);
  970. Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
  971. //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
  972. if (!trace->startsolid && testtrace.startsolid)
  973. Con_Printf(" - ended in solid!\n");
  974. }
  975. Con_Print("\n");
  976. #else
  977. if (VectorLength2(rhc.dist))
  978. Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
  979. else
  980. Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
  981. #endif
  982. }
  983. static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
  984. {
  985. int num = model->brushq1.hulls[0].firstclipnode;
  986. mplane_t *plane;
  987. mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
  988. mplane_t *planes = model->brushq1.hulls[0].planes;
  989. while (num >= 0)
  990. {
  991. plane = planes + nodes[num].planenum;
  992. num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
  993. }
  994. return Mod_Q1BSP_SuperContentsFromNativeContents(num);
  995. }
  996. void Collision_ClipTrace_Box(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
  997. {
  998. #if 1
  999. colbrushf_t cbox;
  1000. colplanef_t cbox_planes[6];
  1001. cbox.isaabb = true;
  1002. cbox.hasaabbplanes = true;
  1003. cbox.supercontents = boxsupercontents;
  1004. cbox.numplanes = 6;
  1005. cbox.numpoints = 0;
  1006. cbox.numtriangles = 0;
  1007. cbox.planes = cbox_planes;
  1008. cbox.points = NULL;
  1009. cbox.elements = NULL;
  1010. cbox.markframe = 0;
  1011. cbox.mins[0] = 0;
  1012. cbox.mins[1] = 0;
  1013. cbox.mins[2] = 0;
  1014. cbox.maxs[0] = 0;
  1015. cbox.maxs[1] = 0;
  1016. cbox.maxs[2] = 0;
  1017. cbox_planes[0].normal[0] = 1;cbox_planes[0].normal[1] = 0;cbox_planes[0].normal[2] = 0;cbox_planes[0].dist = cmaxs[0] - mins[0];
  1018. cbox_planes[1].normal[0] = -1;cbox_planes[1].normal[1] = 0;cbox_planes[1].normal[2] = 0;cbox_planes[1].dist = maxs[0] - cmins[0];
  1019. cbox_planes[2].normal[0] = 0;cbox_planes[2].normal[1] = 1;cbox_planes[2].normal[2] = 0;cbox_planes[2].dist = cmaxs[1] - mins[1];
  1020. cbox_planes[3].normal[0] = 0;cbox_planes[3].normal[1] = -1;cbox_planes[3].normal[2] = 0;cbox_planes[3].dist = maxs[1] - cmins[1];
  1021. cbox_planes[4].normal[0] = 0;cbox_planes[4].normal[1] = 0;cbox_planes[4].normal[2] = 1;cbox_planes[4].dist = cmaxs[2] - mins[2];
  1022. cbox_planes[5].normal[0] = 0;cbox_planes[5].normal[1] = 0;cbox_planes[5].normal[2] = -1;cbox_planes[5].dist = maxs[2] - cmins[2];
  1023. cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
  1024. cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
  1025. cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
  1026. cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
  1027. cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
  1028. cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
  1029. memset(trace, 0, sizeof(trace_t));
  1030. trace->hitsupercontentsmask = hitsupercontentsmask;
  1031. trace->skipsupercontentsmask = skipsupercontentsmask;
  1032. trace->skipmaterialflagsmask = skipmaterialflagsmask;
  1033. trace->fraction = 1;
  1034. Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
  1035. #else
  1036. RecursiveHullCheckTraceInfo_t rhc;
  1037. static hull_t box_hull;
  1038. static mclipnode_t box_clipnodes[6];
  1039. static mplane_t box_planes[6];
  1040. // fill in a default trace
  1041. memset(&rhc, 0, sizeof(rhc));
  1042. memset(trace, 0, sizeof(trace_t));
  1043. //To keep everything totally uniform, bounding boxes are turned into small
  1044. //BSP trees instead of being compared directly.
  1045. // create a temp hull from bounding box sizes
  1046. box_planes[0].dist = cmaxs[0] - mins[0];
  1047. box_planes[1].dist = cmins[0] - maxs[0];
  1048. box_planes[2].dist = cmaxs[1] - mins[1];
  1049. box_planes[3].dist = cmins[1] - maxs[1];
  1050. box_planes[4].dist = cmaxs[2] - mins[2];
  1051. box_planes[5].dist = cmins[2] - maxs[2];
  1052. #if COLLISIONPARANOID >= 3
  1053. Con_Printf("box_planes %f:%f %f:%f %f:%f\ncbox %f %f %f:%f %f %f\nbox %f %f %f:%f %f %f\n", box_planes[0].dist, box_planes[1].dist, box_planes[2].dist, box_planes[3].dist, box_planes[4].dist, box_planes[5].dist, cmins[0], cmins[1], cmins[2], cmaxs[0], cmaxs[1], cmaxs[2], mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]);
  1054. #endif
  1055. if (box_hull.clipnodes == NULL)
  1056. {
  1057. int i, side;
  1058. //Set up the planes and clipnodes so that the six floats of a bounding box
  1059. //can just be stored out and get a proper hull_t structure.
  1060. box_hull.clipnodes = box_clipnodes;
  1061. box_hull.planes = box_planes;
  1062. box_hull.firstclipnode = 0;
  1063. box_hull.lastclipnode = 5;
  1064. for (i = 0;i < 6;i++)
  1065. {
  1066. box_clipnodes[i].planenum = i;
  1067. side = i&1;
  1068. box_clipnodes[i].children[side] = CONTENTS_EMPTY;
  1069. if (i != 5)
  1070. box_clipnodes[i].children[side^1] = i + 1;
  1071. else
  1072. box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
  1073. box_planes[i].type = i>>1;
  1074. box_planes[i].normal[i>>1] = 1;
  1075. }
  1076. }
  1077. // trace a line through the generated clipping hull
  1078. //rhc.boxsupercontents = boxsupercontents;
  1079. rhc.hull = &box_hull;
  1080. rhc.trace = trace;
  1081. rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
  1082. rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
  1083. rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
  1084. rhc.trace->fraction = 1;
  1085. rhc.trace->allsolid = true;
  1086. VectorCopy(start, rhc.start);
  1087. VectorCopy(end, rhc.end);
  1088. VectorSubtract(rhc.end, rhc.start, rhc.dist);
  1089. Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
  1090. //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
  1091. if (rhc.trace->startsupercontents)
  1092. rhc.trace->startsupercontents = boxsupercontents;
  1093. #endif
  1094. }
  1095. void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
  1096. {
  1097. memset(trace, 0, sizeof(trace_t));
  1098. trace->fraction = 1;
  1099. trace->hitsupercontentsmask = hitsupercontentsmask;
  1100. trace->skipsupercontentsmask = skipsupercontentsmask;
  1101. trace->skipmaterialflagsmask = skipmaterialflagsmask;
  1102. if (BoxesOverlap(start, start, cmins, cmaxs))
  1103. {
  1104. trace->startsupercontents |= boxsupercontents;
  1105. if ((hitsupercontentsmask & boxsupercontents) && !(skipsupercontentsmask & boxsupercontents))
  1106. {
  1107. trace->startsolid = true;
  1108. trace->allsolid = true;
  1109. }
  1110. }
  1111. }
  1112. static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
  1113. {
  1114. trace_t trace;
  1115. Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
  1116. return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
  1117. }
  1118. static int Mod_Q1BSP_LightPoint_RecursiveBSPNode(dp_model_t *model, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
  1119. {
  1120. int side;
  1121. float front, back;
  1122. float mid, distz = endz - startz;
  1123. while (node->plane)
  1124. {
  1125. switch (node->plane->type)
  1126. {
  1127. case PLANE_X:
  1128. node = node->children[x < node->plane->dist];
  1129. continue; // loop back and process the new node
  1130. case PLANE_Y:
  1131. node = node->children[y < node->plane->dist];
  1132. continue; // loop back and process the new node
  1133. case PLANE_Z:
  1134. side = startz < node->plane->dist;
  1135. if ((endz < node->plane->dist) == side)
  1136. {
  1137. node = node->children[side];
  1138. continue; // loop back and process the new node
  1139. }
  1140. // found an intersection
  1141. mid = node->plane->dist;
  1142. break;
  1143. default:
  1144. back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
  1145. front += startz * node->plane->normal[2];
  1146. back += endz * node->plane->normal[2];
  1147. side = front < node->plane->dist;
  1148. if ((back < node->plane->dist) == side)
  1149. {
  1150. node = node->children[side];
  1151. continue; // loop back and process the new node
  1152. }
  1153. // found an intersection
  1154. mid = startz + distz * (front - node->plane->dist) / (front - back);
  1155. break;
  1156. }
  1157. // go down front side
  1158. if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
  1159. return true; // hit something
  1160. // check for impact on this node
  1161. if (node->numsurfaces)
  1162. {
  1163. unsigned int i;
  1164. int dsi, dti, lmwidth, lmheight;
  1165. float ds, dt;
  1166. msurface_t *surface;
  1167. unsigned char *lightmap;
  1168. int maps, line3, size3;
  1169. float dsfrac;
  1170. float dtfrac;
  1171. float scale, w, w00, w01, w10, w11;
  1172. surface = model->data_surfaces + node->firstsurface;
  1173. for (i = 0;i < node->numsurfaces;i++, surface++)
  1174. {
  1175. if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
  1176. continue; // no lightmaps
  1177. // location we want to sample in the lightmap
  1178. ds = ((x * surface->lightmapinfo->texinfo->vecs[0][0] + y * surface->lightmapinfo->texinfo->vecs[0][1] + mid * surface->lightmapinfo->texinfo->vecs[0][2] + surface->lightmapinfo->texinfo->vecs[0][3]) - surface->lightmapinfo->texturemins[0]) * 0.0625f;
  1179. dt = ((x * surface->lightmapinfo->texinfo->vecs[1][0] + y * surface->lightmapinfo->texinfo->vecs[1][1] + mid * surface->lightmapinfo->texinfo->vecs[1][2] + surface->lightmapinfo->texinfo->vecs[1][3]) - surface->lightmapinfo->texturemins[1]) * 0.0625f;
  1180. // check the bounds
  1181. // thanks to jitspoe for pointing out that this int cast was
  1182. // rounding toward zero, so we floor it
  1183. dsi = (int)floor(ds);
  1184. dti = (int)floor(dt);
  1185. lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
  1186. lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
  1187. // is it in bounds?
  1188. // we have to tolerate a position of lmwidth-1 for some rare
  1189. // cases - in which case the sampling position still gets
  1190. // clamped but the color gets interpolated to that edge.
  1191. if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
  1192. {
  1193. // in the rare cases where we're sampling slightly off
  1194. // the polygon, clamp the sampling position (we can still
  1195. // interpolate outside it, where it becomes extrapolation)
  1196. if (dsi < 0)
  1197. dsi = 0;
  1198. if (dti < 0)
  1199. dti = 0;
  1200. if (dsi > lmwidth-2)
  1201. dsi = lmwidth-2;
  1202. if (dti > lmheight-2)
  1203. dti = lmheight-2;
  1204. // calculate bilinear interpolation factors
  1205. // and also multiply by fixedpoint conversion factors to
  1206. // compensate for lightmaps being 0-255 (as 0-2), we use
  1207. // r_refdef.scene.rtlightstylevalue here which is already
  1208. // 0.000-2.148 range
  1209. // (if we used r_refdef.scene.lightstylevalue this
  1210. // divisor would be 32768 rather than 128)
  1211. dsfrac = ds - dsi;
  1212. dtfrac = dt - dti;
  1213. w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
  1214. w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
  1215. w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 128.0f);
  1216. w11 = ( dsfrac) * ( dtfrac) * (1.0f / 128.0f);
  1217. // values for pointer math
  1218. line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
  1219. size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
  1220. // look up the pixel
  1221. lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
  1222. // bilinear filter each lightmap style, and sum them
  1223. for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
  1224. {
  1225. scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
  1226. w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
  1227. w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
  1228. w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
  1229. w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
  1230. lightmap += size3;
  1231. }
  1232. return true; // success
  1233. }
  1234. }
  1235. }
  1236. // go down back side
  1237. node = node->children[side ^ 1];
  1238. startz = mid;
  1239. distz = endz - startz;
  1240. // loop back and process the new node
  1241. }
  1242. // did not hit anything
  1243. return false;
  1244. }
  1245. static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
  1246. {
  1247. // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
  1248. VectorSet(diffusenormal, 0, 0, 1);
  1249. if (!model->brushq1.lightdata)
  1250. {
  1251. VectorSet(ambientcolor, 1, 1, 1);
  1252. VectorSet(diffusecolor, 0, 0, 0);
  1253. return;
  1254. }
  1255. Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, p[0], p[1], p[2] + 0.125, p[2] - 65536);
  1256. }
  1257. static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
  1258. {
  1259. unsigned int i;
  1260. int j;
  1261. int k;
  1262. const msurface_t *surface;
  1263. float normal[3];
  1264. float v0[3];
  1265. float v1[3];
  1266. float edgedir[3];
  1267. float edgenormal[3];
  1268. float p[4];
  1269. float midf;
  1270. float t1;
  1271. float t2;
  1272. VectorCopy(mid, p);
  1273. p[3] = 1;
  1274. surface = model->data_surfaces + node->firstsurface;
  1275. for (i = 0;i < node->numsurfaces;i++, surface++)
  1276. {
  1277. // skip surfaces whose bounding box does not include the point
  1278. // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
  1279. // continue;
  1280. // skip faces with contents we don't care about
  1281. if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
  1282. continue;
  1283. // ignore surfaces matching the skipsupercontentsmask (this is rare)
  1284. if (t->trace->skipsupercontentsmask & surface->texture->supercontents)
  1285. continue;
  1286. // skip surfaces matching the skipmaterialflagsmask (e.g. MATERIALFLAG_NOSHADOW)
  1287. if (t->trace->skipmaterialflagsmask & surface->texture->currentmaterialflags)
  1288. continue;
  1289. // get the surface normal - since it is flat we know any vertex normal will suffice
  1290. VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
  1291. // skip backfaces
  1292. if (DotProduct(t->dist, normal) > 0)
  1293. continue;
  1294. // iterate edges and see if the point is outside one of them
  1295. for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
  1296. {
  1297. VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
  1298. VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
  1299. VectorSubtract(v0, v1, edgedir);
  1300. CrossProduct(edgedir, normal, edgenormal);
  1301. if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
  1302. break;
  1303. }
  1304. // if the point is outside one of the edges, it is not within the surface
  1305. if (j < surface->num_vertices)
  1306. continue;
  1307. // we hit a surface, this is the impact point...
  1308. VectorCopy(normal, t->trace->plane.normal);
  1309. t->trace->plane.dist = DotProduct(normal, p);
  1310. // calculate the return fraction which is nudged off the surface a bit
  1311. t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
  1312. t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
  1313. midf = (t1 - collision_impactnudge.value) / (t1 - t2);
  1314. t->trace->fraction = bound(0, midf, 1);
  1315. t->trace->hittexture = surface->texture->currentframe;
  1316. t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
  1317. t->trace->hitsupercontents = t->trace->hittexture->supercontents;
  1318. return surface->texture->currentframe;
  1319. }
  1320. return NULL;
  1321. }
  1322. static int Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, const double p1[3], const double p2[3])
  1323. {
  1324. const mplane_t *plane;
  1325. double t1, t2;
  1326. int side;
  1327. double midf, mid[3];
  1328. const mleaf_t *leaf;
  1329. while (node->plane)
  1330. {
  1331. plane = node->plane;
  1332. if (plane->type < 3)
  1333. {
  1334. t1 = p1[plane->type] - plane->dist;
  1335. t2 = p2[plane->type] - plane->dist;
  1336. }
  1337. else
  1338. {
  1339. t1 = DotProduct (plane->normal, p1) - plane->dist;
  1340. t2 = DotProduct (plane->normal, p2) - plane->dist;
  1341. }
  1342. if (t1 < 0)
  1343. {
  1344. if (t2 < 0)
  1345. {
  1346. node = node->children[1];
  1347. continue;
  1348. }
  1349. side = 1;
  1350. }
  1351. else
  1352. {
  1353. if (t2 >= 0)
  1354. {
  1355. node = node->children[0];
  1356. continue;
  1357. }
  1358. side = 0;
  1359. }
  1360. // the line intersects, find intersection point
  1361. // LordHavoc: this uses the original trace for maximum accuracy
  1362. if (plane->type < 3)
  1363. {
  1364. t1 = t->start[plane->type] - plane->dist;
  1365. t2 = t->end[plane->type] - plane->dist;
  1366. }
  1367. else
  1368. {
  1369. t1 = DotProduct (plane->normal, t->start) - plane->dist;
  1370. t2 = DotProduct (plane->normal, t->end) - plane->dist;
  1371. }
  1372. midf = t1 / (t1 - t2);
  1373. VectorMA(t->start, midf, t->dist, mid);
  1374. // recurse both sides, front side first, return if we hit a surface
  1375. if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
  1376. return HULLCHECKSTATE_DONE;
  1377. // test each surface on the node
  1378. Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
  1379. if (t->trace->hittexture)
  1380. return HULLCHECKSTATE_DONE;
  1381. // recurse back side
  1382. return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
  1383. }
  1384. leaf = (const mleaf_t *)node;
  1385. side = Mod_Q1BSP_SuperContentsFromNativeContents(leaf->contents);
  1386. if (!t->trace->startfound)
  1387. {
  1388. t->trace->startfound = true;
  1389. t->trace->startsupercontents |= side;
  1390. }
  1391. if (side & SUPERCONTENTS_LIQUIDSMASK)
  1392. t->trace->inwater = true;
  1393. if (side == 0)
  1394. t->trace->inopen = true;
  1395. if (side & t->trace->hitsupercontentsmask)
  1396. {
  1397. // if the first leaf is solid, set startsolid
  1398. if (t->trace->allsolid)
  1399. t->trace->startsolid = true;
  1400. return HULLCHECKSTATE_SOLID;
  1401. }
  1402. else
  1403. {
  1404. t->trace->allsolid = false;
  1405. return HULLCHECKSTATE_EMPTY;
  1406. }
  1407. }
  1408. static void Mod_Q1BSP_TraceLineAgainstSurfaces(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  1409. {
  1410. RecursiveHullCheckTraceInfo_t rhc;
  1411. memset(&rhc, 0, sizeof(rhc));
  1412. memset(trace, 0, sizeof(trace_t));
  1413. rhc.trace = trace;
  1414. rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
  1415. rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
  1416. rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
  1417. rhc.trace->fraction = 1;
  1418. rhc.trace->allsolid = true;
  1419. rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
  1420. VectorCopy(start, rhc.start);
  1421. VectorCopy(end, rhc.end);
  1422. VectorSubtract(rhc.end, rhc.start, rhc.dist);
  1423. Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
  1424. VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
  1425. }
  1426. static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
  1427. {
  1428. int c;
  1429. unsigned char *outstart = out;
  1430. while (out < outend)
  1431. {
  1432. if (in == inend)
  1433. {
  1434. Con_Printf("Mod_Q1BSP_DecompressVis: input underrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
  1435. return;
  1436. }
  1437. c = *in++;
  1438. if (c)
  1439. *out++ = c;
  1440. else
  1441. {
  1442. if (in == inend)
  1443. {
  1444. Con_Printf("Mod_Q1BSP_DecompressVis: input underrun (during zero-run) on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
  1445. return;
  1446. }
  1447. for (c = *in++;c > 0;c--)
  1448. {
  1449. if (out == outend)
  1450. {
  1451. Con_Printf("Mod_Q1BSP_DecompressVis: output overrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
  1452. return;
  1453. }
  1454. *out++ = 0;
  1455. }
  1456. }
  1457. }
  1458. }
  1459. /*
  1460. =============
  1461. R_Q1BSP_LoadSplitSky
  1462. A sky texture is 256*128, with the right side being a masked overlay
  1463. ==============
  1464. */
  1465. static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
  1466. {
  1467. int x, y;
  1468. int w = width/2;
  1469. int h = height;
  1470. unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
  1471. unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
  1472. // allocate a texture pool if we need it
  1473. if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
  1474. loadmodel->texturepool = R_AllocTexturePool();
  1475. if (bytesperpixel == 4)
  1476. {
  1477. for (y = 0;y < h;y++)
  1478. {
  1479. for (x = 0;x < w;x++)
  1480. {
  1481. solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
  1482. alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
  1483. }
  1484. }
  1485. }
  1486. else
  1487. {
  1488. // make an average value for the back to avoid
  1489. // a fringe on the top level
  1490. int p, r, g, b;
  1491. union
  1492. {
  1493. unsigned int i;
  1494. unsigned char b[4];
  1495. }
  1496. bgra;
  1497. r = g = b = 0;
  1498. for (y = 0;y < h;y++)
  1499. {
  1500. for (x = 0;x < w;x++)
  1501. {
  1502. p = src[x*width+y+w];
  1503. r += palette_rgb[p][0];
  1504. g += palette_rgb[p][1];
  1505. b += palette_rgb[p][2];
  1506. }
  1507. }
  1508. bgra.b[2] = r/(w*h);
  1509. bgra.b[1] = g/(w*h);
  1510. bgra.b[0] = b/(w*h);
  1511. bgra.b[3] = 0;
  1512. for (y = 0;y < h;y++)
  1513. {
  1514. for (x = 0;x < w;x++)
  1515. {
  1516. solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
  1517. p = src[y*width+x];
  1518. alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
  1519. }
  1520. }
  1521. }
  1522. loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
  1523. loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
  1524. Mem_Free(solidpixels);
  1525. Mem_Free(alphapixels);
  1526. }
  1527. static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
  1528. {
  1529. int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0, firstskynoshadowtexture = 0;
  1530. skinframe_t *skinframemissing;
  1531. texture_t *tx, *tx2, *anims[10], *altanims[10], *currentskynoshadowtexture;
  1532. texture_t backuptex;
  1533. unsigned char *data, *mtdata;
  1534. const char *s;
  1535. char mapname[MAX_QPATH], name[MAX_QPATH];
  1536. unsigned char zeroopaque[4], zerotrans[4];
  1537. sizebuf_t miptexsb;
  1538. char vabuf[1024];
  1539. Vector4Set(zeroopaque, 0, 0, 0, 255);
  1540. Vector4Set(zerotrans, 0, 0, 0, 128);
  1541. loadmodel->data_textures = NULL;
  1542. // add two slots for notexture walls and notexture liquids, and duplicate
  1543. // all sky textures; sky surfaces can be shadow-casting or not, the surface
  1544. // loading will choose according to the contents behind the surface
  1545. // (necessary to support e1m5 logo shadow which has a SKY contents brush,
  1546. // while correctly treating sky textures as occluders in other situations).
  1547. if (sb->cursize)
  1548. {
  1549. int numsky = 0;
  1550. size_t watermark;
  1551. nummiptex = MSG_ReadLittleLong(sb);
  1552. loadmodel->num_textures = nummiptex + 2;
  1553. // save the position so we can go back to it
  1554. watermark = sb->readcount;
  1555. for (i = 0; i < nummiptex; i++)
  1556. {
  1557. doffset = MSG_ReadLittleLong(sb);
  1558. if (r_nosurftextures.integer)
  1559. continue;
  1560. if (doffset == -1)
  1561. {
  1562. Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
  1563. continue;
  1564. }
  1565. MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
  1566. // copy name, but only up to 16 characters
  1567. // (the output buffer can hold more than this, but the input buffer is
  1568. // only 16)
  1569. for (j = 0; j < 16; j++)
  1570. name[j] = MSG_ReadByte(&miptexsb);
  1571. name[j] = 0;
  1572. // pretty up the buffer (replacing any trailing garbage with 0)
  1573. for (j = (int)strlen(name); j < 16; j++)
  1574. name[j] = 0;
  1575. if (!strncmp(name, "sky", 3))
  1576. numsky++;
  1577. }
  1578. // bump it back to where we started parsing
  1579. sb->readcount = watermark;
  1580. firstskynoshadowtexture = loadmodel->num_textures;
  1581. loadmodel->num_textures += numsky;
  1582. }
  1583. else
  1584. {
  1585. loadmodel->num_textures = 2;
  1586. firstskynoshadowtexture = loadmodel->num_textures;
  1587. }
  1588. loadmodel->num_texturesperskin = loadmodel->num_textures;
  1589. loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
  1590. // we'll be writing to these in parallel for sky textures
  1591. currentskynoshadowtexture = loadmodel->data_textures + firstskynoshadowtexture;
  1592. // fill out all slots with notexture
  1593. skinframemissing = R_SkinFrame_LoadMissing();
  1594. for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
  1595. {
  1596. strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
  1597. tx->width = 16;
  1598. tx->height = 16;
  1599. tx->basealpha = 1.0f;
  1600. tx->materialshaderpass = tx->shaderpasses[0] = Mod_CreateShaderPass(skinframemissing);
  1601. tx->materialshaderpass->skinframes[0] = skinframemissing;
  1602. tx->currentskinframe = skinframemissing;
  1603. tx->basematerialflags = MATERIALFLAG_WALL;
  1604. if (i == loadmodel->num_textures - 1)
  1605. {
  1606. tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
  1607. tx->supercontents = mod_q1bsp_texture_water.supercontents;
  1608. tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
  1609. }
  1610. else
  1611. {
  1612. tx->supercontents = mod_q1bsp_texture_solid.supercontents;
  1613. tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
  1614. }
  1615. tx->currentframe = tx;
  1616. // clear water settings
  1617. tx->reflectmin = 0;
  1618. tx->reflectmax = 1;
  1619. tx->refractfactor = 1;
  1620. Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
  1621. tx->reflectfactor = 1;
  1622. Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
  1623. tx->r_water_wateralpha = 1;
  1624. tx->offsetmapping = OFFSETMAPPING_DEFAULT;
  1625. tx->offsetscale = 1;
  1626. tx->offsetbias = 0;
  1627. tx->specularscalemod = 1;
  1628. tx->specularpowermod = 1;
  1629. tx->transparentsort = TRANSPARENTSORT_DISTANCE;
  1630. // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
  1631. // JUST GREP FOR "specularscalemod = 1".
  1632. }
  1633. if (!sb->cursize)
  1634. {
  1635. Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
  1636. return;
  1637. }
  1638. s = loadmodel->name;
  1639. if (!strncasecmp(s, "maps/", 5))
  1640. s += 5;
  1641. FS_StripExtension(s, mapname, sizeof(mapname));
  1642. // LordHavoc: mostly rewritten map texture loader
  1643. for (i = 0;i < nummiptex;i++)
  1644. {
  1645. doffset = MSG_ReadLittleLong(sb);
  1646. if (r_nosurftextures.integer)
  1647. continue;
  1648. if (doffset == -1)
  1649. {
  1650. Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
  1651. continue;
  1652. }
  1653. MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
  1654. // copy name, but only up to 16 characters
  1655. // (the output buffer can hold more than this, but the input buffer is
  1656. // only 16)
  1657. for (j = 0;j < 16;j++)
  1658. name[j] = MSG_ReadByte(&miptexsb);
  1659. name[j] = 0;
  1660. // pretty up the buffer (replacing any trailing garbage with 0)
  1661. for (j = (int)strlen(name);j < 16;j++)
  1662. name[j] = 0;
  1663. if (!name[0])
  1664. {
  1665. dpsnprintf(name, sizeof(name), "unnamed%i", i);
  1666. Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
  1667. }
  1668. mtwidth = MSG_ReadLittleLong(&miptexsb);
  1669. mtheight = MSG_ReadLittleLong(&miptexsb);
  1670. mtdata = NULL;
  1671. j = MSG_ReadLittleLong(&miptexsb);
  1672. if (j)
  1673. {
  1674. // texture included
  1675. if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
  1676. {
  1677. Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
  1678. continue;
  1679. }
  1680. mtdata = miptexsb.data + j;
  1681. }
  1682. if ((mtwidth & 15) || (mtheight & 15))
  1683. Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
  1684. // LordHavoc: force all names to lowercase
  1685. for (j = 0;name[j];j++)
  1686. if (name[j] >= 'A' && name[j] <= 'Z')
  1687. name[j] += 'a' - 'A';
  1688. // LordHavoc: backup the texture_t because q3 shader loading overwrites it
  1689. backuptex = loadmodel->data_textures[i];
  1690. if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
  1691. continue;
  1692. loadmodel->data_textures[i] = backuptex;
  1693. tx = loadmodel->data_textures + i;
  1694. strlcpy(tx->name, name, sizeof(tx->name));
  1695. tx->width = mtwidth;
  1696. tx->height = mtheight;
  1697. tx->basealpha = 1.0f;
  1698. // start out with no animation
  1699. tx->currentframe = tx;
  1700. tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
  1701. if (tx->name[0] == '*')
  1702. {
  1703. if (!strncmp(tx->name, "*lava", 5))
  1704. {
  1705. tx->supercontents = mod_q1bsp_texture_lava.supercontents;
  1706. tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
  1707. }
  1708. else if (!strncmp(tx->name, "*slime", 6))
  1709. {
  1710. tx->supercontents = mod_q1bsp_texture_slime.supercontents;
  1711. tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
  1712. }
  1713. else
  1714. {
  1715. tx->supercontents = mod_q1bsp_texture_water.supercontents;
  1716. tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
  1717. }
  1718. }
  1719. else if (!strncmp(tx->name, "sky", 3))
  1720. {
  1721. tx->supercontents = mod_q1bsp_texture_sky.supercontents;
  1722. tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
  1723. // for the surface traceline we need to hit this surface as a solid...
  1724. tx->supercontents |= SUPERCONTENTS_SOLID;
  1725. }
  1726. else
  1727. {
  1728. tx->supercontents = mod_q1bsp_texture_solid.supercontents;
  1729. tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
  1730. }
  1731. if (cls.state != ca_dedicated)
  1732. {
  1733. // LordHavoc: HL sky textures are entirely different than quake
  1734. if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
  1735. {
  1736. data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
  1737. if (!data)
  1738. data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
  1739. if (data && image_width == image_height * 2)
  1740. {
  1741. R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
  1742. Mem_Free(data);
  1743. }
  1744. else if (mtdata != NULL)
  1745. R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
  1746. }
  1747. else
  1748. {
  1749. skinframe_t *skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
  1750. if (!skinframe)
  1751. skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
  1752. if (skinframe)
  1753. tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
  1754. if (!skinframe)
  1755. {
  1756. // did not find external texture, load it from the bsp or wad3
  1757. if (loadmodel->brush.ishlbsp)
  1758. {
  1759. // internal texture overrides wad
  1760. unsigned char *pixels, *freepixels;
  1761. pixels = freepixels = NULL;
  1762. if (mtdata)
  1763. pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
  1764. if (pixels == NULL)
  1765. pixels = freepixels = W_GetTextureBGRA(tx->name);
  1766. if (pixels != NULL)
  1767. {
  1768. tx->width = image_width;
  1769. tx->height = image_height;
  1770. skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
  1771. }
  1772. if (freepixels)
  1773. Mem_Free(freepixels);
  1774. }
  1775. else if (mtdata) // texture included
  1776. skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
  1777. }
  1778. // if skinframe is still NULL the "missing" texture has already been assigned to this
  1779. if (skinframe)
  1780. tx->materialshaderpass->skinframes[0] = skinframe;
  1781. }
  1782. // LordHavoc: some Tenebrae textures get replaced by black
  1783. if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
  1784. tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
  1785. else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
  1786. tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
  1787. tx->currentskinframe = tx->materialshaderpass->skinframes[0];
  1788. }
  1789. tx->basematerialflags = MATERIALFLAG_WALL;
  1790. if (tx->name[0] == '*')
  1791. {
  1792. // LordHavoc: some turbulent textures should not be affected by wateralpha
  1793. if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
  1794. tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
  1795. else if (!strncmp(tx->name,"*lava",5)
  1796. || !strncmp(tx->name,"*teleport",9)
  1797. || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
  1798. tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
  1799. else
  1800. tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
  1801. if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
  1802. tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
  1803. }
  1804. else if (tx->name[0] == '{') // fence textures
  1805. {
  1806. tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
  1807. }
  1808. else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
  1809. {
  1810. // replace the texture with black
  1811. tx->basematerialflags |= MATERIALFLAG_REFLECTION;
  1812. }
  1813. else if (!strncmp(tx->name, "sky", 3))
  1814. tx->basematerialflags = MATERIALFLAG_SKY;
  1815. else if (!strcmp(tx->name, "caulk"))
  1816. tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
  1817. else if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
  1818. tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
  1819. tx->currentmaterialflags = tx->basematerialflags;
  1820. // duplicate of sky with NOSHADOW
  1821. if (tx->basematerialflags & MATERIALFLAG_SKY)
  1822. {
  1823. *currentskynoshadowtexture = *tx;
  1824. currentskynoshadowtexture->basematerialflags |= MATERIALFLAG_NOSHADOW;
  1825. tx->skynoshadowtexture = currentskynoshadowtexture;
  1826. currentskynoshadowtexture++;
  1827. }
  1828. }
  1829. // sequence the animations
  1830. for (i = 0;i < nummiptex;i++)
  1831. {
  1832. tx = loadmodel->data_textures + i;
  1833. if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
  1834. continue;
  1835. num = tx->name[1];
  1836. if ((num < '0' || num > '9') && (num < 'a' || num > 'j'))
  1837. {
  1838. Con_Printf("Bad animating texture %s\n", tx->name);
  1839. continue;
  1840. }
  1841. if (tx->anim_total[0] || tx->anim_total[1])
  1842. continue; // already sequenced
  1843. // find the number of frames in the animation
  1844. memset(anims, 0, sizeof(anims));
  1845. memset(altanims, 0, sizeof(altanims));
  1846. for (j = i;j < nummiptex;j++)
  1847. {
  1848. tx2 = loadmodel->data_textures + j;
  1849. if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
  1850. continue;
  1851. num = tx2->name[1];
  1852. if (num >= '0' && num <= '9')
  1853. anims[num - '0'] = tx2;
  1854. else if (num >= 'a' && num <= 'j')
  1855. altanims[num - 'a'] = tx2;
  1856. // No need to warn otherwise - we already did above.
  1857. }
  1858. max = altmax = 0;
  1859. for (j = 0;j < 10;j++)
  1860. {
  1861. if (anims[j])
  1862. max = j + 1;
  1863. if (altanims[j])
  1864. altmax = j + 1;
  1865. }
  1866. //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
  1867. incomplete = false;
  1868. for (j = 0;j < max;j++)
  1869. {
  1870. if (!anims[j])
  1871. {
  1872. Con_Printf("Missing frame %i of %s\n", j, tx->name);
  1873. incomplete = true;
  1874. }
  1875. }
  1876. for (j = 0;j < altmax;j++)
  1877. {
  1878. if (!altanims[j])
  1879. {
  1880. Con_Printf("Missing altframe %i of %s\n", j, tx->name);
  1881. incomplete = true;
  1882. }
  1883. }
  1884. if (incomplete)
  1885. continue;
  1886. // If we have exactly one frame, something's wrong.
  1887. if (max + altmax <= 1)
  1888. {
  1889. Con_Printf("Texture %s is animated (leading +) but has only one frame\n", tx->name);
  1890. }
  1891. if (altmax < 1)
  1892. {
  1893. // if there is no alternate animation, duplicate the primary
  1894. // animation into the alternate
  1895. altmax = max;
  1896. for (k = 0;k < 10;k++)
  1897. altanims[k] = anims[k];
  1898. }
  1899. if (max < 1)
  1900. {
  1901. // Warn.
  1902. Con_Printf("Missing frame 0 of %s\n", tx->name);
  1903. // however, we can handle this by duplicating the alternate animation into the primary
  1904. max = altmax;
  1905. for (k = 0;k < 10;k++)
  1906. anims[k] = altanims[k];
  1907. }
  1908. // link together the primary animation
  1909. for (j = 0;j < max;j++)
  1910. {
  1911. tx2 = anims[j];
  1912. tx2->animated = 1; // q1bsp
  1913. tx2->anim_total[0] = max;
  1914. tx2->anim_total[1] = altmax;
  1915. for (k = 0;k < 10;k++)
  1916. {
  1917. tx2->anim_frames[0][k] = anims[k];
  1918. tx2->anim_frames[1][k] = altanims[k];
  1919. }
  1920. }
  1921. // if there really is an alternate anim...
  1922. if (anims[0] != altanims[0])
  1923. {
  1924. // link together the alternate animation
  1925. for (j = 0;j < altmax;j++)
  1926. {
  1927. tx2 = altanims[j];
  1928. tx2->animated = 1; // q1bsp
  1929. // the primary/alternate are reversed here
  1930. tx2->anim_total[0] = altmax;
  1931. tx2->anim_total[1] = max;
  1932. for (k = 0;k < 10;k++)
  1933. {
  1934. tx2->anim_frames[0][k] = altanims[k];
  1935. tx2->anim_frames[1][k] = anims[k];
  1936. }
  1937. }
  1938. }
  1939. }
  1940. }
  1941. static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
  1942. {
  1943. int i;
  1944. unsigned char *in, *out, *data, d;
  1945. char litfilename[MAX_QPATH];
  1946. char dlitfilename[MAX_QPATH];
  1947. fs_offset_t filesize;
  1948. if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
  1949. {
  1950. loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
  1951. for (i = 0;i < sb->cursize;i++)
  1952. loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
  1953. }
  1954. else // LordHavoc: bsp version 29 (normal white lighting)
  1955. {
  1956. // LordHavoc: hope is not lost yet, check for a .lit file to load
  1957. strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
  1958. FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
  1959. strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
  1960. strlcat (litfilename, ".lit", sizeof (litfilename));
  1961. strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
  1962. data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
  1963. if (data)
  1964. {
  1965. if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
  1966. {
  1967. i = LittleLong(((int *)data)[1]);
  1968. if (i == 1)
  1969. {
  1970. if (developer_loading.integer)
  1971. Con_Printf("loaded %s\n", litfilename);
  1972. loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
  1973. memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
  1974. Mem_Free(data);
  1975. data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
  1976. if (data)
  1977. {
  1978. if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
  1979. {
  1980. i = LittleLong(((int *)data)[1]);
  1981. if (i == 1)
  1982. {
  1983. if (developer_loading.integer)
  1984. Con_Printf("loaded %s\n", dlitfilename);
  1985. loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
  1986. memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
  1987. loadmodel->brushq3.deluxemapping_modelspace = false;
  1988. loadmodel->brushq3.deluxemapping = true;
  1989. }
  1990. }
  1991. Mem_Free(data);
  1992. data = NULL;
  1993. }
  1994. return;
  1995. }
  1996. else
  1997. Con_Printf("Unknown .lit file version (%d)\n", i);
  1998. }
  1999. else if (filesize == 8)
  2000. Con_Print("Empty .lit file, ignoring\n");
  2001. else
  2002. Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
  2003. if (data)
  2004. {
  2005. Mem_Free(data);
  2006. data = NULL;
  2007. }
  2008. }
  2009. // LordHavoc: oh well, expand the white lighting data
  2010. if (!sb->cursize)
  2011. return;
  2012. loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
  2013. in = sb->data;
  2014. out = loadmodel->brushq1.lightdata;
  2015. for (i = 0;i < sb->cursize;i++)
  2016. {
  2017. d = *in++;
  2018. *out++ = d;
  2019. *out++ = d;
  2020. *out++ = d;
  2021. }
  2022. }
  2023. }
  2024. static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
  2025. {
  2026. loadmodel->brushq1.num_compressedpvs = 0;
  2027. loadmodel->brushq1.data_compressedpvs = NULL;
  2028. if (!sb->cursize)
  2029. return;
  2030. loadmodel->brushq1.num_compressedpvs = sb->cursize;
  2031. loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
  2032. MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
  2033. }
  2034. // used only for HalfLife maps
  2035. static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
  2036. {
  2037. char key[128], value[4096];
  2038. int i, j, k;
  2039. if (!data)
  2040. return;
  2041. if (!COM_ParseToken_Simple(&data, false, false, true))
  2042. return; // error
  2043. if (com_token[0] != '{')
  2044. return; // error
  2045. while (1)
  2046. {
  2047. if (!COM_ParseToken_Simple(&data, false, false, true))
  2048. return; // error
  2049. if (com_token[0] == '}')
  2050. break; // end of worldspawn
  2051. if (com_token[0] == '_')
  2052. strlcpy(key, com_token + 1, sizeof(key));
  2053. else
  2054. strlcpy(key, com_token, sizeof(key));
  2055. while (key[strlen(key)-1] == ' ') // remove trailing spaces
  2056. key[strlen(key)-1] = 0;
  2057. if (!COM_ParseToken_Simple(&data, false, false, true))
  2058. return; // error
  2059. dpsnprintf(value, sizeof(value), "%s", com_token);
  2060. if (!strcmp("wad", key)) // for HalfLife maps
  2061. {
  2062. if (loadmodel->brush.ishlbsp)
  2063. {
  2064. j = 0;
  2065. for (i = 0;i < (int)sizeof(value);i++)
  2066. if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
  2067. break;
  2068. if (i < (int)sizeof(value) && value[i])
  2069. {
  2070. for (;i < (int)sizeof(value);i++)
  2071. {
  2072. // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
  2073. if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
  2074. j = i+1;
  2075. else if (value[i] == ';' || value[i] == 0)
  2076. {
  2077. k = value[i];
  2078. value[i] = 0;
  2079. W_LoadTextureWadFile(&value[j], false);
  2080. j = i+1;
  2081. if (!k)
  2082. break;
  2083. }
  2084. }
  2085. }
  2086. }
  2087. }
  2088. }
  2089. }
  2090. static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
  2091. {
  2092. loadmodel->brush.entities = NULL;
  2093. if (!sb->cursize)
  2094. return;
  2095. loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
  2096. MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
  2097. loadmodel->brush.entities[sb->cursize] = 0;
  2098. if (loadmodel->brush.ishlbsp)
  2099. Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
  2100. }
  2101. static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
  2102. {
  2103. mvertex_t *out;
  2104. int i, count;
  2105. int structsize = 12;
  2106. if (sb->cursize % structsize)
  2107. Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
  2108. count = sb->cursize / structsize;
  2109. out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
  2110. loadmodel->brushq1.vertexes = out;
  2111. loadmodel->brushq1.numvertexes = count;
  2112. for ( i=0 ; i<count ; i++, out++)
  2113. {
  2114. out->position[0] = MSG_ReadLittleFloat(sb);
  2115. out->position[1] = MSG_ReadLittleFloat(sb);
  2116. out->position[2] = MSG_ReadLittleFloat(sb);
  2117. }
  2118. }
  2119. static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
  2120. {
  2121. mmodel_t *out;
  2122. int i, j, count;
  2123. int structsize = (48+4*hullinfo->filehulls);
  2124. if (sb->cursize % structsize)
  2125. Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
  2126. count = sb->cursize / structsize;
  2127. out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
  2128. loadmodel->brushq1.submodels = out;
  2129. loadmodel->brush.numsubmodels = count;
  2130. for (i = 0; i < count; i++, out++)
  2131. {
  2132. // spread out the mins / maxs by a pixel
  2133. out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
  2134. out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
  2135. out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
  2136. out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
  2137. out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
  2138. out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
  2139. out->origin[0] = MSG_ReadLittleFloat(sb);
  2140. out->origin[1] = MSG_ReadLittleFloat(sb);
  2141. out->origin[2] = MSG_ReadLittleFloat(sb);
  2142. for (j = 0; j < hullinfo->filehulls; j++)
  2143. out->headnode[j] = MSG_ReadLittleLong(sb);
  2144. out->visleafs = MSG_ReadLittleLong(sb);
  2145. out->firstface = MSG_ReadLittleLong(sb);
  2146. out->numfaces = MSG_ReadLittleLong(sb);
  2147. }
  2148. }
  2149. static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
  2150. {
  2151. medge_t *out;
  2152. int i, count;
  2153. int structsize = loadmodel->brush.isbsp2 ? 8 : 4;
  2154. if (sb->cursize % structsize)
  2155. Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
  2156. count = sb->cursize / structsize;
  2157. out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  2158. loadmodel->brushq1.edges = out;
  2159. loadmodel->brushq1.numedges = count;
  2160. for ( i=0 ; i<count ; i++, out++)
  2161. {
  2162. if (loadmodel->brush.isbsp2)
  2163. {
  2164. out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
  2165. out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
  2166. }
  2167. else
  2168. {
  2169. out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
  2170. out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
  2171. }
  2172. if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
  2173. {
  2174. Con_Printf("Mod_Q1BSP_LoadEdges: %s has invalid vertex indices in edge %i (vertices %i %i >= numvertices %i)\n", loadmodel->name, i, out->v[0], out->v[1], loadmodel->brushq1.numvertexes);
  2175. if(!loadmodel->brushq1.numvertexes)
  2176. Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
  2177. out->v[0] = 0;
  2178. out->v[1] = 0;
  2179. }
  2180. }
  2181. }
  2182. static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
  2183. {
  2184. mtexinfo_t *out;
  2185. int i, j, k, count, miptex;
  2186. int structsize = 40;
  2187. if (sb->cursize % structsize)
  2188. Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
  2189. count = sb->cursize / structsize;
  2190. out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  2191. loadmodel->brushq1.texinfo = out;
  2192. loadmodel->brushq1.numtexinfo = count;
  2193. for (i = 0;i < count;i++, out++)
  2194. {
  2195. for (k = 0;k < 2;k++)
  2196. for (j = 0;j < 4;j++)
  2197. out->vecs[k][j] = MSG_ReadLittleFloat(sb);
  2198. miptex = MSG_ReadLittleLong(sb);
  2199. out->q1flags = MSG_ReadLittleLong(sb);
  2200. if (out->q1flags & TEX_SPECIAL)
  2201. {
  2202. // if texture chosen is NULL or the shader needs a lightmap,
  2203. // force to notexture water shader
  2204. out->textureindex = loadmodel->num_textures - 1;
  2205. }
  2206. else
  2207. {
  2208. // if texture chosen is NULL, force to notexture
  2209. out->textureindex = loadmodel->num_textures - 2;
  2210. }
  2211. // see if the specified miptex is valid and try to use it instead
  2212. if (loadmodel->data_textures)
  2213. {
  2214. if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
  2215. Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
  2216. else
  2217. out->textureindex = miptex;
  2218. }
  2219. }
  2220. }
  2221. #if 0
  2222. void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
  2223. {
  2224. int i, j;
  2225. float *v;
  2226. mins[0] = mins[1] = mins[2] = 9999;
  2227. maxs[0] = maxs[1] = maxs[2] = -9999;
  2228. v = verts;
  2229. for (i = 0;i < numverts;i++)
  2230. {
  2231. for (j = 0;j < 3;j++, v++)
  2232. {
  2233. if (*v < mins[j])
  2234. mins[j] = *v;
  2235. if (*v > maxs[j])
  2236. maxs[j] = *v;
  2237. }
  2238. }
  2239. }
  2240. #define MAX_SUBDIVPOLYTRIANGLES 4096
  2241. #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
  2242. static int subdivpolyverts, subdivpolytriangles;
  2243. static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
  2244. static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
  2245. static int subdivpolylookupvert(vec3_t v)
  2246. {
  2247. int i;
  2248. for (i = 0;i < subdivpolyverts;i++)
  2249. if (subdivpolyvert[i][0] == v[0]
  2250. && subdivpolyvert[i][1] == v[1]
  2251. && subdivpolyvert[i][2] == v[2])
  2252. return i;
  2253. if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
  2254. Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
  2255. VectorCopy(v, subdivpolyvert[subdivpolyverts]);
  2256. return subdivpolyverts++;
  2257. }
  2258. static void SubdividePolygon(int numverts, float *verts)
  2259. {
  2260. int i, i1, i2, i3, f, b, c, p;
  2261. vec3_t mins, maxs, front[256], back[256];
  2262. float m, *pv, *cv, dist[256], frac;
  2263. if (numverts > 250)
  2264. Host_Error("SubdividePolygon: ran out of verts in buffer");
  2265. BoundPoly(numverts, verts, mins, maxs);
  2266. for (i = 0;i < 3;i++)
  2267. {
  2268. m = (mins[i] + maxs[i]) * 0.5;
  2269. m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
  2270. if (maxs[i] - m < 8)
  2271. continue;
  2272. if (m - mins[i] < 8)
  2273. continue;
  2274. // cut it
  2275. for (cv = verts, c = 0;c < numverts;c++, cv += 3)
  2276. dist[c] = cv[i] - m;
  2277. f = b = 0;
  2278. for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
  2279. {
  2280. if (dist[p] >= 0)
  2281. {
  2282. VectorCopy(pv, front[f]);
  2283. f++;
  2284. }
  2285. if (dist[p] <= 0)
  2286. {
  2287. VectorCopy(pv, back[b]);
  2288. b++;
  2289. }
  2290. if (dist[p] == 0 || dist[c] == 0)
  2291. continue;
  2292. if ((dist[p] > 0) != (dist[c] > 0) )
  2293. {
  2294. // clip point
  2295. frac = dist[p] / (dist[p] - dist[c]);
  2296. front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
  2297. front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
  2298. front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
  2299. f++;
  2300. b++;
  2301. }
  2302. }
  2303. SubdividePolygon(f, front[0]);
  2304. SubdividePolygon(b, back[0]);
  2305. return;
  2306. }
  2307. i1 = subdivpolylookupvert(verts);
  2308. i2 = subdivpolylookupvert(verts + 3);
  2309. for (i = 2;i < numverts;i++)
  2310. {
  2311. if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
  2312. {
  2313. Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
  2314. return;
  2315. }
  2316. i3 = subdivpolylookupvert(verts + i * 3);
  2317. subdivpolyindex[subdivpolytriangles][0] = i1;
  2318. subdivpolyindex[subdivpolytriangles][1] = i2;
  2319. subdivpolyindex[subdivpolytriangles][2] = i3;
  2320. i2 = i3;
  2321. subdivpolytriangles++;
  2322. }
  2323. }
  2324. //Breaks a polygon up along axial 64 unit
  2325. //boundaries so that turbulent and sky warps
  2326. //can be done reasonably.
  2327. static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
  2328. {
  2329. int i, j;
  2330. surfvertex_t *v;
  2331. surfmesh_t *mesh;
  2332. subdivpolytriangles = 0;
  2333. subdivpolyverts = 0;
  2334. SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
  2335. if (subdivpolytriangles < 1)
  2336. Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
  2337. surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
  2338. mesh->num_vertices = subdivpolyverts;
  2339. mesh->num_triangles = subdivpolytriangles;
  2340. mesh->vertex = (surfvertex_t *)(mesh + 1);
  2341. mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
  2342. memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
  2343. for (i = 0;i < mesh->num_triangles;i++)
  2344. for (j = 0;j < 3;j++)
  2345. mesh->index[i*3+j] = subdivpolyindex[i][j];
  2346. for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
  2347. {
  2348. VectorCopy(subdivpolyvert[i], v->v);
  2349. v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
  2350. v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
  2351. }
  2352. }
  2353. #endif
  2354. extern cvar_t gl_max_lightmapsize;
  2355. static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
  2356. {
  2357. msurface_t *surface;
  2358. int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
  2359. float texmins[2], texmaxs[2], val;
  2360. rtexture_t *lightmaptexture, *deluxemaptexture;
  2361. char vabuf[1024];
  2362. int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
  2363. if (sb->cursize % structsize)
  2364. Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
  2365. count = sb->cursize / structsize;
  2366. loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
  2367. loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
  2368. loadmodel->num_surfaces = count;
  2369. loadmodel->brushq1.firstrender = true;
  2370. loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
  2371. totalverts = 0;
  2372. totaltris = 0;
  2373. for (surfacenum = 0;surfacenum < count;surfacenum++)
  2374. {
  2375. if (loadmodel->brush.isbsp2)
  2376. numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
  2377. else
  2378. numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
  2379. totalverts += numedges;
  2380. totaltris += numedges - 2;
  2381. }
  2382. Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
  2383. lightmaptexture = NULL;
  2384. deluxemaptexture = r_texture_blanknormalmap;
  2385. lightmapnumber = 0;
  2386. lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
  2387. totallightmapsamples = 0;
  2388. totalverts = 0;
  2389. totaltris = 0;
  2390. for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
  2391. {
  2392. surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
  2393. // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
  2394. planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
  2395. /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
  2396. firstedge = MSG_ReadLittleLong(sb);
  2397. numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
  2398. texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
  2399. for (i = 0;i < MAXLIGHTMAPS;i++)
  2400. surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
  2401. lightmapoffset = MSG_ReadLittleLong(sb);
  2402. // FIXME: validate edges, texinfo, etc?
  2403. if ((unsigned int) firstedge > (unsigned int) loadmodel->brushq1.numsurfedges || (unsigned int) numedges > (unsigned int) loadmodel->brushq1.numsurfedges || (unsigned int) firstedge + (unsigned int) numedges > (unsigned int) loadmodel->brushq1.numsurfedges)
  2404. Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
  2405. if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
  2406. Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
  2407. if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
  2408. Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
  2409. surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
  2410. surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
  2411. // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
  2412. if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
  2413. lightmapoffset = -1;
  2414. //surface->flags = surface->texture->flags;
  2415. //if (LittleShort(in->side))
  2416. // surface->flags |= SURF_PLANEBACK;
  2417. //surface->plane = loadmodel->brush.data_planes + planenum;
  2418. surface->num_firstvertex = totalverts;
  2419. surface->num_vertices = numedges;
  2420. surface->num_firsttriangle = totaltris;
  2421. surface->num_triangles = numedges - 2;
  2422. totalverts += numedges;
  2423. totaltris += numedges - 2;
  2424. // convert edges back to a normal polygon
  2425. for (i = 0;i < surface->num_vertices;i++)
  2426. {
  2427. int lindex = loadmodel->brushq1.surfedges[firstedge + i];
  2428. float s, t;
  2429. // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
  2430. if (lindex >= 0)
  2431. VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
  2432. else
  2433. VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
  2434. s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
  2435. t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
  2436. (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
  2437. (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
  2438. (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
  2439. (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
  2440. (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
  2441. }
  2442. for (i = 0;i < surface->num_triangles;i++)
  2443. {
  2444. (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
  2445. (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
  2446. (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
  2447. }
  2448. // compile additional data about the surface geometry
  2449. Mod_BuildNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_normal3f, r_smoothnormals_areaweighting.integer != 0);
  2450. Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
  2451. BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
  2452. // generate surface extents information
  2453. texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
  2454. texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
  2455. for (i = 1;i < surface->num_vertices;i++)
  2456. {
  2457. for (j = 0;j < 2;j++)
  2458. {
  2459. val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
  2460. texmins[j] = min(texmins[j], val);
  2461. texmaxs[j] = max(texmaxs[j], val);
  2462. }
  2463. }
  2464. for (i = 0;i < 2;i++)
  2465. {
  2466. surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
  2467. surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
  2468. }
  2469. smax = surface->lightmapinfo->extents[0] >> 4;
  2470. tmax = surface->lightmapinfo->extents[1] >> 4;
  2471. ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
  2472. tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
  2473. // lighting info
  2474. surface->lightmaptexture = NULL;
  2475. surface->deluxemaptexture = r_texture_blanknormalmap;
  2476. if (lightmapoffset == -1)
  2477. {
  2478. surface->lightmapinfo->samples = NULL;
  2479. #if 1
  2480. // give non-lightmapped water a 1x white lightmap
  2481. if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
  2482. {
  2483. surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
  2484. surface->lightmapinfo->styles[0] = 0;
  2485. memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
  2486. }
  2487. #endif
  2488. }
  2489. else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LordHavoc: HalfLife map (bsp version 30)
  2490. surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
  2491. else // LordHavoc: white lighting (bsp version 29)
  2492. {
  2493. surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
  2494. if (loadmodel->brushq1.nmaplightdata)
  2495. surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
  2496. }
  2497. // check if we should apply a lightmap to this
  2498. if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
  2499. {
  2500. if (ssize > 256 || tsize > 256)
  2501. Host_Error("Bad surface extents");
  2502. if (lightmapsize < ssize)
  2503. lightmapsize = ssize;
  2504. if (lightmapsize < tsize)
  2505. lightmapsize = tsize;
  2506. totallightmapsamples += ssize*tsize;
  2507. // force lightmap upload on first time seeing the surface
  2508. //
  2509. // additionally this is used by the later code to see if a
  2510. // lightmap is needed on this surface (rather than duplicating the
  2511. // logic above)
  2512. loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
  2513. loadmodel->lit = true;
  2514. }
  2515. }
  2516. // small maps (such as ammo boxes especially) don't need big lightmap
  2517. // textures, so this code tries to guess a good size based on
  2518. // totallightmapsamples (size of the lightmaps lump basically), as well as
  2519. // trying to max out the size if there is a lot of lightmap data to store
  2520. // additionally, never choose a lightmapsize that is smaller than the
  2521. // largest surface encountered (as it would fail)
  2522. i = lightmapsize;
  2523. for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
  2524. ;
  2525. // now that we've decided the lightmap texture size, we can do the rest
  2526. if (cls.state != ca_dedicated)
  2527. {
  2528. int stainmapsize = 0;
  2529. mod_alloclightmap_state_t allocState;
  2530. Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
  2531. for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
  2532. {
  2533. int iu, iv, lightmapx = 0, lightmapy = 0;
  2534. float u, v, ubase, vbase, uscale, vscale;
  2535. if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
  2536. continue;
  2537. smax = surface->lightmapinfo->extents[0] >> 4;
  2538. tmax = surface->lightmapinfo->extents[1] >> 4;
  2539. ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
  2540. tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
  2541. stainmapsize += ssize * tsize * 3;
  2542. if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
  2543. {
  2544. // allocate a texture pool if we need it
  2545. if (loadmodel->texturepool == NULL)
  2546. loadmodel->texturepool = R_AllocTexturePool();
  2547. // could not find room, make a new lightmap
  2548. loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
  2549. loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
  2550. loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
  2551. loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
  2552. if (loadmodel->brushq1.nmaplightdata)
  2553. loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
  2554. lightmapnumber++;
  2555. Mod_AllocLightmap_Reset(&allocState);
  2556. Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
  2557. }
  2558. surface->lightmaptexture = lightmaptexture;
  2559. surface->deluxemaptexture = deluxemaptexture;
  2560. surface->lightmapinfo->lightmaporigin[0] = lightmapx;
  2561. surface->lightmapinfo->lightmaporigin[1] = lightmapy;
  2562. uscale = 1.0f / (float)lightmapsize;
  2563. vscale = 1.0f / (float)lightmapsize;
  2564. ubase = lightmapx * uscale;
  2565. vbase = lightmapy * vscale;
  2566. for (i = 0;i < surface->num_vertices;i++)
  2567. {
  2568. u = ((DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3]) + 8 - surface->lightmapinfo->texturemins[0]) * (1.0 / 16.0);
  2569. v = ((DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3]) + 8 - surface->lightmapinfo->texturemins[1]) * (1.0 / 16.0);
  2570. (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
  2571. (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
  2572. // LordHavoc: calc lightmap data offset for vertex lighting to use
  2573. iu = (int) u;
  2574. iv = (int) v;
  2575. (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
  2576. }
  2577. }
  2578. if (cl_stainmaps.integer)
  2579. {
  2580. // allocate stainmaps for permanent marks on walls and clear white
  2581. unsigned char *stainsamples = NULL;
  2582. stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
  2583. memset(stainsamples, 255, stainmapsize);
  2584. // assign pointers
  2585. for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
  2586. {
  2587. if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
  2588. continue;
  2589. ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
  2590. tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
  2591. surface->lightmapinfo->stainsamples = stainsamples;
  2592. stainsamples += ssize * tsize * 3;
  2593. }
  2594. }
  2595. }
  2596. // generate ushort elements array if possible
  2597. if (loadmodel->surfmesh.data_element3s)
  2598. for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
  2599. loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
  2600. }
  2601. static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
  2602. {
  2603. //if (node->parent)
  2604. // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
  2605. node->parent = parent;
  2606. if (node->plane)
  2607. {
  2608. // this is a node, recurse to children
  2609. Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
  2610. Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
  2611. // combine supercontents of children
  2612. node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
  2613. }
  2614. else
  2615. {
  2616. int j;
  2617. mleaf_t *leaf = (mleaf_t *)node;
  2618. // if this is a leaf, calculate supercontents mask from all collidable
  2619. // primitives in the leaf (brushes and collision surfaces)
  2620. // also flag if the leaf contains any collision surfaces
  2621. leaf->combinedsupercontents = 0;
  2622. // combine the supercontents values of all brushes in this leaf
  2623. for (j = 0;j < leaf->numleafbrushes;j++)
  2624. leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
  2625. // check if this leaf contains any collision surfaces (q3 patches)
  2626. for (j = 0;j < leaf->numleafsurfaces;j++)
  2627. {
  2628. msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
  2629. if (surface->num_collisiontriangles)
  2630. {
  2631. leaf->containscollisionsurfaces = true;
  2632. leaf->combinedsupercontents |= surface->texture->supercontents;
  2633. }
  2634. }
  2635. }
  2636. }
  2637. static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
  2638. {
  2639. int i, j, count, p, child[2];
  2640. mnode_t *out;
  2641. int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
  2642. if (sb->cursize % structsize)
  2643. Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
  2644. count = sb->cursize / structsize;
  2645. if (count == 0)
  2646. Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
  2647. out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
  2648. loadmodel->brush.data_nodes = out;
  2649. loadmodel->brush.num_nodes = count;
  2650. for ( i=0 ; i<count ; i++, out++)
  2651. {
  2652. p = MSG_ReadLittleLong(sb);
  2653. out->plane = loadmodel->brush.data_planes + p;
  2654. if (loadmodel->brush.isbsp2rmqe)
  2655. {
  2656. child[0] = MSG_ReadLittleLong(sb);
  2657. child[1] = MSG_ReadLittleLong(sb);
  2658. out->mins[0] = MSG_ReadLittleShort(sb);
  2659. out->mins[1] = MSG_ReadLittleShort(sb);
  2660. out->mins[2] = MSG_ReadLittleShort(sb);
  2661. out->maxs[0] = MSG_ReadLittleShort(sb);
  2662. out->maxs[1] = MSG_ReadLittleShort(sb);
  2663. out->maxs[2] = MSG_ReadLittleShort(sb);
  2664. out->firstsurface = MSG_ReadLittleLong(sb);
  2665. out->numsurfaces = MSG_ReadLittleLong(sb);
  2666. }
  2667. else if (loadmodel->brush.isbsp2)
  2668. {
  2669. child[0] = MSG_ReadLittleLong(sb);
  2670. child[1] = MSG_ReadLittleLong(sb);
  2671. out->mins[0] = MSG_ReadLittleFloat(sb);
  2672. out->mins[1] = MSG_ReadLittleFloat(sb);
  2673. out->mins[2] = MSG_ReadLittleFloat(sb);
  2674. out->maxs[0] = MSG_ReadLittleFloat(sb);
  2675. out->maxs[1] = MSG_ReadLittleFloat(sb);
  2676. out->maxs[2] = MSG_ReadLittleFloat(sb);
  2677. out->firstsurface = MSG_ReadLittleLong(sb);
  2678. out->numsurfaces = MSG_ReadLittleLong(sb);
  2679. }
  2680. else
  2681. {
  2682. child[0] = (unsigned short)MSG_ReadLittleShort(sb);
  2683. child[1] = (unsigned short)MSG_ReadLittleShort(sb);
  2684. if (child[0] >= count)
  2685. child[0] -= 65536;
  2686. if (child[1] >= count)
  2687. child[1] -= 65536;
  2688. out->mins[0] = MSG_ReadLittleShort(sb);
  2689. out->mins[1] = MSG_ReadLittleShort(sb);
  2690. out->mins[2] = MSG_ReadLittleShort(sb);
  2691. out->maxs[0] = MSG_ReadLittleShort(sb);
  2692. out->maxs[1] = MSG_ReadLittleShort(sb);
  2693. out->maxs[2] = MSG_ReadLittleShort(sb);
  2694. out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
  2695. out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
  2696. }
  2697. for (j=0 ; j<2 ; j++)
  2698. {
  2699. // LordHavoc: this code supports broken bsp files produced by
  2700. // arguire qbsp which can produce more than 32768 nodes, any value
  2701. // below count is assumed to be a node number, any other value is
  2702. // assumed to be a leaf number
  2703. p = child[j];
  2704. if (p >= 0)
  2705. {
  2706. if (p < loadmodel->brush.num_nodes)
  2707. out->children[j] = loadmodel->brush.data_nodes + p;
  2708. else
  2709. {
  2710. Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
  2711. // map it to the solid leaf
  2712. out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
  2713. }
  2714. }
  2715. else
  2716. {
  2717. // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
  2718. p = -(p+1);
  2719. if (p < loadmodel->brush.num_leafs)
  2720. out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
  2721. else
  2722. {
  2723. Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
  2724. // map it to the solid leaf
  2725. out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
  2726. }
  2727. }
  2728. }
  2729. }
  2730. Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
  2731. }
  2732. static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
  2733. {
  2734. mleaf_t *out;
  2735. int i, j, count, p, firstmarksurface, nummarksurfaces;
  2736. int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
  2737. if (sb->cursize % structsize)
  2738. Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
  2739. count = sb->cursize / structsize;
  2740. out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
  2741. loadmodel->brush.data_leafs = out;
  2742. loadmodel->brush.num_leafs = count;
  2743. // get visleafs from the submodel data
  2744. loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
  2745. loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
  2746. loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
  2747. memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
  2748. // FIXME: this function could really benefit from some error checking
  2749. for ( i=0 ; i<count ; i++, out++)
  2750. {
  2751. out->contents = MSG_ReadLittleLong(sb);
  2752. out->clusterindex = i - 1;
  2753. if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
  2754. out->clusterindex = -1;
  2755. p = MSG_ReadLittleLong(sb);
  2756. // ignore visofs errors on leaf 0 (solid)
  2757. if (p >= 0 && out->clusterindex >= 0)
  2758. {
  2759. if (p >= loadmodel->brushq1.num_compressedpvs)
  2760. Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
  2761. else
  2762. Mod_Q1BSP_DecompressVis(loadmodel->brushq1.data_compressedpvs + p, loadmodel->brushq1.data_compressedpvs + loadmodel->brushq1.num_compressedpvs, loadmodel->brush.data_pvsclusters + out->clusterindex * loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.data_pvsclusters + (out->clusterindex + 1) * loadmodel->brush.num_pvsclusterbytes);
  2763. }
  2764. if (loadmodel->brush.isbsp2rmqe)
  2765. {
  2766. out->mins[0] = MSG_ReadLittleShort(sb);
  2767. out->mins[1] = MSG_ReadLittleShort(sb);
  2768. out->mins[2] = MSG_ReadLittleShort(sb);
  2769. out->maxs[0] = MSG_ReadLittleShort(sb);
  2770. out->maxs[1] = MSG_ReadLittleShort(sb);
  2771. out->maxs[2] = MSG_ReadLittleShort(sb);
  2772. firstmarksurface = MSG_ReadLittleLong(sb);
  2773. nummarksurfaces = MSG_ReadLittleLong(sb);
  2774. }
  2775. else if (loadmodel->brush.isbsp2)
  2776. {
  2777. out->mins[0] = MSG_ReadLittleFloat(sb);
  2778. out->mins[1] = MSG_ReadLittleFloat(sb);
  2779. out->mins[2] = MSG_ReadLittleFloat(sb);
  2780. out->maxs[0] = MSG_ReadLittleFloat(sb);
  2781. out->maxs[1] = MSG_ReadLittleFloat(sb);
  2782. out->maxs[2] = MSG_ReadLittleFloat(sb);
  2783. firstmarksurface = MSG_ReadLittleLong(sb);
  2784. nummarksurfaces = MSG_ReadLittleLong(sb);
  2785. }
  2786. else
  2787. {
  2788. out->mins[0] = MSG_ReadLittleShort(sb);
  2789. out->mins[1] = MSG_ReadLittleShort(sb);
  2790. out->mins[2] = MSG_ReadLittleShort(sb);
  2791. out->maxs[0] = MSG_ReadLittleShort(sb);
  2792. out->maxs[1] = MSG_ReadLittleShort(sb);
  2793. out->maxs[2] = MSG_ReadLittleShort(sb);
  2794. firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
  2795. nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
  2796. }
  2797. if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
  2798. {
  2799. out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
  2800. out->numleafsurfaces = nummarksurfaces;
  2801. }
  2802. else
  2803. {
  2804. Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
  2805. out->firstleafsurface = NULL;
  2806. out->numleafsurfaces = 0;
  2807. }
  2808. for (j = 0;j < 4;j++)
  2809. out->ambient_sound_level[j] = MSG_ReadByte(sb);
  2810. }
  2811. }
  2812. static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
  2813. {
  2814. int i, j;
  2815. mleaf_t *leaf;
  2816. const unsigned char *pvs;
  2817. // if there's no vis data, assume supported (because everything is visible all the time)
  2818. if (!loadmodel->brush.data_pvsclusters)
  2819. return true;
  2820. // check all liquid leafs to see if they can see into empty leafs, if any
  2821. // can we can assume this map supports r_wateralpha
  2822. for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
  2823. {
  2824. if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
  2825. {
  2826. pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
  2827. for (j = 0;j < loadmodel->brush.num_leafs;j++)
  2828. if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
  2829. return true;
  2830. }
  2831. }
  2832. return false;
  2833. }
  2834. static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
  2835. {
  2836. mclipnode_t *out;
  2837. int i, count;
  2838. hull_t *hull;
  2839. int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
  2840. if (sb->cursize % structsize)
  2841. Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
  2842. count = sb->cursize / structsize;
  2843. out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
  2844. loadmodel->brushq1.clipnodes = out;
  2845. loadmodel->brushq1.numclipnodes = count;
  2846. for (i = 1; i < MAX_MAP_HULLS; i++)
  2847. {
  2848. hull = &loadmodel->brushq1.hulls[i];
  2849. hull->clipnodes = out;
  2850. hull->firstclipnode = 0;
  2851. hull->lastclipnode = count-1;
  2852. hull->planes = loadmodel->brush.data_planes;
  2853. hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
  2854. hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
  2855. hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
  2856. hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
  2857. hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
  2858. hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
  2859. VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
  2860. }
  2861. for (i=0 ; i<count ; i++, out++)
  2862. {
  2863. out->planenum = MSG_ReadLittleLong(sb);
  2864. if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
  2865. Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
  2866. if (loadmodel->brush.isbsp2)
  2867. {
  2868. out->children[0] = MSG_ReadLittleLong(sb);
  2869. out->children[1] = MSG_ReadLittleLong(sb);
  2870. if (out->children[0] >= count)
  2871. Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
  2872. if (out->children[1] >= count)
  2873. Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
  2874. }
  2875. else
  2876. {
  2877. // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
  2878. out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
  2879. out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
  2880. if (out->children[0] >= count)
  2881. out->children[0] -= 65536;
  2882. if (out->children[1] >= count)
  2883. out->children[1] -= 65536;
  2884. }
  2885. }
  2886. }
  2887. //Duplicate the drawing hull structure as a clipping hull
  2888. static void Mod_Q1BSP_MakeHull0(void)
  2889. {
  2890. mnode_t *in;
  2891. mclipnode_t *out;
  2892. int i;
  2893. hull_t *hull;
  2894. hull = &loadmodel->brushq1.hulls[0];
  2895. in = loadmodel->brush.data_nodes;
  2896. out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
  2897. hull->clipnodes = out;
  2898. hull->firstclipnode = 0;
  2899. hull->lastclipnode = loadmodel->brush.num_nodes - 1;
  2900. hull->planes = loadmodel->brush.data_planes;
  2901. for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
  2902. {
  2903. out->planenum = in->plane - loadmodel->brush.data_planes;
  2904. out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
  2905. out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
  2906. }
  2907. }
  2908. static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
  2909. {
  2910. int i, j;
  2911. int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
  2912. if (sb->cursize % structsize)
  2913. Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
  2914. loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
  2915. loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
  2916. if (loadmodel->brush.isbsp2)
  2917. {
  2918. for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
  2919. {
  2920. j = MSG_ReadLittleLong(sb);
  2921. if (j < 0 || j >= loadmodel->num_surfaces)
  2922. Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
  2923. loadmodel->brush.data_leafsurfaces[i] = j;
  2924. }
  2925. }
  2926. else
  2927. {
  2928. for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
  2929. {
  2930. j = (unsigned short) MSG_ReadLittleShort(sb);
  2931. if (j >= loadmodel->num_surfaces)
  2932. Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
  2933. loadmodel->brush.data_leafsurfaces[i] = j;
  2934. }
  2935. }
  2936. }
  2937. static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
  2938. {
  2939. int i;
  2940. int structsize = 4;
  2941. if (sb->cursize % structsize)
  2942. Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
  2943. loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
  2944. loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
  2945. for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
  2946. loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
  2947. }
  2948. static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
  2949. {
  2950. int i;
  2951. mplane_t *out;
  2952. int structsize = 20;
  2953. if (sb->cursize % structsize)
  2954. Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
  2955. loadmodel->brush.num_planes = sb->cursize / structsize;
  2956. loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
  2957. for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
  2958. {
  2959. out->normal[0] = MSG_ReadLittleFloat(sb);
  2960. out->normal[1] = MSG_ReadLittleFloat(sb);
  2961. out->normal[2] = MSG_ReadLittleFloat(sb);
  2962. out->dist = MSG_ReadLittleFloat(sb);
  2963. MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
  2964. PlaneClassify(out);
  2965. }
  2966. }
  2967. // fixes up sky surfaces that have SKY contents behind them, so that they do not cast shadows (e1m5 logo shadow trick).
  2968. static void Mod_Q1BSP_AssignNoShadowSkySurfaces(dp_model_t *mod)
  2969. {
  2970. int i;
  2971. msurface_t *surface;
  2972. vec3_t center;
  2973. int contents;
  2974. for (i = 0, surface = mod->data_surfaces + mod->firstmodelsurface; i < mod->nummodelsurfaces; i++, surface++)
  2975. {
  2976. if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
  2977. {
  2978. // check if the point behind the surface polygon is SOLID or SKY contents
  2979. VectorMAMAM(0.5f, surface->mins, 0.5f, surface->maxs, -0.25f, mod->surfmesh.data_normal3f + 3*surface->num_firstvertex, center);
  2980. contents = Mod_Q1BSP_PointSuperContents(mod, 0, center);
  2981. if (!(contents & SUPERCONTENTS_SOLID))
  2982. surface->texture = surface->texture->skynoshadowtexture;
  2983. }
  2984. }
  2985. }
  2986. static void Mod_Q1BSP_LoadMapBrushes(void)
  2987. {
  2988. #if 0
  2989. // unfinished
  2990. int submodel, numbrushes;
  2991. qboolean firstbrush;
  2992. char *text, *maptext;
  2993. char mapfilename[MAX_QPATH];
  2994. FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
  2995. strlcat (mapfilename, ".map", sizeof (mapfilename));
  2996. maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
  2997. if (!maptext)
  2998. return;
  2999. text = maptext;
  3000. if (!COM_ParseToken_Simple(&data, false, false, true))
  3001. return; // error
  3002. submodel = 0;
  3003. for (;;)
  3004. {
  3005. if (!COM_ParseToken_Simple(&data, false, false, true))
  3006. break;
  3007. if (com_token[0] != '{')
  3008. return; // error
  3009. // entity
  3010. firstbrush = true;
  3011. numbrushes = 0;
  3012. maxbrushes = 256;
  3013. brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
  3014. for (;;)
  3015. {
  3016. if (!COM_ParseToken_Simple(&data, false, false, true))
  3017. return; // error
  3018. if (com_token[0] == '}')
  3019. break; // end of entity
  3020. if (com_token[0] == '{')
  3021. {
  3022. // brush
  3023. if (firstbrush)
  3024. {
  3025. if (submodel)
  3026. {
  3027. if (submodel > loadmodel->brush.numsubmodels)
  3028. {
  3029. Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
  3030. model = NULL;
  3031. }
  3032. else
  3033. model = loadmodel->brush.submodels[submodel];
  3034. }
  3035. else
  3036. model = loadmodel;
  3037. }
  3038. for (;;)
  3039. {
  3040. if (!COM_ParseToken_Simple(&data, false, false, true))
  3041. return; // error
  3042. if (com_token[0] == '}')
  3043. break; // end of brush
  3044. // each brush face should be this format:
  3045. // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
  3046. // FIXME: support hl .map format
  3047. for (pointnum = 0;pointnum < 3;pointnum++)
  3048. {
  3049. COM_ParseToken_Simple(&data, false, false, true);
  3050. for (componentnum = 0;componentnum < 3;componentnum++)
  3051. {
  3052. COM_ParseToken_Simple(&data, false, false, true);
  3053. point[pointnum][componentnum] = atof(com_token);
  3054. }
  3055. COM_ParseToken_Simple(&data, false, false, true);
  3056. }
  3057. COM_ParseToken_Simple(&data, false, false, true);
  3058. strlcpy(facetexture, com_token, sizeof(facetexture));
  3059. COM_ParseToken_Simple(&data, false, false, true);
  3060. //scroll_s = atof(com_token);
  3061. COM_ParseToken_Simple(&data, false, false, true);
  3062. //scroll_t = atof(com_token);
  3063. COM_ParseToken_Simple(&data, false, false, true);
  3064. //rotate = atof(com_token);
  3065. COM_ParseToken_Simple(&data, false, false, true);
  3066. //scale_s = atof(com_token);
  3067. COM_ParseToken_Simple(&data, false, false, true);
  3068. //scale_t = atof(com_token);
  3069. TriangleNormal(point[0], point[1], point[2], planenormal);
  3070. VectorNormalizeDouble(planenormal);
  3071. planedist = DotProduct(point[0], planenormal);
  3072. //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
  3073. }
  3074. continue;
  3075. }
  3076. }
  3077. }
  3078. #endif
  3079. }
  3080. #define MAX_PORTALPOINTS 64
  3081. typedef struct portal_s
  3082. {
  3083. mplane_t plane;
  3084. mnode_t *nodes[2]; // [0] = front side of plane
  3085. struct portal_s *next[2];
  3086. int numpoints;
  3087. double points[3*MAX_PORTALPOINTS];
  3088. struct portal_s *chain; // all portals are linked into a list
  3089. }
  3090. portal_t;
  3091. static memexpandablearray_t portalarray;
  3092. static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
  3093. {
  3094. // process only nodes (leafs already had their box calculated)
  3095. if (!node->plane)
  3096. return;
  3097. // calculate children first
  3098. Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
  3099. Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
  3100. // make combined bounding box from children
  3101. node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
  3102. node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
  3103. node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
  3104. node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
  3105. node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
  3106. node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
  3107. }
  3108. static void Mod_Q1BSP_FinalizePortals(void)
  3109. {
  3110. int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
  3111. portal_t *p;
  3112. mportal_t *portal;
  3113. mvertex_t *point;
  3114. mleaf_t *leaf, *endleaf;
  3115. // tally up portal and point counts and recalculate bounding boxes for all
  3116. // leafs (because qbsp is very sloppy)
  3117. leaf = loadmodel->brush.data_leafs;
  3118. endleaf = leaf + loadmodel->brush.num_leafs;
  3119. if (mod_recalculatenodeboxes.integer)
  3120. {
  3121. for (;leaf < endleaf;leaf++)
  3122. {
  3123. VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
  3124. VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
  3125. }
  3126. }
  3127. numportals = 0;
  3128. numpoints = 0;
  3129. for (portalindex = 0;portalindex < portalrange;portalindex++)
  3130. {
  3131. p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
  3132. if (!p)
  3133. continue;
  3134. // note: this check must match the one below or it will usually corrupt memory
  3135. // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
  3136. if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
  3137. {
  3138. numportals += 2;
  3139. numpoints += p->numpoints * 2;
  3140. }
  3141. }
  3142. loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
  3143. loadmodel->brush.num_portals = numportals;
  3144. loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
  3145. loadmodel->brush.num_portalpoints = numpoints;
  3146. // clear all leaf portal chains
  3147. for (i = 0;i < loadmodel->brush.num_leafs;i++)
  3148. loadmodel->brush.data_leafs[i].portals = NULL;
  3149. // process all portals in the global portal chain, while freeing them
  3150. portal = loadmodel->brush.data_portals;
  3151. point = loadmodel->brush.data_portalpoints;
  3152. for (portalindex = 0;portalindex < portalrange;portalindex++)
  3153. {
  3154. p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
  3155. if (!p)
  3156. continue;
  3157. if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
  3158. {
  3159. // note: this check must match the one above or it will usually corrupt memory
  3160. // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
  3161. if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
  3162. {
  3163. // first make the back to front portal(forward portal)
  3164. portal->points = point;
  3165. portal->numpoints = p->numpoints;
  3166. portal->plane.dist = p->plane.dist;
  3167. VectorCopy(p->plane.normal, portal->plane.normal);
  3168. portal->here = (mleaf_t *)p->nodes[1];
  3169. portal->past = (mleaf_t *)p->nodes[0];
  3170. // copy points
  3171. for (j = 0;j < portal->numpoints;j++)
  3172. {
  3173. VectorCopy(p->points + j*3, point->position);
  3174. point++;
  3175. }
  3176. BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
  3177. PlaneClassify(&portal->plane);
  3178. // link into leaf's portal chain
  3179. portal->next = portal->here->portals;
  3180. portal->here->portals = portal;
  3181. // advance to next portal
  3182. portal++;
  3183. // then make the front to back portal(backward portal)
  3184. portal->points = point;
  3185. portal->numpoints = p->numpoints;
  3186. portal->plane.dist = -p->plane.dist;
  3187. VectorNegate(p->plane.normal, portal->plane.normal);
  3188. portal->here = (mleaf_t *)p->nodes[0];
  3189. portal->past = (mleaf_t *)p->nodes[1];
  3190. // copy points
  3191. for (j = portal->numpoints - 1;j >= 0;j--)
  3192. {
  3193. VectorCopy(p->points + j*3, point->position);
  3194. point++;
  3195. }
  3196. BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
  3197. PlaneClassify(&portal->plane);
  3198. // link into leaf's portal chain
  3199. portal->next = portal->here->portals;
  3200. portal->here->portals = portal;
  3201. // advance to next portal
  3202. portal++;
  3203. }
  3204. // add the portal's polygon points to the leaf bounding boxes
  3205. if (mod_recalculatenodeboxes.integer)
  3206. {
  3207. for (i = 0;i < 2;i++)
  3208. {
  3209. leaf = (mleaf_t *)p->nodes[i];
  3210. for (j = 0;j < p->numpoints;j++)
  3211. {
  3212. if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
  3213. if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
  3214. if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
  3215. if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
  3216. if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
  3217. if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
  3218. }
  3219. }
  3220. }
  3221. }
  3222. }
  3223. // now recalculate the node bounding boxes from the leafs
  3224. if (mod_recalculatenodeboxes.integer)
  3225. Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
  3226. }
  3227. /*
  3228. =============
  3229. AddPortalToNodes
  3230. =============
  3231. */
  3232. static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
  3233. {
  3234. if (!front)
  3235. Host_Error("AddPortalToNodes: NULL front node");
  3236. if (!back)
  3237. Host_Error("AddPortalToNodes: NULL back node");
  3238. if (p->nodes[0] || p->nodes[1])
  3239. Host_Error("AddPortalToNodes: already included");
  3240. // note: front == back is handled gracefully, because leaf 0 is the shared solid leaf, it can often have portals with the same leaf on both sides
  3241. p->nodes[0] = front;
  3242. p->next[0] = (portal_t *)front->portals;
  3243. front->portals = (mportal_t *)p;
  3244. p->nodes[1] = back;
  3245. p->next[1] = (portal_t *)back->portals;
  3246. back->portals = (mportal_t *)p;
  3247. }
  3248. /*
  3249. =============
  3250. RemovePortalFromNode
  3251. =============
  3252. */
  3253. static void RemovePortalFromNodes(portal_t *portal)
  3254. {
  3255. int i;
  3256. mnode_t *node;
  3257. void **portalpointer;
  3258. portal_t *t;
  3259. for (i = 0;i < 2;i++)
  3260. {
  3261. node = portal->nodes[i];
  3262. portalpointer = (void **) &node->portals;
  3263. while (1)
  3264. {
  3265. t = (portal_t *)*portalpointer;
  3266. if (!t)
  3267. Host_Error("RemovePortalFromNodes: portal not in leaf");
  3268. if (t == portal)
  3269. {
  3270. if (portal->nodes[0] == node)
  3271. {
  3272. *portalpointer = portal->next[0];
  3273. portal->nodes[0] = NULL;
  3274. }
  3275. else if (portal->nodes[1] == node)
  3276. {
  3277. *portalpointer = portal->next[1];
  3278. portal->nodes[1] = NULL;
  3279. }
  3280. else
  3281. Host_Error("RemovePortalFromNodes: portal not bounding leaf");
  3282. break;
  3283. }
  3284. if (t->nodes[0] == node)
  3285. portalpointer = (void **) &t->next[0];
  3286. else if (t->nodes[1] == node)
  3287. portalpointer = (void **) &t->next[1];
  3288. else
  3289. Host_Error("RemovePortalFromNodes: portal not bounding leaf");
  3290. }
  3291. }
  3292. }
  3293. #define PORTAL_DIST_EPSILON (1.0 / 32.0)
  3294. static double *portalpointsbuffer;
  3295. static int portalpointsbufferoffset;
  3296. static int portalpointsbuffersize;
  3297. static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
  3298. {
  3299. int i, side;
  3300. mnode_t *front, *back, *other_node;
  3301. mplane_t clipplane, *plane;
  3302. portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
  3303. int numfrontpoints, numbackpoints;
  3304. double *frontpoints, *backpoints;
  3305. // if a leaf, we're done
  3306. if (!node->plane)
  3307. return;
  3308. // get some space for our clipping operations to use
  3309. if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
  3310. {
  3311. portalpointsbuffersize = portalpointsbufferoffset * 2;
  3312. portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
  3313. }
  3314. frontpoints = portalpointsbuffer + portalpointsbufferoffset;
  3315. portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
  3316. backpoints = portalpointsbuffer + portalpointsbufferoffset;
  3317. portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
  3318. plane = node->plane;
  3319. front = node->children[0];
  3320. back = node->children[1];
  3321. if (front == back)
  3322. Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
  3323. // create the new portal by generating a polygon for the node plane,
  3324. // and clipping it by all of the other portals(which came from nodes above this one)
  3325. nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
  3326. nodeportal->plane = *plane;
  3327. // TODO: calculate node bounding boxes during recursion and calculate a maximum plane size accordingly to improve precision (as most maps do not need 1 billion unit plane polygons)
  3328. PolygonD_QuadForPlane(nodeportal->points, nodeportal->plane.normal[0], nodeportal->plane.normal[1], nodeportal->plane.normal[2], nodeportal->plane.dist, 1024.0*1024.0*1024.0);
  3329. nodeportal->numpoints = 4;
  3330. // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
  3331. for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
  3332. {
  3333. clipplane = portal->plane;
  3334. if (portal->nodes[0] == portal->nodes[1])
  3335. Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
  3336. if (portal->nodes[0] == node)
  3337. side = 0;
  3338. else if (portal->nodes[1] == node)
  3339. {
  3340. clipplane.dist = -clipplane.dist;
  3341. VectorNegate(clipplane.normal, clipplane.normal);
  3342. side = 1;
  3343. }
  3344. else
  3345. {
  3346. Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
  3347. side = 0; // hush warning
  3348. }
  3349. for (i = 0;i < nodeportal->numpoints*3;i++)
  3350. frontpoints[i] = nodeportal->points[i];
  3351. PolygonD_Divide(nodeportal->numpoints, frontpoints, clipplane.normal[0], clipplane.normal[1], clipplane.normal[2], clipplane.dist, PORTAL_DIST_EPSILON, MAX_PORTALPOINTS, nodeportal->points, &nodeportal->numpoints, 0, NULL, NULL, NULL);
  3352. if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
  3353. break;
  3354. }
  3355. if (nodeportal->numpoints < 3)
  3356. {
  3357. Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
  3358. nodeportal->numpoints = 0;
  3359. }
  3360. else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
  3361. {
  3362. Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
  3363. nodeportal->numpoints = 0;
  3364. }
  3365. AddPortalToNodes(nodeportal, front, back);
  3366. // split the portals of this node along this node's plane and assign them to the children of this node
  3367. // (migrating the portals downward through the tree)
  3368. for (portal = (portal_t *)node->portals;portal;portal = nextportal)
  3369. {
  3370. if (portal->nodes[0] == portal->nodes[1])
  3371. Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
  3372. if (portal->nodes[0] == node)
  3373. side = 0;
  3374. else if (portal->nodes[1] == node)
  3375. side = 1;
  3376. else
  3377. {
  3378. Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
  3379. side = 0; // hush warning
  3380. }
  3381. nextportal = portal->next[side];
  3382. if (!portal->numpoints)
  3383. continue;
  3384. other_node = portal->nodes[!side];
  3385. RemovePortalFromNodes(portal);
  3386. // cut the portal into two portals, one on each side of the node plane
  3387. PolygonD_Divide(portal->numpoints, portal->points, plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, PORTAL_DIST_EPSILON, MAX_PORTALPOINTS, frontpoints, &numfrontpoints, MAX_PORTALPOINTS, backpoints, &numbackpoints, NULL);
  3388. if (!numfrontpoints)
  3389. {
  3390. if (side == 0)
  3391. AddPortalToNodes(portal, back, other_node);
  3392. else
  3393. AddPortalToNodes(portal, other_node, back);
  3394. continue;
  3395. }
  3396. if (!numbackpoints)
  3397. {
  3398. if (side == 0)
  3399. AddPortalToNodes(portal, front, other_node);
  3400. else
  3401. AddPortalToNodes(portal, other_node, front);
  3402. continue;
  3403. }
  3404. // the portal is split
  3405. splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
  3406. temp = splitportal->chain;
  3407. *splitportal = *portal;
  3408. splitportal->chain = temp;
  3409. for (i = 0;i < numbackpoints*3;i++)
  3410. splitportal->points[i] = backpoints[i];
  3411. splitportal->numpoints = numbackpoints;
  3412. for (i = 0;i < numfrontpoints*3;i++)
  3413. portal->points[i] = frontpoints[i];
  3414. portal->numpoints = numfrontpoints;
  3415. if (side == 0)
  3416. {
  3417. AddPortalToNodes(portal, front, other_node);
  3418. AddPortalToNodes(splitportal, back, other_node);
  3419. }
  3420. else
  3421. {
  3422. AddPortalToNodes(portal, other_node, front);
  3423. AddPortalToNodes(splitportal, other_node, back);
  3424. }
  3425. }
  3426. Mod_Q1BSP_RecursiveNodePortals(front);
  3427. Mod_Q1BSP_RecursiveNodePortals(back);
  3428. portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
  3429. }
  3430. static void Mod_Q1BSP_MakePortals(void)
  3431. {
  3432. Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
  3433. portalpointsbufferoffset = 0;
  3434. portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
  3435. portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
  3436. Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
  3437. Mem_Free(portalpointsbuffer);
  3438. portalpointsbuffer = NULL;
  3439. portalpointsbufferoffset = 0;
  3440. portalpointsbuffersize = 0;
  3441. Mod_Q1BSP_FinalizePortals();
  3442. Mem_ExpandableArray_FreeArray(&portalarray);
  3443. }
  3444. //Returns PVS data for a given point
  3445. //(note: can return NULL)
  3446. static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
  3447. {
  3448. mnode_t *node;
  3449. node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
  3450. while (node->plane)
  3451. node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
  3452. if (((mleaf_t *)node)->clusterindex >= 0)
  3453. return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
  3454. else
  3455. return NULL;
  3456. }
  3457. static void Mod_Q1BSP_FatPVS_RecursiveBSPNode(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbytes, mnode_t *node)
  3458. {
  3459. while (node->plane)
  3460. {
  3461. float d = PlaneDiff(org, node->plane);
  3462. if (d > radius)
  3463. node = node->children[0];
  3464. else if (d < -radius)
  3465. node = node->children[1];
  3466. else
  3467. {
  3468. // go down both sides
  3469. Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
  3470. node = node->children[1];
  3471. }
  3472. }
  3473. // if this leaf is in a cluster, accumulate the pvs bits
  3474. if (((mleaf_t *)node)->clusterindex >= 0)
  3475. {
  3476. int i;
  3477. unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
  3478. for (i = 0;i < pvsbytes;i++)
  3479. pvsbuffer[i] |= pvs[i];
  3480. }
  3481. }
  3482. //Calculates a PVS that is the inclusive or of all leafs within radius pixels
  3483. //of the given point.
  3484. static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
  3485. {
  3486. int bytes = model->brush.num_pvsclusterbytes;
  3487. bytes = min(bytes, pvsbufferlength);
  3488. if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
  3489. {
  3490. memset(pvsbuffer, 0xFF, bytes);
  3491. return bytes;
  3492. }
  3493. if (!merge)
  3494. memset(pvsbuffer, 0, bytes);
  3495. Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
  3496. return bytes;
  3497. }
  3498. static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
  3499. {
  3500. vec3_t size;
  3501. const hull_t *hull;
  3502. VectorSubtract(inmaxs, inmins, size);
  3503. if (cmodel->brush.ishlbsp)
  3504. {
  3505. if (size[0] < 3)
  3506. hull = &cmodel->brushq1.hulls[0]; // 0x0x0
  3507. else if (size[0] <= 32)
  3508. {
  3509. if (size[2] < 54) // pick the nearest of 36 or 72
  3510. hull = &cmodel->brushq1.hulls[3]; // 32x32x36
  3511. else
  3512. hull = &cmodel->brushq1.hulls[1]; // 32x32x72
  3513. }
  3514. else
  3515. hull = &cmodel->brushq1.hulls[2]; // 64x64x64
  3516. }
  3517. else
  3518. {
  3519. if (size[0] < 3)
  3520. hull = &cmodel->brushq1.hulls[0]; // 0x0x0
  3521. else if (size[0] <= 32)
  3522. hull = &cmodel->brushq1.hulls[1]; // 32x32x56
  3523. else
  3524. hull = &cmodel->brushq1.hulls[2]; // 64x64x88
  3525. }
  3526. VectorCopy(inmins, outmins);
  3527. VectorAdd(inmins, hull->clip_size, outmaxs);
  3528. }
  3529. static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
  3530. {
  3531. int j;
  3532. int numshadowmeshtriangles = 0;
  3533. msurface_t *surface;
  3534. if (cls.state == ca_dedicated)
  3535. return 0;
  3536. // make a single combined shadow mesh to allow optimized shadow volume creation
  3537. for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
  3538. {
  3539. surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
  3540. numshadowmeshtriangles += surface->num_triangles;
  3541. }
  3542. mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
  3543. for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
  3544. if (surface->num_triangles > 0)
  3545. Mod_ShadowMesh_AddMesh(mod->mempool, mod->brush.shadowmesh, NULL, NULL, NULL, mod->surfmesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (mod->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
  3546. mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
  3547. if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
  3548. Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
  3549. return numshadowmeshtriangles;
  3550. }
  3551. void Mod_CollisionBIH_TraceLineAgainstSurfaces(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask);
  3552. void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
  3553. {
  3554. int i, j, k;
  3555. sizebuf_t lumpsb[HEADER_LUMPS];
  3556. mmodel_t *bm;
  3557. float dist, modelyawradius, modelradius;
  3558. msurface_t *surface;
  3559. hullinfo_t hullinfo;
  3560. int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
  3561. model_brush_lightstyleinfo_t styleinfo[256];
  3562. unsigned char *datapointer;
  3563. sizebuf_t sb;
  3564. MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
  3565. mod->type = mod_brushq1;
  3566. mod->brush.ishlbsp = false;
  3567. mod->brush.isbsp2rmqe = false;
  3568. mod->brush.isbsp2 = false;
  3569. mod->brush.isq2bsp = false;
  3570. mod->brush.isq3bsp = false;
  3571. mod->brush.skymasking = true;
  3572. i = MSG_ReadLittleLong(&sb);
  3573. switch(i)
  3574. {
  3575. case BSPVERSION:
  3576. mod->modeldatatypestring = "Q1BSP";
  3577. break;
  3578. case 30:
  3579. mod->brush.ishlbsp = true;
  3580. mod->modeldatatypestring = "HLBSP";
  3581. break;
  3582. case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
  3583. mod->brush.isbsp2 = true;
  3584. mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
  3585. mod->modeldatatypestring = "Q1BSP2rmqe";
  3586. break;
  3587. case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
  3588. mod->brush.isbsp2 = true;
  3589. mod->modeldatatypestring = "Q1BSP2";
  3590. break;
  3591. default:
  3592. mod->modeldatatypestring = "Unknown BSP";
  3593. Host_Error("Mod_Q1BSP_Load: %s has wrong version number %i: supported versions are 29 (Quake), 30 (Half-Life), \"BSP2\" or \"2PSB\" (rmqe)", mod->name, i);
  3594. return;
  3595. }
  3596. // fill in hull info
  3597. VectorClear (hullinfo.hullsizes[0][0]);
  3598. VectorClear (hullinfo.hullsizes[0][1]);
  3599. if (mod->brush.ishlbsp)
  3600. {
  3601. hullinfo.filehulls = 4;
  3602. VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
  3603. VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
  3604. VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
  3605. VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
  3606. VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
  3607. VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
  3608. }
  3609. else
  3610. {
  3611. hullinfo.filehulls = 4;
  3612. VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
  3613. VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
  3614. VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
  3615. VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
  3616. }
  3617. // read lumps
  3618. for (i = 0; i < HEADER_LUMPS; i++)
  3619. {
  3620. int offset = MSG_ReadLittleLong(&sb);
  3621. int size = MSG_ReadLittleLong(&sb);
  3622. if (offset < 0 || offset + size > sb.cursize)
  3623. Host_Error("Mod_Q1BSP_Load: %s has invalid lump %i (offset %i, size %i, file size %i)\n", mod->name, i, offset, size, (int)sb.cursize);
  3624. MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
  3625. }
  3626. mod->soundfromcenter = true;
  3627. mod->TraceBox = Mod_Q1BSP_TraceBox;
  3628. mod->TraceLine = Mod_Q1BSP_TraceLine;
  3629. mod->TracePoint = Mod_Q1BSP_TracePoint;
  3630. mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
  3631. mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
  3632. mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
  3633. mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
  3634. mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
  3635. mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
  3636. mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
  3637. mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
  3638. mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
  3639. mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
  3640. mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
  3641. mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
  3642. mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
  3643. mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
  3644. mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
  3645. mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
  3646. mod->Draw = R_Q1BSP_Draw;
  3647. mod->DrawDepth = R_Q1BSP_DrawDepth;
  3648. mod->DrawDebug = R_Q1BSP_DrawDebug;
  3649. mod->DrawPrepass = R_Q1BSP_DrawPrepass;
  3650. mod->GetLightInfo = R_Q1BSP_GetLightInfo;
  3651. mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
  3652. mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
  3653. mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
  3654. mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
  3655. mod->DrawLight = R_Q1BSP_DrawLight;
  3656. // load into heap
  3657. mod->brush.qw_md4sum = 0;
  3658. mod->brush.qw_md4sum2 = 0;
  3659. for (i = 0;i < HEADER_LUMPS;i++)
  3660. {
  3661. int temp;
  3662. if (i == LUMP_ENTITIES)
  3663. continue;
  3664. temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
  3665. mod->brush.qw_md4sum ^= LittleLong(temp);
  3666. if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
  3667. continue;
  3668. mod->brush.qw_md4sum2 ^= LittleLong(temp);
  3669. }
  3670. Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
  3671. Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
  3672. Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
  3673. Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
  3674. Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
  3675. Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
  3676. Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
  3677. Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
  3678. Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
  3679. Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
  3680. Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
  3681. // load submodels before leafs because they contain the number of vis leafs
  3682. Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
  3683. Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
  3684. Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
  3685. Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
  3686. for (i = 0; i < HEADER_LUMPS; i++)
  3687. if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
  3688. Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
  3689. // check if the map supports transparent water rendering
  3690. loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
  3691. // we don't need the compressed pvs data anymore
  3692. if (mod->brushq1.data_compressedpvs)
  3693. Mem_Free(mod->brushq1.data_compressedpvs);
  3694. mod->brushq1.data_compressedpvs = NULL;
  3695. mod->brushq1.num_compressedpvs = 0;
  3696. Mod_Q1BSP_MakeHull0();
  3697. if (mod_bsp_portalize.integer)
  3698. Mod_Q1BSP_MakePortals();
  3699. mod->numframes = 2; // regular and alternate animation
  3700. mod->numskins = 1;
  3701. // make a single combined shadow mesh to allow optimized shadow volume creation
  3702. Mod_Q1BSP_CreateShadowMesh(loadmodel);
  3703. if (loadmodel->brush.numsubmodels)
  3704. loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
  3705. // LordHavoc: to clear the fog around the original quake submodel code, I
  3706. // will explain:
  3707. // first of all, some background info on the submodels:
  3708. // model 0 is the map model (the world, named maps/e1m1.bsp for example)
  3709. // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
  3710. // now the weird for loop itself:
  3711. // the loop functions in an odd way, on each iteration it sets up the
  3712. // current 'mod' model (which despite the confusing code IS the model of
  3713. // the number i), at the end of the loop it duplicates the model to become
  3714. // the next submodel, and loops back to set up the new submodel.
  3715. // LordHavoc: now the explanation of my sane way (which works identically):
  3716. // set up the world model, then on each submodel copy from the world model
  3717. // and set up the submodel with the respective model info.
  3718. totalstylesurfaces = 0;
  3719. totalstyles = 0;
  3720. for (i = 0;i < mod->brush.numsubmodels;i++)
  3721. {
  3722. memset(stylecounts, 0, sizeof(stylecounts));
  3723. for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
  3724. {
  3725. surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
  3726. for (j = 0;j < MAXLIGHTMAPS;j++)
  3727. stylecounts[surface->lightmapinfo->styles[j]]++;
  3728. }
  3729. for (k = 0;k < 255;k++)
  3730. {
  3731. totalstyles++;
  3732. if (stylecounts[k])
  3733. totalstylesurfaces += stylecounts[k];
  3734. }
  3735. }
  3736. datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
  3737. for (i = 0;i < mod->brush.numsubmodels;i++)
  3738. {
  3739. // LordHavoc: this code was originally at the end of this loop, but
  3740. // has been transformed to something more readable at the start here.
  3741. if (i > 0)
  3742. {
  3743. char name[10];
  3744. // duplicate the basic information
  3745. dpsnprintf(name, sizeof(name), "*%i", i);
  3746. mod = Mod_FindName(name, loadmodel->name);
  3747. // copy the base model to this one
  3748. *mod = *loadmodel;
  3749. // rename the clone back to its proper name
  3750. strlcpy(mod->name, name, sizeof(mod->name));
  3751. mod->brush.parentmodel = loadmodel;
  3752. // textures and memory belong to the main model
  3753. mod->texturepool = NULL;
  3754. mod->mempool = NULL;
  3755. mod->brush.GetPVS = NULL;
  3756. mod->brush.FatPVS = NULL;
  3757. mod->brush.BoxTouchingPVS = NULL;
  3758. mod->brush.BoxTouchingLeafPVS = NULL;
  3759. mod->brush.BoxTouchingVisibleLeafs = NULL;
  3760. mod->brush.FindBoxClusters = NULL;
  3761. mod->brush.LightPoint = NULL;
  3762. mod->brush.AmbientSoundLevelsForPoint = NULL;
  3763. }
  3764. mod->brush.submodel = i;
  3765. if (loadmodel->brush.submodels)
  3766. loadmodel->brush.submodels[i] = mod;
  3767. bm = &mod->brushq1.submodels[i];
  3768. mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
  3769. for (j=1 ; j<MAX_MAP_HULLS ; j++)
  3770. {
  3771. mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
  3772. mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
  3773. }
  3774. mod->firstmodelsurface = bm->firstface;
  3775. mod->nummodelsurfaces = bm->numfaces;
  3776. // set node/leaf parents for this submodel
  3777. Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
  3778. // this has to occur after hull info has been set, as it uses Mod_Q1BSP_PointSuperContents
  3779. Mod_Q1BSP_AssignNoShadowSkySurfaces(mod);
  3780. // make the model surface list (used by shadowing/lighting)
  3781. mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
  3782. Mod_MakeSortedSurfaces(mod);
  3783. // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
  3784. // (previously this code measured the radius of the vertices of surfaces in the submodel, but that broke submodels that contain only CLIP brushes, which do not produce surfaces)
  3785. VectorCopy(bm->mins, mod->normalmins);
  3786. VectorCopy(bm->maxs, mod->normalmaxs);
  3787. dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
  3788. modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
  3789. modelyawradius = dist*dist+modelyawradius*modelyawradius;
  3790. modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
  3791. modelradius = modelyawradius + modelradius * modelradius;
  3792. modelyawradius = sqrt(modelyawradius);
  3793. modelradius = sqrt(modelradius);
  3794. mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
  3795. mod->yawmins[2] = mod->normalmins[2];
  3796. mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
  3797. mod->yawmaxs[2] = mod->normalmaxs[2];
  3798. mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
  3799. mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
  3800. mod->radius = modelradius;
  3801. mod->radius2 = modelradius * modelradius;
  3802. // this gets altered below if sky or water is used
  3803. mod->DrawSky = NULL;
  3804. mod->DrawAddWaterPlanes = NULL;
  3805. // scan surfaces for sky and water and flag the submodel as possessing these features or not
  3806. // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
  3807. if (mod->nummodelsurfaces)
  3808. {
  3809. for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
  3810. if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
  3811. break;
  3812. if (j < mod->nummodelsurfaces)
  3813. mod->DrawSky = R_Q1BSP_DrawSky;
  3814. for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
  3815. if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
  3816. break;
  3817. if (j < mod->nummodelsurfaces)
  3818. mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
  3819. // build lightstyle update chains
  3820. // (used to rapidly mark lightmapupdateflags on many surfaces
  3821. // when d_lightstylevalue changes)
  3822. memset(stylecounts, 0, sizeof(stylecounts));
  3823. for (k = 0;k < mod->nummodelsurfaces;k++)
  3824. {
  3825. surface = mod->data_surfaces + mod->firstmodelsurface + k;
  3826. for (j = 0;j < MAXLIGHTMAPS;j++)
  3827. stylecounts[surface->lightmapinfo->styles[j]]++;
  3828. }
  3829. mod->brushq1.num_lightstyles = 0;
  3830. for (k = 0;k < 255;k++)
  3831. {
  3832. if (stylecounts[k])
  3833. {
  3834. styleinfo[mod->brushq1.num_lightstyles].style = k;
  3835. styleinfo[mod->brushq1.num_lightstyles].value = 0;
  3836. styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
  3837. styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
  3838. remapstyles[k] = mod->brushq1.num_lightstyles;
  3839. mod->brushq1.num_lightstyles++;
  3840. }
  3841. }
  3842. for (k = 0;k < mod->nummodelsurfaces;k++)
  3843. {
  3844. surface = mod->data_surfaces + mod->firstmodelsurface + k;
  3845. for (j = 0;j < MAXLIGHTMAPS;j++)
  3846. {
  3847. if (surface->lightmapinfo->styles[j] != 255)
  3848. {
  3849. int r = remapstyles[surface->lightmapinfo->styles[j]];
  3850. styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
  3851. }
  3852. }
  3853. }
  3854. mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
  3855. memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
  3856. }
  3857. else
  3858. {
  3859. // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
  3860. Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
  3861. }
  3862. //mod->brushq1.num_visleafs = bm->visleafs;
  3863. // build a Bounding Interval Hierarchy for culling triangles in light rendering
  3864. Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
  3865. if (mod_q1bsp_polygoncollisions.integer)
  3866. {
  3867. mod->collision_bih = mod->render_bih;
  3868. // point traces and contents checks still use the bsp tree
  3869. mod->TraceLine = Mod_CollisionBIH_TraceLine;
  3870. mod->TraceBox = Mod_CollisionBIH_TraceBox;
  3871. mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
  3872. mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
  3873. }
  3874. // generate VBOs and other shared data before cloning submodels
  3875. if (i == 0)
  3876. {
  3877. Mod_BuildVBOs();
  3878. Mod_Q1BSP_LoadMapBrushes();
  3879. //Mod_Q1BSP_ProcessLightList();
  3880. }
  3881. }
  3882. Con_DPrintf("Stats for q1bsp model \"%s\": %i faces, %i nodes, %i leafs, %i visleafs, %i visleafportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
  3883. }
  3884. int Mod_Q2BSP_SuperContentsFromNativeContents(int nativecontents)
  3885. {
  3886. int supercontents = 0;
  3887. if (nativecontents & CONTENTSQ2_SOLID)
  3888. supercontents |= SUPERCONTENTS_SOLID;
  3889. if (nativecontents & CONTENTSQ2_WATER)
  3890. supercontents |= SUPERCONTENTS_WATER;
  3891. if (nativecontents & CONTENTSQ2_SLIME)
  3892. supercontents |= SUPERCONTENTS_SLIME;
  3893. if (nativecontents & CONTENTSQ2_LAVA)
  3894. supercontents |= SUPERCONTENTS_LAVA;
  3895. if (nativecontents & CONTENTSQ2_MONSTER)
  3896. supercontents |= SUPERCONTENTS_BODY;
  3897. if (nativecontents & CONTENTSQ2_DEADMONSTER)
  3898. supercontents |= SUPERCONTENTS_CORPSE;
  3899. if (nativecontents & CONTENTSQ2_PLAYERCLIP)
  3900. supercontents |= SUPERCONTENTS_PLAYERCLIP;
  3901. if (nativecontents & CONTENTSQ2_MONSTERCLIP)
  3902. supercontents |= SUPERCONTENTS_MONSTERCLIP;
  3903. if (!(nativecontents & CONTENTSQ2_TRANSLUCENT))
  3904. supercontents |= SUPERCONTENTS_OPAQUE;
  3905. return supercontents;
  3906. }
  3907. int Mod_Q2BSP_NativeContentsFromSuperContents(int supercontents)
  3908. {
  3909. int nativecontents = 0;
  3910. if (supercontents & SUPERCONTENTS_SOLID)
  3911. nativecontents |= CONTENTSQ2_SOLID;
  3912. if (supercontents & SUPERCONTENTS_WATER)
  3913. nativecontents |= CONTENTSQ2_WATER;
  3914. if (supercontents & SUPERCONTENTS_SLIME)
  3915. nativecontents |= CONTENTSQ2_SLIME;
  3916. if (supercontents & SUPERCONTENTS_LAVA)
  3917. nativecontents |= CONTENTSQ2_LAVA;
  3918. if (supercontents & SUPERCONTENTS_BODY)
  3919. nativecontents |= CONTENTSQ2_MONSTER;
  3920. if (supercontents & SUPERCONTENTS_CORPSE)
  3921. nativecontents |= CONTENTSQ2_DEADMONSTER;
  3922. if (supercontents & SUPERCONTENTS_PLAYERCLIP)
  3923. nativecontents |= CONTENTSQ2_PLAYERCLIP;
  3924. if (supercontents & SUPERCONTENTS_MONSTERCLIP)
  3925. nativecontents |= CONTENTSQ2_MONSTERCLIP;
  3926. if (!(supercontents & SUPERCONTENTS_OPAQUE))
  3927. nativecontents |= CONTENTSQ2_TRANSLUCENT;
  3928. return nativecontents;
  3929. }
  3930. static void Mod_Q2BSP_LoadVisibility(sizebuf_t *sb)
  3931. {
  3932. int i, count;
  3933. loadmodel->brushq1.num_compressedpvs = 0;
  3934. loadmodel->brushq1.data_compressedpvs = NULL;
  3935. loadmodel->brush.num_pvsclusters = 0;
  3936. loadmodel->brush.num_pvsclusterbytes = 0;
  3937. loadmodel->brush.data_pvsclusters = NULL;
  3938. if (!sb->cursize)
  3939. return;
  3940. count = MSG_ReadLittleLong(sb);
  3941. loadmodel->brush.num_pvsclusters = count;
  3942. loadmodel->brush.num_pvsclusterbytes = (count+7)>>3;
  3943. loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*loadmodel->brush.num_pvsclusterbytes);
  3944. for (i = 0;i < count;i++)
  3945. {
  3946. int pvsofs = MSG_ReadLittleLong(sb);
  3947. /*int phsofs = */MSG_ReadLittleLong(sb);
  3948. // decompress the vis data for this cluster
  3949. // (note this accesses the underlying data store of sb, which is kind of evil)
  3950. Mod_Q1BSP_DecompressVis(sb->data + pvsofs, sb->data + sb->cursize, loadmodel->brush.data_pvsclusters + i * loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.data_pvsclusters + (i+1) * loadmodel->brush.num_pvsclusterbytes);
  3951. }
  3952. // hush the loading error check later - we had to do random access on this lump, so we didn't read to the end
  3953. sb->readcount = sb->cursize;
  3954. }
  3955. static void Mod_Q2BSP_LoadNodes(sizebuf_t *sb)
  3956. {
  3957. int i, j, count, p, child[2];
  3958. mnode_t *out;
  3959. int structsize = 28;
  3960. if (sb->cursize % structsize)
  3961. Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
  3962. count = sb->cursize / structsize;
  3963. if (count == 0)
  3964. Host_Error("Mod_Q2BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
  3965. out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
  3966. loadmodel->brush.data_nodes = out;
  3967. loadmodel->brush.num_nodes = count;
  3968. for ( i=0 ; i<count ; i++, out++)
  3969. {
  3970. p = MSG_ReadLittleLong(sb);
  3971. out->plane = loadmodel->brush.data_planes + p;
  3972. child[0] = MSG_ReadLittleLong(sb);
  3973. child[1] = MSG_ReadLittleLong(sb);
  3974. out->mins[0] = MSG_ReadLittleShort(sb);
  3975. out->mins[1] = MSG_ReadLittleShort(sb);
  3976. out->mins[2] = MSG_ReadLittleShort(sb);
  3977. out->maxs[0] = MSG_ReadLittleShort(sb);
  3978. out->maxs[1] = MSG_ReadLittleShort(sb);
  3979. out->maxs[2] = MSG_ReadLittleShort(sb);
  3980. out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
  3981. out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
  3982. if (out->firstsurface + out->numsurfaces > (unsigned int)loadmodel->num_surfaces)
  3983. {
  3984. Con_Printf("Mod_Q2BSP_LoadNodes: invalid surface index range %i+%i (file has only %i surfaces)\n", out->firstsurface, out->numsurfaces, loadmodel->num_surfaces);
  3985. out->firstsurface = 0;
  3986. out->numsurfaces = 0;
  3987. }
  3988. for (j=0 ; j<2 ; j++)
  3989. {
  3990. p = child[j];
  3991. if (p >= 0)
  3992. {
  3993. if (p < loadmodel->brush.num_nodes)
  3994. out->children[j] = loadmodel->brush.data_nodes + p;
  3995. else
  3996. {
  3997. Con_Printf("Mod_Q2BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
  3998. // map it to the solid leaf
  3999. out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
  4000. }
  4001. }
  4002. else
  4003. {
  4004. // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
  4005. p = -(p+1);
  4006. if (p < loadmodel->brush.num_leafs)
  4007. out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
  4008. else
  4009. {
  4010. Con_Printf("Mod_Q2BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
  4011. // map it to the solid leaf
  4012. out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
  4013. }
  4014. }
  4015. }
  4016. }
  4017. Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
  4018. }
  4019. static void Mod_Q2BSP_LoadTexinfo(sizebuf_t *sb)
  4020. {
  4021. mtexinfo_t *out;
  4022. int i, l, count;
  4023. int structsize = 76;
  4024. int maxtextures = 1024; // hardcoded limit of quake2 engine, so we may as well use it as an upper bound
  4025. char filename[MAX_QPATH];
  4026. if (sb->cursize % structsize)
  4027. Host_Error("Mod_Q2BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
  4028. count = sb->cursize / structsize;
  4029. out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  4030. loadmodel->brushq1.texinfo = out;
  4031. loadmodel->brushq1.numtexinfo = count;
  4032. loadmodel->num_texturesperskin = 0;
  4033. loadmodel->data_textures = (texture_t*)Mem_Alloc(loadmodel->mempool, maxtextures * sizeof(texture_t));
  4034. for (i = 0;i < count;i++, out++)
  4035. {
  4036. int j, k;
  4037. for (k = 0;k < 2;k++)
  4038. for (j = 0;j < 4;j++)
  4039. out->vecs[k][j] = MSG_ReadLittleFloat(sb);
  4040. out->q2flags = MSG_ReadLittleLong(sb);
  4041. out->q2value = MSG_ReadLittleLong(sb);
  4042. MSG_ReadBytes(sb, 32, (unsigned char*)out->q2texture);
  4043. out->q2texture[31] = 0; // make absolutely sure it is terminated
  4044. out->q2nexttexinfo = MSG_ReadLittleLong(sb);
  4045. // find an existing match for the texture if possible
  4046. dpsnprintf(filename, sizeof(filename), "textures/%s.wal", out->q2texture);
  4047. for (j = 0;j < loadmodel->num_texturesperskin;j++)
  4048. if (!strcmp(filename, loadmodel->data_textures[j].name)
  4049. && out->q2flags == loadmodel->data_textures[j].q2flags
  4050. && out->q2value == loadmodel->data_textures[j].q2value)
  4051. break;
  4052. // if we don't find the texture, store the new texture
  4053. if (j == loadmodel->num_texturesperskin)
  4054. {
  4055. if (loadmodel->num_texturesperskin < maxtextures)
  4056. {
  4057. texture_t *tx = loadmodel->data_textures + j;
  4058. int q2flags = out->q2flags;
  4059. unsigned char *walfile = NULL;
  4060. fs_offset_t walfilesize = 0;
  4061. Mod_LoadTextureFromQ3Shader(tx, filename, true, true, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
  4062. // now read the .wal file to get metadata (even if a .tga was overriding it, we still need the wal data)
  4063. walfile = FS_LoadFile(filename, tempmempool, true, &walfilesize);
  4064. if (walfile)
  4065. {
  4066. int w, h;
  4067. LoadWAL_GetMetadata(walfile, (int)walfilesize, &w, &h, NULL, NULL, &tx->q2contents, NULL);
  4068. tx->width = w;
  4069. tx->height = h;
  4070. Mem_Free(walfile);
  4071. }
  4072. else
  4073. {
  4074. tx->width = 16;
  4075. tx->height = 16;
  4076. }
  4077. tx->q2flags = out->q2flags;
  4078. tx->q2value = out->q2value;
  4079. // also modify the texture to have the correct contents and such based on flags
  4080. // note that we create multiple texture_t structures if q2flags differs
  4081. if (q2flags & Q2SURF_LIGHT)
  4082. {
  4083. // doesn't mean anything to us
  4084. }
  4085. if (q2flags & Q2SURF_SLICK)
  4086. {
  4087. // would be nice to support...
  4088. }
  4089. if (q2flags & Q2SURF_SKY)
  4090. {
  4091. // sky is a rather specific thing
  4092. q2flags &= ~Q2SURF_NODRAW; // quake2 had a slightly different meaning than we have in mind here...
  4093. tx->basematerialflags = MATERIALFLAG_SKY;
  4094. tx->supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE;
  4095. tx->surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
  4096. }
  4097. if (q2flags & Q2SURF_WARP)
  4098. {
  4099. // we use a scroll instead of a warp
  4100. tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_FULLBRIGHT;
  4101. // if it's also transparent, we can enable the WATERSHADER
  4102. // but we do not set the WATERALPHA flag because we don't
  4103. // want to honor r_wateralpha in q2bsp
  4104. // (it would go against the artistic intent)
  4105. if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66))
  4106. tx->basematerialflags |= MATERIALFLAG_WATERSHADER;
  4107. }
  4108. if (q2flags & Q2SURF_TRANS33)
  4109. {
  4110. tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
  4111. tx->basealpha = 1.0f / 3.0f;
  4112. tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
  4113. if (tx->q2contents & Q2CONTENTS_SOLID)
  4114. tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
  4115. }
  4116. if (q2flags & Q2SURF_TRANS66)
  4117. {
  4118. tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
  4119. tx->basealpha = 2.0f / 3.0f;
  4120. tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
  4121. if (tx->q2contents & Q2CONTENTS_SOLID)
  4122. tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
  4123. }
  4124. if ((q2flags & Q2SURF_FLOWING) && tx->materialshaderpass != NULL)
  4125. {
  4126. tx->materialshaderpass->tcmods[0].tcmod = Q3TCMOD_SCROLL;
  4127. if (q2flags & Q2SURF_WARP)
  4128. tx->materialshaderpass->tcmods[0].parms[0] = -0.5f;
  4129. else
  4130. tx->materialshaderpass->tcmods[0].parms[0] = -1.6f;
  4131. tx->materialshaderpass->tcmods[0].parms[1] = 0.0f;
  4132. }
  4133. if (q2flags & Q2SURF_ALPHATEST)
  4134. {
  4135. // KMQUAKE2 and other modded engines added this flag for lit alpha tested surfaces
  4136. tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
  4137. }
  4138. else if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66 | Q2SURF_WARP))
  4139. {
  4140. if (!mod_q2bsp_littransparentsurfaces.integer)
  4141. tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
  4142. }
  4143. if (q2flags & Q2SURF_NODRAW)
  4144. {
  4145. tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
  4146. }
  4147. if (tx->q2contents & (Q2CONTENTS_TRANSLUCENT | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_PLAYERCLIP))
  4148. tx->q2contents |= Q2CONTENTS_DETAIL;
  4149. if (!(tx->q2contents & (Q2CONTENTS_SOLID | Q2CONTENTS_WINDOW | Q2CONTENTS_AUX | Q2CONTENTS_LAVA | Q2CONTENTS_SLIME | Q2CONTENTS_WATER | Q2CONTENTS_MIST | Q2CONTENTS_PLAYERCLIP | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_MIST)))
  4150. tx->q2contents |= Q2CONTENTS_SOLID;
  4151. if (tx->q2flags & (Q2SURF_HINT | Q2SURF_SKIP))
  4152. tx->q2contents = 0;
  4153. tx->supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(tx->q2contents);
  4154. // set the current values to the base values
  4155. tx->currentframe = tx;
  4156. tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
  4157. tx->currentmaterialflags = tx->basematerialflags;
  4158. loadmodel->num_texturesperskin++;
  4159. loadmodel->num_textures = loadmodel->num_texturesperskin;
  4160. }
  4161. else
  4162. {
  4163. Con_Printf("Mod_Q2BSP_LoadTexinfo: max textures reached (%i)\n", maxtextures);
  4164. j = 0; // use first texture and give up
  4165. }
  4166. }
  4167. // store the index we found for this texture
  4168. out->textureindex = j;
  4169. }
  4170. // realloc the textures array now that we know how many we actually need
  4171. loadmodel->data_textures = (texture_t*)Mem_Realloc(loadmodel->mempool, loadmodel->data_textures, loadmodel->num_texturesperskin * sizeof(texture_t));
  4172. // now assemble the texture chains
  4173. // if we encounter the textures out of order, the later ones won't mark the earlier ones in a sequence, so the earlier
  4174. for (i = 0, out = loadmodel->brushq1.texinfo;i < count;i++, out++)
  4175. {
  4176. int j, k;
  4177. texture_t *t = loadmodel->data_textures + out->textureindex;
  4178. t->currentframe = t; // fix the reallocated pointer
  4179. // if this is not animated, skip it
  4180. // if this is already processed, skip it (part of an existing sequence)
  4181. if (out->q2nexttexinfo == 0 || t->animated)
  4182. continue;
  4183. // store the array of frames to use
  4184. t->animated = 2; // q2bsp animation
  4185. t->anim_total[0] = 0;
  4186. t->anim_total[1] = 0;
  4187. // gather up to 10 frames (we don't support more)
  4188. for (j = i;j >= 0 && t->anim_total[0] < (int)(sizeof(t->anim_frames[0])/sizeof(t->anim_frames[0][0]));j = loadmodel->brushq1.texinfo[j].q2nexttexinfo)
  4189. {
  4190. // detect looping and stop there
  4191. if (t->anim_total[0] && loadmodel->brushq1.texinfo[j].textureindex == out->textureindex)
  4192. break;
  4193. t->anim_frames[0][t->anim_total[0]++] = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
  4194. }
  4195. // we could look for the +a sequence here if this is the +0 sequence,
  4196. // but it seems that quake2 did not implement that (even though the
  4197. // files exist in the baseq2 content)
  4198. // write the frame sequence to all the textures involved (just like
  4199. // in the q1bsp loader)
  4200. //
  4201. // note that this can overwrite the rest of the sequence - so if the
  4202. // start of a sequence is found later than the other parts of the
  4203. // sequence, it will go back and rewrite them correctly.
  4204. for (k = 0;k < t->anim_total[0];k++)
  4205. {
  4206. texture_t *txk = t->anim_frames[0][k];
  4207. txk->animated = t->animated;
  4208. txk->anim_total[0] = t->anim_total[0];
  4209. for (l = 0;l < t->anim_total[0];l++)
  4210. txk->anim_frames[0][l] = t->anim_frames[0][l];
  4211. }
  4212. }
  4213. }
  4214. static void Mod_Q2BSP_LoadLighting(sizebuf_t *sb)
  4215. {
  4216. // LordHavoc: this fits exactly the same format that we use in .lit files
  4217. loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
  4218. MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.lightdata);
  4219. }
  4220. static void Mod_Q2BSP_LoadLeafs(sizebuf_t *sb)
  4221. {
  4222. mleaf_t *out;
  4223. int i, j, count, firstmarksurface, nummarksurfaces, firstmarkbrush, nummarkbrushes;
  4224. int structsize = 28;
  4225. if (sb->cursize % structsize)
  4226. Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
  4227. count = sb->cursize / structsize;
  4228. out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
  4229. loadmodel->brush.data_leafs = out;
  4230. loadmodel->brush.num_leafs = count;
  4231. // FIXME: this function could really benefit from some error checking
  4232. for ( i=0 ; i<count ; i++, out++)
  4233. {
  4234. out->contents = MSG_ReadLittleLong(sb);
  4235. out->clusterindex = MSG_ReadLittleShort(sb);
  4236. out->areaindex = MSG_ReadLittleShort(sb);
  4237. out->mins[0] = MSG_ReadLittleShort(sb);
  4238. out->mins[1] = MSG_ReadLittleShort(sb);
  4239. out->mins[2] = MSG_ReadLittleShort(sb);
  4240. out->maxs[0] = MSG_ReadLittleShort(sb);
  4241. out->maxs[1] = MSG_ReadLittleShort(sb);
  4242. out->maxs[2] = MSG_ReadLittleShort(sb);
  4243. firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
  4244. nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
  4245. firstmarkbrush = (unsigned short)MSG_ReadLittleShort(sb);
  4246. nummarkbrushes = (unsigned short)MSG_ReadLittleShort(sb);
  4247. for (j = 0;j < 4;j++)
  4248. out->ambient_sound_level[j] = 0;
  4249. if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
  4250. {
  4251. Con_Print("Mod_Q2BSP_LoadLeafs: invalid clusterindex\n");
  4252. out->clusterindex = -1;
  4253. }
  4254. if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
  4255. {
  4256. out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
  4257. out->numleafsurfaces = nummarksurfaces;
  4258. }
  4259. else
  4260. {
  4261. Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
  4262. out->firstleafsurface = NULL;
  4263. out->numleafsurfaces = 0;
  4264. }
  4265. if (firstmarkbrush >= 0 && firstmarkbrush + nummarkbrushes <= loadmodel->brush.num_leafbrushes)
  4266. {
  4267. out->firstleafbrush = loadmodel->brush.data_leafbrushes + firstmarkbrush;
  4268. out->numleafbrushes = nummarkbrushes;
  4269. }
  4270. else
  4271. {
  4272. Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafbrush range %i:%i outside range %i:%i\n", firstmarkbrush, firstmarkbrush+nummarkbrushes, 0, loadmodel->brush.num_leafbrushes);
  4273. out->firstleafbrush = NULL;
  4274. out->numleafbrushes = 0;
  4275. }
  4276. }
  4277. }
  4278. static void Mod_Q2BSP_LoadLeafBrushes(sizebuf_t *sb)
  4279. {
  4280. int i, j;
  4281. int structsize = 2;
  4282. if (sb->cursize % structsize)
  4283. Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
  4284. loadmodel->brush.num_leafbrushes = sb->cursize / structsize;
  4285. loadmodel->brush.data_leafbrushes = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafbrushes * sizeof(int));
  4286. for (i = 0;i < loadmodel->brush.num_leafbrushes;i++)
  4287. {
  4288. j = (unsigned short) MSG_ReadLittleShort(sb);
  4289. if (j >= loadmodel->brush.num_brushes)
  4290. Host_Error("Mod_Q1BSP_LoadLeafBrushes: bad brush number");
  4291. loadmodel->brush.data_leafbrushes[i] = j;
  4292. }
  4293. }
  4294. static void Mod_Q2BSP_LoadBrushSides(sizebuf_t *sb)
  4295. {
  4296. q3mbrushside_t *out;
  4297. int i, n, count;
  4298. int structsize = 4;
  4299. if (sb->cursize % structsize)
  4300. Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
  4301. count = sb->cursize / structsize;
  4302. out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  4303. loadmodel->brush.data_brushsides = out;
  4304. loadmodel->brush.num_brushsides = count;
  4305. for (i = 0;i < count;i++, out++)
  4306. {
  4307. n = (unsigned short)MSG_ReadLittleShort(sb);
  4308. if (n < 0 || n >= loadmodel->brush.num_planes)
  4309. Host_Error("Mod_Q2BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
  4310. out->plane = loadmodel->brush.data_planes + n;
  4311. n = MSG_ReadLittleShort(sb);
  4312. if (n >= 0)
  4313. {
  4314. if (n >= loadmodel->brushq1.numtexinfo)
  4315. Host_Error("Mod_Q2BSP_LoadBrushSides: invalid texinfo index %i (%i texinfos)", n, loadmodel->brushq1.numtexinfo);
  4316. out->texture = loadmodel->data_textures + loadmodel->brushq1.texinfo[n].textureindex;
  4317. }
  4318. else
  4319. {
  4320. //Con_Printf("Mod_Q2BSP_LoadBrushSides: brushside %i has texinfo index %i < 0, changing to generic texture!\n", i, n);
  4321. out->texture = &mod_q1bsp_texture_solid;
  4322. }
  4323. }
  4324. }
  4325. static void Mod_Q2BSP_LoadBrushes(sizebuf_t *sb)
  4326. {
  4327. q3mbrush_t *out;
  4328. int i, j, firstside, numsides, contents, count, maxplanes, q3surfaceflags, supercontents;
  4329. colplanef_t *planes;
  4330. int structsize = 12;
  4331. qboolean brushmissingtextures;
  4332. int numbrushesmissingtextures = 0;
  4333. int numcreatedtextures = 0;
  4334. if (sb->cursize % structsize)
  4335. Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
  4336. count = sb->cursize / structsize;
  4337. out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  4338. loadmodel->brush.data_brushes = out;
  4339. loadmodel->brush.num_brushes = count;
  4340. maxplanes = 0;
  4341. planes = NULL;
  4342. for (i = 0; i < count; i++, out++)
  4343. {
  4344. firstside = MSG_ReadLittleLong(sb);
  4345. numsides = MSG_ReadLittleLong(sb);
  4346. contents = MSG_ReadLittleLong(sb);
  4347. if (firstside < 0 || firstside + numsides > loadmodel->brush.num_brushsides)
  4348. Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", firstside, firstside + numsides, loadmodel->brush.num_brushsides);
  4349. out->firstbrushside = loadmodel->brush.data_brushsides + firstside;
  4350. out->numbrushsides = numsides;
  4351. // convert the contents to our values
  4352. supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(contents);
  4353. // problem: q2bsp brushes have contents but not a texture
  4354. // problem: q2bsp brushsides *may* have a texture or may not
  4355. // problem: all brushsides and brushes must have a texture for trace_hittexture functionality to work, and the collision code is engineered around this assumption
  4356. // solution: nasty hacks
  4357. brushmissingtextures = false;
  4358. out->texture = NULL;
  4359. for (j = 0; j < out->numbrushsides; j++)
  4360. {
  4361. if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
  4362. brushmissingtextures = true;
  4363. else
  4364. {
  4365. // if we can find a matching texture on a brush side we can use it instead of creating one
  4366. if (out->firstbrushside[j].texture->supercontents == supercontents)
  4367. out->texture = out->firstbrushside[j].texture;
  4368. }
  4369. }
  4370. if (brushmissingtextures || out->texture == NULL)
  4371. {
  4372. numbrushesmissingtextures++;
  4373. // if we didn't find any appropriate texture (matching contents), we'll have to create one
  4374. // we could search earlier ones for a matching one but that can be slow
  4375. if (out->texture == NULL)
  4376. {
  4377. texture_t *validtexture;
  4378. validtexture = (texture_t *)Mem_Alloc(loadmodel->mempool, sizeof(texture_t));
  4379. dpsnprintf(validtexture->name, sizeof(validtexture->name), "brushcollision%i", numcreatedtextures);
  4380. validtexture->surfaceflags = 0;
  4381. validtexture->supercontents = supercontents;
  4382. numcreatedtextures++;
  4383. out->texture = validtexture;
  4384. }
  4385. // out->texture now contains a texture with appropriate contents, copy onto any missing sides
  4386. for (j = 0; j < out->numbrushsides; j++)
  4387. if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
  4388. out->firstbrushside[j].texture = out->texture;
  4389. }
  4390. // make a colbrush from the brush
  4391. q3surfaceflags = 0;
  4392. // make a list of mplane_t structs to construct a colbrush from
  4393. if (maxplanes < out->numbrushsides)
  4394. {
  4395. maxplanes = out->numbrushsides;
  4396. if (planes)
  4397. Mem_Free(planes);
  4398. planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
  4399. }
  4400. for (j = 0;j < out->numbrushsides;j++)
  4401. {
  4402. VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
  4403. planes[j].dist = out->firstbrushside[j].plane->dist;
  4404. planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
  4405. planes[j].texture = out->firstbrushside[j].texture;
  4406. q3surfaceflags |= planes[j].q3surfaceflags;
  4407. }
  4408. out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
  4409. // this whole loop can take a while (e.g. on redstarrepublic4)
  4410. CL_KeepaliveMessage(false);
  4411. }
  4412. if (planes)
  4413. Mem_Free(planes);
  4414. if (numcreatedtextures)
  4415. Con_DPrintf("Mod_Q2BSP_LoadBrushes: %i brushes own sides that lack textures or have differing contents from the brush, %i textures have been created to describe these contents.\n", numbrushesmissingtextures, numcreatedtextures);
  4416. }
  4417. static void Mod_Q2BSP_LoadPOP(sizebuf_t *sb)
  4418. {
  4419. // this is probably a "proof of purchase" lump of some sort, it seems to be 0 size in most bsp files (but not q2dm1.bsp for instance)
  4420. sb->readcount = sb->cursize;
  4421. }
  4422. static void Mod_Q2BSP_LoadAreas(sizebuf_t *sb)
  4423. {
  4424. // we currently don't use areas, they represent closable doors as vis blockers
  4425. sb->readcount = sb->cursize;
  4426. }
  4427. static void Mod_Q2BSP_LoadAreaPortals(sizebuf_t *sb)
  4428. {
  4429. // we currently don't use areas, they represent closable doors as vis blockers
  4430. sb->readcount = sb->cursize;
  4431. }
  4432. static void Mod_Q2BSP_LoadSubmodels(sizebuf_t *sb)
  4433. {
  4434. mmodel_t *out;
  4435. int i, count;
  4436. int structsize = 48;
  4437. if (sb->cursize % structsize)
  4438. Host_Error ("Mod_Q2BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
  4439. count = sb->cursize / structsize;
  4440. out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
  4441. loadmodel->brushq1.submodels = out;
  4442. loadmodel->brush.numsubmodels = count;
  4443. // this is identical to the q1 submodel structure except for having 1 hull
  4444. for (i = 0; i < count; i++, out++)
  4445. {
  4446. // spread out the mins / maxs by a pixel
  4447. out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
  4448. out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
  4449. out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
  4450. out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
  4451. out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
  4452. out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
  4453. out->origin[0] = MSG_ReadLittleFloat(sb);
  4454. out->origin[1] = MSG_ReadLittleFloat(sb);
  4455. out->origin[2] = MSG_ReadLittleFloat(sb);
  4456. out->headnode[0] = MSG_ReadLittleLong(sb);
  4457. out->firstface = MSG_ReadLittleLong(sb);
  4458. out->numfaces = MSG_ReadLittleLong(sb);
  4459. }
  4460. }
  4461. static void Mod_Q2BSP_FindSubmodelBrushRange_r(dp_model_t *mod, mnode_t *node, int *first, int *last)
  4462. {
  4463. int i;
  4464. mleaf_t *leaf;
  4465. while (node->plane)
  4466. {
  4467. Mod_Q2BSP_FindSubmodelBrushRange_r(mod, node->children[0], first, last);
  4468. node = node->children[1];
  4469. }
  4470. leaf = (mleaf_t*)node;
  4471. for (i = 0;i < leaf->numleafbrushes;i++)
  4472. {
  4473. int brushnum = leaf->firstleafbrush[i];
  4474. if (*first > brushnum)
  4475. *first = brushnum;
  4476. if (*last < brushnum)
  4477. *last = brushnum;
  4478. }
  4479. }
  4480. static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
  4481. {
  4482. int i, j, k;
  4483. sizebuf_t lumpsb[Q2HEADER_LUMPS];
  4484. mmodel_t *bm;
  4485. float dist, modelyawradius, modelradius;
  4486. msurface_t *surface;
  4487. int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
  4488. model_brush_lightstyleinfo_t styleinfo[256];
  4489. unsigned char *datapointer;
  4490. sizebuf_t sb;
  4491. MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
  4492. mod->type = mod_brushq2;
  4493. mod->brush.ishlbsp = false;
  4494. mod->brush.isbsp2rmqe = false;
  4495. mod->brush.isbsp2 = false;
  4496. mod->brush.isq2bsp = true; // q1bsp loaders mostly work but we need a few tweaks
  4497. mod->brush.isq3bsp = false;
  4498. mod->brush.skymasking = true;
  4499. mod->modeldatatypestring = "Q2BSP";
  4500. i = MSG_ReadLittleLong(&sb);
  4501. if (i != Q2BSPMAGIC)
  4502. Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
  4503. i = MSG_ReadLittleLong(&sb);
  4504. if (i != Q2BSPVERSION)
  4505. Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
  4506. // read lumps
  4507. for (i = 0; i < Q2HEADER_LUMPS; i++)
  4508. {
  4509. int offset = MSG_ReadLittleLong(&sb);
  4510. int size = MSG_ReadLittleLong(&sb);
  4511. if (offset < 0 || offset + size > sb.cursize)
  4512. Host_Error("Mod_Q2BSP_Load: %s has invalid lump %i (offset %i, size %i, file size %i)\n", mod->name, i, offset, size, (int)sb.cursize);
  4513. MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
  4514. }
  4515. mod->soundfromcenter = true;
  4516. mod->TracePoint = Mod_CollisionBIH_TracePoint;
  4517. mod->TraceLine = Mod_CollisionBIH_TraceLine;
  4518. mod->TraceBox = Mod_CollisionBIH_TraceBox;
  4519. mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
  4520. mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
  4521. mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
  4522. mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
  4523. mod->brush.SuperContentsFromNativeContents = Mod_Q2BSP_SuperContentsFromNativeContents;
  4524. mod->brush.NativeContentsFromSuperContents = Mod_Q2BSP_NativeContentsFromSuperContents;
  4525. mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
  4526. mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
  4527. mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
  4528. mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
  4529. mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
  4530. mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
  4531. mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
  4532. mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
  4533. mod->brush.AmbientSoundLevelsForPoint = NULL;
  4534. mod->brush.RoundUpToHullSize = NULL;
  4535. mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
  4536. mod->Draw = R_Q1BSP_Draw;
  4537. mod->DrawDepth = R_Q1BSP_DrawDepth;
  4538. mod->DrawDebug = R_Q1BSP_DrawDebug;
  4539. mod->DrawPrepass = R_Q1BSP_DrawPrepass;
  4540. mod->GetLightInfo = R_Q1BSP_GetLightInfo;
  4541. mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
  4542. mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
  4543. mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
  4544. mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
  4545. mod->DrawLight = R_Q1BSP_DrawLight;
  4546. // load into heap
  4547. mod->brush.qw_md4sum = 0;
  4548. mod->brush.qw_md4sum2 = 0;
  4549. for (i = 0;i < Q2HEADER_LUMPS;i++)
  4550. {
  4551. int temp;
  4552. if (i == Q2LUMP_ENTITIES)
  4553. continue;
  4554. temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
  4555. mod->brush.qw_md4sum ^= LittleLong(temp);
  4556. if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
  4557. continue;
  4558. mod->brush.qw_md4sum2 ^= LittleLong(temp);
  4559. }
  4560. // many of these functions are identical to Q1 loaders, so we use those where possible
  4561. Mod_Q1BSP_LoadEntities(&lumpsb[Q2LUMP_ENTITIES]);
  4562. Mod_Q1BSP_LoadVertexes(&lumpsb[Q2LUMP_VERTEXES]);
  4563. Mod_Q1BSP_LoadEdges(&lumpsb[Q2LUMP_EDGES]);
  4564. Mod_Q1BSP_LoadSurfedges(&lumpsb[Q2LUMP_SURFEDGES]);
  4565. Mod_Q2BSP_LoadLighting(&lumpsb[Q2LUMP_LIGHTING]);
  4566. Mod_Q1BSP_LoadPlanes(&lumpsb[Q2LUMP_PLANES]);
  4567. Mod_Q2BSP_LoadTexinfo(&lumpsb[Q2LUMP_TEXINFO]);
  4568. Mod_Q2BSP_LoadBrushSides(&lumpsb[Q2LUMP_BRUSHSIDES]);
  4569. Mod_Q2BSP_LoadBrushes(&lumpsb[Q2LUMP_BRUSHES]);
  4570. Mod_Q1BSP_LoadFaces(&lumpsb[Q2LUMP_FACES]);
  4571. Mod_Q1BSP_LoadLeaffaces(&lumpsb[Q2LUMP_LEAFFACES]);
  4572. Mod_Q2BSP_LoadLeafBrushes(&lumpsb[Q2LUMP_LEAFBRUSHES]);
  4573. Mod_Q2BSP_LoadVisibility(&lumpsb[Q2LUMP_VISIBILITY]);
  4574. Mod_Q2BSP_LoadPOP(&lumpsb[Q2LUMP_POP]);
  4575. Mod_Q2BSP_LoadAreas(&lumpsb[Q2LUMP_AREAS]);
  4576. Mod_Q2BSP_LoadAreaPortals(&lumpsb[Q2LUMP_AREAPORTALS]);
  4577. Mod_Q2BSP_LoadLeafs(&lumpsb[Q2LUMP_LEAFS]);
  4578. Mod_Q2BSP_LoadNodes(&lumpsb[Q2LUMP_NODES]);
  4579. Mod_Q2BSP_LoadSubmodels(&lumpsb[Q2LUMP_MODELS]);
  4580. for (i = 0; i < Q2HEADER_LUMPS; i++)
  4581. if (lumpsb[i].readcount != lumpsb[i].cursize)
  4582. Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
  4583. // we don't actually set MATERIALFLAG_WATERALPHA on anything, so this
  4584. // doesn't enable the cvar, just indicates that transparent water is OK
  4585. loadmodel->brush.supportwateralpha = true;
  4586. // we don't need the compressed pvs data anymore
  4587. if (mod->brushq1.data_compressedpvs)
  4588. Mem_Free(mod->brushq1.data_compressedpvs);
  4589. mod->brushq1.data_compressedpvs = NULL;
  4590. mod->brushq1.num_compressedpvs = 0;
  4591. // the MakePortals code works fine on the q2bsp data as well
  4592. if (mod_bsp_portalize.integer)
  4593. Mod_Q1BSP_MakePortals();
  4594. mod->numframes = 0; // q2bsp animations are kind of special, frame is unbounded...
  4595. mod->numskins = 1;
  4596. // make a single combined shadow mesh to allow optimized shadow volume creation
  4597. Mod_Q1BSP_CreateShadowMesh(loadmodel);
  4598. if (loadmodel->brush.numsubmodels)
  4599. loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
  4600. totalstylesurfaces = 0;
  4601. totalstyles = 0;
  4602. for (i = 0;i < mod->brush.numsubmodels;i++)
  4603. {
  4604. memset(stylecounts, 0, sizeof(stylecounts));
  4605. for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
  4606. {
  4607. surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
  4608. for (j = 0;j < MAXLIGHTMAPS;j++)
  4609. stylecounts[surface->lightmapinfo->styles[j]]++;
  4610. }
  4611. for (k = 0;k < 255;k++)
  4612. {
  4613. totalstyles++;
  4614. if (stylecounts[k])
  4615. totalstylesurfaces += stylecounts[k];
  4616. }
  4617. }
  4618. datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
  4619. // set up the world model, then on each submodel copy from the world model
  4620. // and set up the submodel with the respective model info.
  4621. mod = loadmodel;
  4622. for (i = 0;i < loadmodel->brush.numsubmodels;i++)
  4623. {
  4624. mnode_t *rootnode = NULL;
  4625. int firstbrush = loadmodel->brush.num_brushes, lastbrush = 0;
  4626. if (i > 0)
  4627. {
  4628. char name[10];
  4629. // duplicate the basic information
  4630. dpsnprintf(name, sizeof(name), "*%i", i);
  4631. mod = Mod_FindName(name, loadmodel->name);
  4632. // copy the base model to this one
  4633. *mod = *loadmodel;
  4634. // rename the clone back to its proper name
  4635. strlcpy(mod->name, name, sizeof(mod->name));
  4636. mod->brush.parentmodel = loadmodel;
  4637. // textures and memory belong to the main model
  4638. mod->texturepool = NULL;
  4639. mod->mempool = NULL;
  4640. mod->brush.GetPVS = NULL;
  4641. mod->brush.FatPVS = NULL;
  4642. mod->brush.BoxTouchingPVS = NULL;
  4643. mod->brush.BoxTouchingLeafPVS = NULL;
  4644. mod->brush.BoxTouchingVisibleLeafs = NULL;
  4645. mod->brush.FindBoxClusters = NULL;
  4646. mod->brush.LightPoint = NULL;
  4647. mod->brush.AmbientSoundLevelsForPoint = NULL;
  4648. }
  4649. mod->brush.submodel = i;
  4650. if (loadmodel->brush.submodels)
  4651. loadmodel->brush.submodels[i] = mod;
  4652. bm = &mod->brushq1.submodels[i];
  4653. // we store the headnode (there's only one in Q2BSP) as if it were the first hull
  4654. mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
  4655. mod->firstmodelsurface = bm->firstface;
  4656. mod->nummodelsurfaces = bm->numfaces;
  4657. // set node/leaf parents for this submodel
  4658. // note: if the root of this submodel is a leaf (headnode[0] < 0) then there is nothing to do...
  4659. // (this happens in base3.bsp)
  4660. if (bm->headnode[0] >= 0)
  4661. rootnode = mod->brush.data_nodes + bm->headnode[0];
  4662. else
  4663. rootnode = (mnode_t*)(mod->brush.data_leafs + -1 - bm->headnode[0]);
  4664. Mod_Q1BSP_LoadNodes_RecursiveSetParent(rootnode, NULL);
  4665. // make the model surface list (used by shadowing/lighting)
  4666. mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
  4667. Mod_Q2BSP_FindSubmodelBrushRange_r(mod, rootnode, &firstbrush, &lastbrush);
  4668. if (firstbrush <= lastbrush)
  4669. {
  4670. mod->firstmodelbrush = firstbrush;
  4671. mod->nummodelbrushes = lastbrush + 1 - firstbrush;
  4672. }
  4673. else
  4674. {
  4675. mod->firstmodelbrush = 0;
  4676. mod->nummodelbrushes = 0;
  4677. }
  4678. Mod_MakeSortedSurfaces(mod);
  4679. VectorCopy(bm->mins, mod->normalmins);
  4680. VectorCopy(bm->maxs, mod->normalmaxs);
  4681. dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
  4682. modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
  4683. modelyawradius = dist*dist+modelyawradius*modelyawradius;
  4684. modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
  4685. modelradius = modelyawradius + modelradius * modelradius;
  4686. modelyawradius = sqrt(modelyawradius);
  4687. modelradius = sqrt(modelradius);
  4688. mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
  4689. mod->yawmins[2] = mod->normalmins[2];
  4690. mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
  4691. mod->yawmaxs[2] = mod->normalmaxs[2];
  4692. mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
  4693. mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
  4694. mod->radius = modelradius;
  4695. mod->radius2 = modelradius * modelradius;
  4696. // this gets altered below if sky or water is used
  4697. mod->DrawSky = NULL;
  4698. mod->DrawAddWaterPlanes = NULL;
  4699. // scan surfaces for sky and water and flag the submodel as possessing these features or not
  4700. // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
  4701. if (mod->nummodelsurfaces)
  4702. {
  4703. for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
  4704. if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
  4705. break;
  4706. if (j < mod->nummodelsurfaces)
  4707. mod->DrawSky = R_Q1BSP_DrawSky;
  4708. for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
  4709. if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
  4710. break;
  4711. if (j < mod->nummodelsurfaces)
  4712. mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
  4713. // build lightstyle update chains
  4714. // (used to rapidly mark lightmapupdateflags on many surfaces
  4715. // when d_lightstylevalue changes)
  4716. memset(stylecounts, 0, sizeof(stylecounts));
  4717. for (k = 0;k < mod->nummodelsurfaces;k++)
  4718. {
  4719. surface = mod->data_surfaces + mod->firstmodelsurface + k;
  4720. for (j = 0;j < MAXLIGHTMAPS;j++)
  4721. stylecounts[surface->lightmapinfo->styles[j]]++;
  4722. }
  4723. mod->brushq1.num_lightstyles = 0;
  4724. for (k = 0;k < 255;k++)
  4725. {
  4726. if (stylecounts[k])
  4727. {
  4728. styleinfo[mod->brushq1.num_lightstyles].style = k;
  4729. styleinfo[mod->brushq1.num_lightstyles].value = 0;
  4730. styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
  4731. styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
  4732. remapstyles[k] = mod->brushq1.num_lightstyles;
  4733. mod->brushq1.num_lightstyles++;
  4734. }
  4735. }
  4736. for (k = 0;k < mod->nummodelsurfaces;k++)
  4737. {
  4738. surface = mod->data_surfaces + mod->firstmodelsurface + k;
  4739. for (j = 0;j < MAXLIGHTMAPS;j++)
  4740. {
  4741. if (surface->lightmapinfo->styles[j] != 255)
  4742. {
  4743. int r = remapstyles[surface->lightmapinfo->styles[j]];
  4744. styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
  4745. }
  4746. }
  4747. }
  4748. mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
  4749. memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
  4750. }
  4751. else
  4752. {
  4753. Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
  4754. }
  4755. //mod->brushq1.num_visleafs = bm->visleafs;
  4756. // build a Bounding Interval Hierarchy for culling triangles in light rendering
  4757. Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
  4758. // build a Bounding Interval Hierarchy for culling brushes in collision detection
  4759. Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
  4760. // generate VBOs and other shared data before cloning submodels
  4761. if (i == 0)
  4762. Mod_BuildVBOs();
  4763. }
  4764. mod = loadmodel;
  4765. Con_DPrintf("Stats for q2bsp model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
  4766. }
  4767. static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents);
  4768. static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents);
  4769. static void Mod_Q3BSP_LoadEntities(lump_t *l)
  4770. {
  4771. const char *data;
  4772. char key[128], value[MAX_INPUTLINE];
  4773. float v[3];
  4774. loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
  4775. loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
  4776. loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
  4777. if (!l->filelen)
  4778. return;
  4779. loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
  4780. memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
  4781. loadmodel->brush.entities[l->filelen] = 0;
  4782. data = loadmodel->brush.entities;
  4783. // some Q3 maps override the lightgrid_cellsize with a worldspawn key
  4784. // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
  4785. loadmodel->brushq3.deluxemapping = false;
  4786. if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
  4787. {
  4788. while (1)
  4789. {
  4790. if (!COM_ParseToken_Simple(&data, false, false, true))
  4791. break; // error
  4792. if (com_token[0] == '}')
  4793. break; // end of worldspawn
  4794. if (com_token[0] == '_')
  4795. strlcpy(key, com_token + 1, sizeof(key));
  4796. else
  4797. strlcpy(key, com_token, sizeof(key));
  4798. while (key[strlen(key)-1] == ' ') // remove trailing spaces
  4799. key[strlen(key)-1] = 0;
  4800. if (!COM_ParseToken_Simple(&data, false, false, true))
  4801. break; // error
  4802. strlcpy(value, com_token, sizeof(value));
  4803. if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
  4804. {
  4805. #if _MSC_VER >= 1400
  4806. #define sscanf sscanf_s
  4807. #endif
  4808. #if 0
  4809. if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
  4810. VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
  4811. #else
  4812. VectorSet(v, 64, 64, 128);
  4813. if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
  4814. Con_Printf("Mod_Q3BSP_LoadEntities: funny gridsize \"%s\" in %s, interpreting as \"%f %f %f\" to match q3map2's parsing\n", value, loadmodel->name, v[0], v[1], v[2]);
  4815. if (v[0] != 0 && v[1] != 0 && v[2] != 0)
  4816. VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
  4817. #endif
  4818. }
  4819. else if (!strcmp("deluxeMaps", key))
  4820. {
  4821. if (!strcmp(com_token, "1"))
  4822. {
  4823. loadmodel->brushq3.deluxemapping = true;
  4824. loadmodel->brushq3.deluxemapping_modelspace = true;
  4825. }
  4826. else if (!strcmp(com_token, "2"))
  4827. {
  4828. loadmodel->brushq3.deluxemapping = true;
  4829. loadmodel->brushq3.deluxemapping_modelspace = false;
  4830. }
  4831. }
  4832. }
  4833. }
  4834. }
  4835. static void Mod_Q3BSP_LoadTextures(lump_t *l)
  4836. {
  4837. q3dtexture_t *in;
  4838. texture_t *out;
  4839. int i, count;
  4840. in = (q3dtexture_t *)(mod_base + l->fileofs);
  4841. if (l->filelen % sizeof(*in))
  4842. Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
  4843. count = l->filelen / sizeof(*in);
  4844. out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  4845. loadmodel->data_textures = out;
  4846. loadmodel->num_textures = count;
  4847. loadmodel->num_texturesperskin = loadmodel->num_textures;
  4848. for (i = 0;i < count;i++)
  4849. {
  4850. out[i].surfaceflags = LittleLong(in[i].surfaceflags);
  4851. out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
  4852. Mod_LoadTextureFromQ3Shader(out + i, in[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
  4853. // restore the surfaceflags and supercontents
  4854. out[i].surfaceflags = LittleLong(in[i].surfaceflags);
  4855. out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
  4856. }
  4857. }
  4858. static void Mod_Q3BSP_LoadPlanes(lump_t *l)
  4859. {
  4860. q3dplane_t *in;
  4861. mplane_t *out;
  4862. int i, count;
  4863. in = (q3dplane_t *)(mod_base + l->fileofs);
  4864. if (l->filelen % sizeof(*in))
  4865. Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
  4866. count = l->filelen / sizeof(*in);
  4867. out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  4868. loadmodel->brush.data_planes = out;
  4869. loadmodel->brush.num_planes = count;
  4870. for (i = 0;i < count;i++, in++, out++)
  4871. {
  4872. out->normal[0] = LittleFloat(in->normal[0]);
  4873. out->normal[1] = LittleFloat(in->normal[1]);
  4874. out->normal[2] = LittleFloat(in->normal[2]);
  4875. out->dist = LittleFloat(in->dist);
  4876. PlaneClassify(out);
  4877. }
  4878. }
  4879. static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
  4880. {
  4881. q3dbrushside_t *in;
  4882. q3mbrushside_t *out;
  4883. int i, n, count;
  4884. in = (q3dbrushside_t *)(mod_base + l->fileofs);
  4885. if (l->filelen % sizeof(*in))
  4886. Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
  4887. count = l->filelen / sizeof(*in);
  4888. out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  4889. loadmodel->brush.data_brushsides = out;
  4890. loadmodel->brush.num_brushsides = count;
  4891. for (i = 0;i < count;i++, in++, out++)
  4892. {
  4893. n = LittleLong(in->planeindex);
  4894. if (n < 0 || n >= loadmodel->brush.num_planes)
  4895. Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
  4896. out->plane = loadmodel->brush.data_planes + n;
  4897. n = LittleLong(in->textureindex);
  4898. if (n < 0 || n >= loadmodel->num_textures)
  4899. Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
  4900. out->texture = loadmodel->data_textures + n;
  4901. }
  4902. }
  4903. static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
  4904. {
  4905. q3dbrushside_ig_t *in;
  4906. q3mbrushside_t *out;
  4907. int i, n, count;
  4908. in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
  4909. if (l->filelen % sizeof(*in))
  4910. Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
  4911. count = l->filelen / sizeof(*in);
  4912. out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  4913. loadmodel->brush.data_brushsides = out;
  4914. loadmodel->brush.num_brushsides = count;
  4915. for (i = 0;i < count;i++, in++, out++)
  4916. {
  4917. n = LittleLong(in->planeindex);
  4918. if (n < 0 || n >= loadmodel->brush.num_planes)
  4919. Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
  4920. out->plane = loadmodel->brush.data_planes + n;
  4921. n = LittleLong(in->textureindex);
  4922. if (n < 0 || n >= loadmodel->num_textures)
  4923. Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
  4924. out->texture = loadmodel->data_textures + n;
  4925. }
  4926. }
  4927. static void Mod_Q3BSP_LoadBrushes(lump_t *l)
  4928. {
  4929. q3dbrush_t *in;
  4930. q3mbrush_t *out;
  4931. int i, j, n, c, count, maxplanes, q3surfaceflags;
  4932. colplanef_t *planes;
  4933. in = (q3dbrush_t *)(mod_base + l->fileofs);
  4934. if (l->filelen % sizeof(*in))
  4935. Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
  4936. count = l->filelen / sizeof(*in);
  4937. out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  4938. loadmodel->brush.data_brushes = out;
  4939. loadmodel->brush.num_brushes = count;
  4940. maxplanes = 0;
  4941. planes = NULL;
  4942. for (i = 0;i < count;i++, in++, out++)
  4943. {
  4944. n = LittleLong(in->firstbrushside);
  4945. c = LittleLong(in->numbrushsides);
  4946. if (n < 0 || n + c > loadmodel->brush.num_brushsides)
  4947. Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
  4948. out->firstbrushside = loadmodel->brush.data_brushsides + n;
  4949. out->numbrushsides = c;
  4950. n = LittleLong(in->textureindex);
  4951. if (n < 0 || n >= loadmodel->num_textures)
  4952. Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
  4953. out->texture = loadmodel->data_textures + n;
  4954. // make a list of mplane_t structs to construct a colbrush from
  4955. if (maxplanes < out->numbrushsides)
  4956. {
  4957. maxplanes = out->numbrushsides;
  4958. if (planes)
  4959. Mem_Free(planes);
  4960. planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
  4961. }
  4962. q3surfaceflags = 0;
  4963. for (j = 0;j < out->numbrushsides;j++)
  4964. {
  4965. VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
  4966. planes[j].dist = out->firstbrushside[j].plane->dist;
  4967. planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
  4968. planes[j].texture = out->firstbrushside[j].texture;
  4969. q3surfaceflags |= planes[j].q3surfaceflags;
  4970. }
  4971. // make the colbrush from the planes
  4972. out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
  4973. // this whole loop can take a while (e.g. on redstarrepublic4)
  4974. CL_KeepaliveMessage(false);
  4975. }
  4976. if (planes)
  4977. Mem_Free(planes);
  4978. }
  4979. static void Mod_Q3BSP_LoadEffects(lump_t *l)
  4980. {
  4981. q3deffect_t *in;
  4982. q3deffect_t *out;
  4983. int i, n, count;
  4984. in = (q3deffect_t *)(mod_base + l->fileofs);
  4985. if (l->filelen % sizeof(*in))
  4986. Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
  4987. count = l->filelen / sizeof(*in);
  4988. out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  4989. loadmodel->brushq3.data_effects = out;
  4990. loadmodel->brushq3.num_effects = count;
  4991. for (i = 0;i < count;i++, in++, out++)
  4992. {
  4993. strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
  4994. n = LittleLong(in->brushindex);
  4995. if (n >= loadmodel->brush.num_brushes)
  4996. {
  4997. Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
  4998. n = -1;
  4999. }
  5000. out->brushindex = n;
  5001. out->unknown = LittleLong(in->unknown);
  5002. }
  5003. }
  5004. static void Mod_Q3BSP_LoadVertices(lump_t *l)
  5005. {
  5006. q3dvertex_t *in;
  5007. int i, count;
  5008. in = (q3dvertex_t *)(mod_base + l->fileofs);
  5009. if (l->filelen % sizeof(*in))
  5010. Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
  5011. loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
  5012. loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
  5013. loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
  5014. loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
  5015. loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
  5016. loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
  5017. for (i = 0;i < count;i++, in++)
  5018. {
  5019. loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
  5020. loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
  5021. loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
  5022. loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
  5023. loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
  5024. loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
  5025. loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
  5026. loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
  5027. loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
  5028. loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
  5029. // svector/tvector are calculated later in face loading
  5030. if(mod_q3bsp_sRGBlightmaps.integer)
  5031. {
  5032. // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
  5033. // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
  5034. // working like this may be odd, but matches q3map2 -gamma 2.2
  5035. if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
  5036. {
  5037. loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
  5038. loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
  5039. loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
  5040. // we fix the brightness consistently via lightmapscale
  5041. }
  5042. else
  5043. {
  5044. loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
  5045. loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
  5046. loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
  5047. }
  5048. }
  5049. else
  5050. {
  5051. if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
  5052. {
  5053. loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
  5054. loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
  5055. loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
  5056. }
  5057. else
  5058. {
  5059. loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
  5060. loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
  5061. loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
  5062. }
  5063. }
  5064. loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
  5065. if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
  5066. loadmodel->lit = true;
  5067. }
  5068. }
  5069. static void Mod_Q3BSP_LoadTriangles(lump_t *l)
  5070. {
  5071. int *in;
  5072. int *out;
  5073. int i, count;
  5074. in = (int *)(mod_base + l->fileofs);
  5075. if (l->filelen % sizeof(int[3]))
  5076. Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
  5077. count = l->filelen / sizeof(*in);
  5078. if(!loadmodel->brushq3.num_vertices)
  5079. {
  5080. if (count)
  5081. Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
  5082. loadmodel->brushq3.num_triangles = 0;
  5083. return;
  5084. }
  5085. out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  5086. loadmodel->brushq3.num_triangles = count / 3;
  5087. loadmodel->brushq3.data_element3i = out;
  5088. for (i = 0;i < count;i++, in++, out++)
  5089. {
  5090. *out = LittleLong(*in);
  5091. if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
  5092. {
  5093. Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
  5094. *out = 0;
  5095. }
  5096. }
  5097. }
  5098. static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
  5099. {
  5100. q3dlightmap_t *input_pointer;
  5101. int i;
  5102. int j;
  5103. int k;
  5104. int count;
  5105. int powerx;
  5106. int powery;
  5107. int powerxy;
  5108. int powerdxy;
  5109. int endlightmap;
  5110. int mergegoal;
  5111. int lightmapindex;
  5112. int realcount;
  5113. int realindex;
  5114. int mergedwidth;
  5115. int mergedheight;
  5116. int mergedcolumns;
  5117. int mergedrows;
  5118. int mergedrowsxcolumns;
  5119. int size;
  5120. int bytesperpixel;
  5121. int rgbmap[3];
  5122. unsigned char *c;
  5123. unsigned char *mergedpixels;
  5124. unsigned char *mergeddeluxepixels;
  5125. unsigned char *mergebuf;
  5126. char mapname[MAX_QPATH];
  5127. qboolean external;
  5128. unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
  5129. char vabuf[1024];
  5130. // defaults for q3bsp
  5131. size = 128;
  5132. bytesperpixel = 3;
  5133. rgbmap[0] = 2;
  5134. rgbmap[1] = 1;
  5135. rgbmap[2] = 0;
  5136. external = false;
  5137. loadmodel->brushq3.lightmapsize = 128;
  5138. if (cls.state == ca_dedicated)
  5139. return;
  5140. if(mod_q3bsp_nolightmaps.integer)
  5141. {
  5142. return;
  5143. }
  5144. else if(l->filelen)
  5145. {
  5146. // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
  5147. if (developer_loading.integer)
  5148. Con_Printf("Using internal lightmaps\n");
  5149. input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
  5150. if (l->filelen % sizeof(*input_pointer))
  5151. Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
  5152. count = l->filelen / sizeof(*input_pointer);
  5153. for(i = 0; i < count; ++i)
  5154. inpixels[i] = input_pointer[i].rgb;
  5155. }
  5156. else
  5157. {
  5158. // no internal lightmaps
  5159. // try external lightmaps
  5160. if (developer_loading.integer)
  5161. Con_Printf("Using external lightmaps\n");
  5162. FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
  5163. inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
  5164. if(!inpixels[0])
  5165. return;
  5166. // using EXTERNAL lightmaps instead
  5167. if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
  5168. {
  5169. Mem_Free(inpixels[0]);
  5170. Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
  5171. }
  5172. size = image_width;
  5173. bytesperpixel = 4;
  5174. rgbmap[0] = 0;
  5175. rgbmap[1] = 1;
  5176. rgbmap[2] = 2;
  5177. external = true;
  5178. for(count = 1; ; ++count)
  5179. {
  5180. inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
  5181. if(!inpixels[count])
  5182. break; // we got all of them
  5183. if(image_width != size || image_height != size)
  5184. {
  5185. Mem_Free(inpixels[count]);
  5186. inpixels[count] = NULL;
  5187. Con_Printf("Mod_Q3BSP_LoadLightmaps: mismatched lightmap size in %s - external lightmap %s/lm_%04d does not match earlier ones\n", loadmodel->name, mapname, count);
  5188. break;
  5189. }
  5190. }
  5191. }
  5192. loadmodel->brushq3.lightmapsize = size;
  5193. loadmodel->brushq3.num_originallightmaps = count;
  5194. // now check the surfaces to see if any of them index an odd numbered
  5195. // lightmap, if so this is not a deluxemapped bsp file
  5196. //
  5197. // also check what lightmaps are actually used, because q3map2 sometimes
  5198. // (always?) makes an unused one at the end, which
  5199. // q3map2 sometimes (or always?) makes a second blank lightmap for no
  5200. // reason when only one lightmap is used, which can throw off the
  5201. // deluxemapping detection method, so check 2-lightmap bsp's specifically
  5202. // to see if the second lightmap is blank, if so it is not deluxemapped.
  5203. // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
  5204. // in Mod_Q3BSP_LoadEntities was failed
  5205. if (!loadmodel->brushq3.deluxemapping)
  5206. {
  5207. loadmodel->brushq3.deluxemapping = !(count & 1);
  5208. loadmodel->brushq3.deluxemapping_modelspace = true;
  5209. endlightmap = 0;
  5210. if (loadmodel->brushq3.deluxemapping)
  5211. {
  5212. int facecount = faceslump->filelen / sizeof(q3dface_t);
  5213. q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
  5214. for (i = 0;i < facecount;i++)
  5215. {
  5216. j = LittleLong(faces[i].lightmapindex);
  5217. if (j >= 0)
  5218. {
  5219. endlightmap = max(endlightmap, j + 1);
  5220. if ((j & 1) || j + 1 >= count)
  5221. {
  5222. loadmodel->brushq3.deluxemapping = false;
  5223. break;
  5224. }
  5225. }
  5226. }
  5227. }
  5228. // q3map2 sometimes (or always?) makes a second blank lightmap for no
  5229. // reason when only one lightmap is used, which can throw off the
  5230. // deluxemapping detection method, so check 2-lightmap bsp's specifically
  5231. // to see if the second lightmap is blank, if so it is not deluxemapped.
  5232. //
  5233. // further research has shown q3map2 sometimes creates a deluxemap and two
  5234. // blank lightmaps, which must be handled properly as well
  5235. if (endlightmap == 1 && count > 1)
  5236. {
  5237. c = inpixels[1];
  5238. for (i = 0;i < size*size;i++)
  5239. {
  5240. if (c[bytesperpixel*i + rgbmap[0]])
  5241. break;
  5242. if (c[bytesperpixel*i + rgbmap[1]])
  5243. break;
  5244. if (c[bytesperpixel*i + rgbmap[2]])
  5245. break;
  5246. }
  5247. if (i == size*size)
  5248. {
  5249. // all pixels in the unused lightmap were black...
  5250. loadmodel->brushq3.deluxemapping = false;
  5251. }
  5252. }
  5253. }
  5254. Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
  5255. // figure out what the most reasonable merge power is within limits
  5256. // find the appropriate NxN dimensions to merge to, to avoid wasted space
  5257. realcount = count >> (int)loadmodel->brushq3.deluxemapping;
  5258. // figure out how big the merged texture has to be
  5259. mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
  5260. mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
  5261. while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
  5262. mergegoal /= 2;
  5263. mergedwidth = mergegoal;
  5264. mergedheight = mergegoal;
  5265. // choose non-square size (2x1 aspect) if only half the space is used;
  5266. // this really only happens when the entire set fits in one texture, if
  5267. // there are multiple textures, we don't worry about shrinking the last
  5268. // one to fit, because the driver prefers the same texture size on
  5269. // consecutive draw calls...
  5270. if (mergedwidth * mergedheight / 2 >= size*size*realcount)
  5271. mergedheight /= 2;
  5272. loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
  5273. loadmodel->brushq3.num_lightmapmergedheightpower = 0;
  5274. while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
  5275. loadmodel->brushq3.num_lightmapmergedwidthpower++;
  5276. while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
  5277. loadmodel->brushq3.num_lightmapmergedheightpower++;
  5278. loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
  5279. powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
  5280. powery = loadmodel->brushq3.num_lightmapmergedheightpower;
  5281. powerxy = powerx+powery;
  5282. powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
  5283. mergedcolumns = 1 << powerx;
  5284. mergedrows = 1 << powery;
  5285. mergedrowsxcolumns = 1 << powerxy;
  5286. loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
  5287. loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
  5288. if (loadmodel->brushq3.deluxemapping)
  5289. loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
  5290. // allocate a texture pool if we need it
  5291. if (loadmodel->texturepool == NULL)
  5292. loadmodel->texturepool = R_AllocTexturePool();
  5293. mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
  5294. mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
  5295. for (i = 0;i < count;i++)
  5296. {
  5297. // figure out which merged lightmap texture this fits into
  5298. realindex = i >> (int)loadmodel->brushq3.deluxemapping;
  5299. lightmapindex = i >> powerdxy;
  5300. // choose the destination address
  5301. mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
  5302. mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
  5303. if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
  5304. Con_DPrintf("copying original lightmap %i (%ix%i) to %i (at %i,%i)\n", i, size, size, lightmapindex, (realindex & (mergedcolumns-1))*size, ((realindex >> powerx) & (mergedrows-1))*size);
  5305. // convert pixels from RGB or BGRA while copying them into the destination rectangle
  5306. for (j = 0;j < size;j++)
  5307. for (k = 0;k < size;k++)
  5308. {
  5309. mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
  5310. mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
  5311. mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
  5312. mergebuf[(j*mergedwidth+k)*4+3] = 255;
  5313. }
  5314. // upload texture if this was the last tile being written to the texture
  5315. if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
  5316. {
  5317. if (loadmodel->brushq3.deluxemapping && (i & 1))
  5318. loadmodel->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%04i", lightmapindex), mergedwidth, mergedheight, mergeddeluxepixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bspdeluxemaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
  5319. else
  5320. {
  5321. if(mod_q3bsp_sRGBlightmaps.integer)
  5322. {
  5323. textype_t t;
  5324. if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
  5325. {
  5326. t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
  5327. // we fix the brightness consistently via lightmapscale
  5328. }
  5329. else
  5330. t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
  5331. loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, t, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
  5332. }
  5333. else
  5334. {
  5335. if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
  5336. Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
  5337. loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
  5338. }
  5339. }
  5340. }
  5341. }
  5342. if (mergeddeluxepixels)
  5343. Mem_Free(mergeddeluxepixels);
  5344. Mem_Free(mergedpixels);
  5345. if(external)
  5346. {
  5347. for(i = 0; i < count; ++i)
  5348. Mem_Free(inpixels[i]);
  5349. }
  5350. }
  5351. static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
  5352. {
  5353. int j, k, cnt, tri;
  5354. float *mins, *maxs;
  5355. const float *vert;
  5356. *collisionstride = stride;
  5357. if(stride > 0)
  5358. {
  5359. cnt = (num_triangles + stride - 1) / stride;
  5360. *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
  5361. for(j = 0; j < cnt; ++j)
  5362. {
  5363. mins = &((*collisionbbox6f)[6 * j + 0]);
  5364. maxs = &((*collisionbbox6f)[6 * j + 3]);
  5365. for(k = 0; k < stride; ++k)
  5366. {
  5367. tri = j * stride + k;
  5368. if(tri >= num_triangles)
  5369. break;
  5370. vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
  5371. if(!k || vert[0] < mins[0]) mins[0] = vert[0];
  5372. if(!k || vert[1] < mins[1]) mins[1] = vert[1];
  5373. if(!k || vert[2] < mins[2]) mins[2] = vert[2];
  5374. if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
  5375. if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
  5376. if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
  5377. vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
  5378. if(vert[0] < mins[0]) mins[0] = vert[0];
  5379. if(vert[1] < mins[1]) mins[1] = vert[1];
  5380. if(vert[2] < mins[2]) mins[2] = vert[2];
  5381. if(vert[0] > maxs[0]) maxs[0] = vert[0];
  5382. if(vert[1] > maxs[1]) maxs[1] = vert[1];
  5383. if(vert[2] > maxs[2]) maxs[2] = vert[2];
  5384. vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
  5385. if(vert[0] < mins[0]) mins[0] = vert[0];
  5386. if(vert[1] < mins[1]) mins[1] = vert[1];
  5387. if(vert[2] < mins[2]) mins[2] = vert[2];
  5388. if(vert[0] > maxs[0]) maxs[0] = vert[0];
  5389. if(vert[1] > maxs[1]) maxs[1] = vert[1];
  5390. if(vert[2] > maxs[2]) maxs[2] = vert[2];
  5391. }
  5392. }
  5393. }
  5394. else
  5395. *collisionbbox6f = NULL;
  5396. }
  5397. typedef struct patchtess_s
  5398. {
  5399. patchinfo_t info;
  5400. // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
  5401. int surface_id;
  5402. float lodgroup[6];
  5403. float *originalvertex3f;
  5404. } patchtess_t;
  5405. #define PATCHTESS_SAME_LODGROUP(a,b) \
  5406. ( \
  5407. (a).lodgroup[0] == (b).lodgroup[0] && \
  5408. (a).lodgroup[1] == (b).lodgroup[1] && \
  5409. (a).lodgroup[2] == (b).lodgroup[2] && \
  5410. (a).lodgroup[3] == (b).lodgroup[3] && \
  5411. (a).lodgroup[4] == (b).lodgroup[4] && \
  5412. (a).lodgroup[5] == (b).lodgroup[5] \
  5413. )
  5414. static void Mod_Q3BSP_LoadFaces(lump_t *l)
  5415. {
  5416. q3dface_t *in, *oldin;
  5417. msurface_t *out, *oldout;
  5418. int i, oldi, j, n, count, invalidelements, patchsize[2], finalwidth, finalheight, xtess, ytess, finalvertices, finaltriangles, firstvertex, firstelement, type, oldnumtriangles, oldnumtriangles2, meshvertices, meshtriangles, collisionvertices, collisiontriangles, numvertices, numtriangles, cxtess, cytess;
  5419. float lightmaptcbase[2], lightmaptcscale[2];
  5420. //int *originalelement3i;
  5421. //int *originalneighbor3i;
  5422. float *originalvertex3f;
  5423. //float *originalsvector3f;
  5424. //float *originaltvector3f;
  5425. float *originalnormal3f;
  5426. float *originalcolor4f;
  5427. float *originaltexcoordtexture2f;
  5428. float *originaltexcoordlightmap2f;
  5429. float *surfacecollisionvertex3f;
  5430. int *surfacecollisionelement3i;
  5431. float *v;
  5432. patchtess_t *patchtess = NULL;
  5433. int patchtesscount = 0;
  5434. qboolean again;
  5435. in = (q3dface_t *)(mod_base + l->fileofs);
  5436. if (l->filelen % sizeof(*in))
  5437. Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
  5438. count = l->filelen / sizeof(*in);
  5439. out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  5440. loadmodel->data_surfaces = out;
  5441. loadmodel->num_surfaces = count;
  5442. if(count > 0)
  5443. patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
  5444. i = 0;
  5445. oldi = i;
  5446. oldin = in;
  5447. oldout = out;
  5448. meshvertices = 0;
  5449. meshtriangles = 0;
  5450. for (;i < count;i++, in++, out++)
  5451. {
  5452. // check face type first
  5453. type = LittleLong(in->type);
  5454. if (type != Q3FACETYPE_FLAT
  5455. && type != Q3FACETYPE_PATCH
  5456. && type != Q3FACETYPE_MESH
  5457. && type != Q3FACETYPE_FLARE)
  5458. {
  5459. Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
  5460. continue;
  5461. }
  5462. n = LittleLong(in->textureindex);
  5463. if (n < 0 || n >= loadmodel->num_textures)
  5464. {
  5465. Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
  5466. continue;
  5467. }
  5468. out->texture = loadmodel->data_textures + n;
  5469. n = LittleLong(in->effectindex);
  5470. if (n < -1 || n >= loadmodel->brushq3.num_effects)
  5471. {
  5472. if (developer_extra.integer)
  5473. Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
  5474. n = -1;
  5475. }
  5476. if (n == -1)
  5477. out->effect = NULL;
  5478. else
  5479. out->effect = loadmodel->brushq3.data_effects + n;
  5480. if (cls.state != ca_dedicated)
  5481. {
  5482. out->lightmaptexture = NULL;
  5483. out->deluxemaptexture = r_texture_blanknormalmap;
  5484. n = LittleLong(in->lightmapindex);
  5485. if (n < 0)
  5486. n = -1;
  5487. else if (n >= loadmodel->brushq3.num_originallightmaps)
  5488. {
  5489. if(loadmodel->brushq3.num_originallightmaps != 0)
  5490. Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
  5491. n = -1;
  5492. }
  5493. else
  5494. {
  5495. out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
  5496. if (loadmodel->brushq3.deluxemapping)
  5497. out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
  5498. loadmodel->lit = true;
  5499. }
  5500. }
  5501. firstvertex = LittleLong(in->firstvertex);
  5502. numvertices = LittleLong(in->numvertices);
  5503. firstelement = LittleLong(in->firstelement);
  5504. numtriangles = LittleLong(in->numelements) / 3;
  5505. if (numtriangles * 3 != LittleLong(in->numelements))
  5506. {
  5507. Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): numelements %i is not a multiple of 3\n", i, out->texture->name, LittleLong(in->numelements));
  5508. continue;
  5509. }
  5510. if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
  5511. {
  5512. Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid vertex range %i : %i (%i vertices)\n", i, out->texture->name, firstvertex, firstvertex + numvertices, loadmodel->brushq3.num_vertices);
  5513. continue;
  5514. }
  5515. if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
  5516. {
  5517. Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid element range %i : %i (%i elements)\n", i, out->texture->name, firstelement, firstelement + numtriangles * 3, loadmodel->brushq3.num_triangles * 3);
  5518. continue;
  5519. }
  5520. switch(type)
  5521. {
  5522. case Q3FACETYPE_FLAT:
  5523. case Q3FACETYPE_MESH:
  5524. // no processing necessary
  5525. break;
  5526. case Q3FACETYPE_PATCH:
  5527. patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
  5528. patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
  5529. if (numvertices != (patchsize[0] * patchsize[1]) || patchsize[0] < 3 || patchsize[1] < 3 || !(patchsize[0] & 1) || !(patchsize[1] & 1) || patchsize[0] * patchsize[1] >= min(r_subdivisions_maxvertices.integer, r_subdivisions_collision_maxvertices.integer))
  5530. {
  5531. Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
  5532. continue;
  5533. }
  5534. originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
  5535. // convert patch to Q3FACETYPE_MESH
  5536. xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
  5537. ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
  5538. // bound to user settings
  5539. xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
  5540. ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
  5541. // bound to sanity settings
  5542. xtess = bound(0, xtess, 1024);
  5543. ytess = bound(0, ytess, 1024);
  5544. // lower quality collision patches! Same procedure as before, but different cvars
  5545. // convert patch to Q3FACETYPE_MESH
  5546. cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
  5547. cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
  5548. // bound to user settings
  5549. cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
  5550. cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
  5551. // bound to sanity settings
  5552. cxtess = bound(0, cxtess, 1024);
  5553. cytess = bound(0, cytess, 1024);
  5554. // store it for the LOD grouping step
  5555. patchtess[patchtesscount].info.xsize = patchsize[0];
  5556. patchtess[patchtesscount].info.ysize = patchsize[1];
  5557. patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
  5558. patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
  5559. patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
  5560. patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
  5561. patchtess[patchtesscount].surface_id = i;
  5562. patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
  5563. patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
  5564. patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
  5565. patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
  5566. patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
  5567. patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
  5568. patchtess[patchtesscount].originalvertex3f = originalvertex3f;
  5569. ++patchtesscount;
  5570. break;
  5571. case Q3FACETYPE_FLARE:
  5572. if (developer_extra.integer)
  5573. Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
  5574. // don't render it
  5575. continue;
  5576. }
  5577. out->num_vertices = numvertices;
  5578. out->num_triangles = numtriangles;
  5579. meshvertices += out->num_vertices;
  5580. meshtriangles += out->num_triangles;
  5581. }
  5582. // Fix patches tesselations so that they make no seams
  5583. do
  5584. {
  5585. again = false;
  5586. for(i = 0; i < patchtesscount; ++i)
  5587. {
  5588. for(j = i+1; j < patchtesscount; ++j)
  5589. {
  5590. if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
  5591. continue;
  5592. if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
  5593. again = true;
  5594. }
  5595. }
  5596. }
  5597. while (again);
  5598. // Calculate resulting number of triangles
  5599. collisionvertices = 0;
  5600. collisiontriangles = 0;
  5601. for(i = 0; i < patchtesscount; ++i)
  5602. {
  5603. finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
  5604. finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
  5605. numvertices = finalwidth * finalheight;
  5606. numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
  5607. oldout[patchtess[i].surface_id].num_vertices = numvertices;
  5608. oldout[patchtess[i].surface_id].num_triangles = numtriangles;
  5609. meshvertices += oldout[patchtess[i].surface_id].num_vertices;
  5610. meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
  5611. finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
  5612. finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
  5613. numvertices = finalwidth * finalheight;
  5614. numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
  5615. oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
  5616. oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
  5617. collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
  5618. collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
  5619. }
  5620. i = oldi;
  5621. in = oldin;
  5622. out = oldout;
  5623. Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
  5624. if (collisiontriangles)
  5625. {
  5626. loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
  5627. loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
  5628. }
  5629. meshvertices = 0;
  5630. meshtriangles = 0;
  5631. collisionvertices = 0;
  5632. collisiontriangles = 0;
  5633. for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
  5634. {
  5635. if (out->num_vertices < 3 || out->num_triangles < 1)
  5636. continue;
  5637. type = LittleLong(in->type);
  5638. firstvertex = LittleLong(in->firstvertex);
  5639. firstelement = LittleLong(in->firstelement);
  5640. out->num_firstvertex = meshvertices;
  5641. out->num_firsttriangle = meshtriangles;
  5642. out->num_firstcollisiontriangle = collisiontriangles;
  5643. switch(type)
  5644. {
  5645. case Q3FACETYPE_FLAT:
  5646. case Q3FACETYPE_MESH:
  5647. // no processing necessary, except for lightmap merging
  5648. for (j = 0;j < out->num_vertices;j++)
  5649. {
  5650. (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
  5651. (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
  5652. (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
  5653. (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
  5654. (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
  5655. (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
  5656. (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
  5657. (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
  5658. (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
  5659. (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
  5660. (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
  5661. (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
  5662. (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
  5663. (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
  5664. }
  5665. for (j = 0;j < out->num_triangles*3;j++)
  5666. (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
  5667. break;
  5668. case Q3FACETYPE_PATCH:
  5669. patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
  5670. patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
  5671. originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
  5672. originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
  5673. originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
  5674. originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
  5675. originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
  5676. xtess = ytess = cxtess = cytess = -1;
  5677. for(j = 0; j < patchtesscount; ++j)
  5678. if(patchtess[j].surface_id == i)
  5679. {
  5680. xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
  5681. ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
  5682. cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
  5683. cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
  5684. break;
  5685. }
  5686. if(xtess == -1)
  5687. {
  5688. Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
  5689. xtess = ytess = cxtess = cytess = 0;
  5690. }
  5691. finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
  5692. finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
  5693. finalvertices = finalwidth * finalheight;
  5694. oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
  5695. type = Q3FACETYPE_MESH;
  5696. // generate geometry
  5697. // (note: normals are skipped because they get recalculated)
  5698. Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
  5699. Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
  5700. Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
  5701. Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
  5702. Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
  5703. Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
  5704. out->num_triangles = Mod_RemoveDegenerateTriangles(out->num_triangles, (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), loadmodel->surfmesh.data_vertex3f);
  5705. if (developer_extra.integer)
  5706. {
  5707. if (out->num_triangles < finaltriangles)
  5708. Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles, %i degenerate triangles removed (leaving %i)\n", patchsize[0], patchsize[1], out->num_vertices, finaltriangles, finaltriangles - out->num_triangles, out->num_triangles);
  5709. else
  5710. Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles\n", patchsize[0], patchsize[1], out->num_vertices, out->num_triangles);
  5711. }
  5712. // q3map does not put in collision brushes for curves... ugh
  5713. // build the lower quality collision geometry
  5714. finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
  5715. finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
  5716. finalvertices = finalwidth * finalheight;
  5717. oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
  5718. // legacy collision geometry implementation
  5719. out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
  5720. out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
  5721. out->num_collisionvertices = finalvertices;
  5722. out->num_collisiontriangles = finaltriangles;
  5723. Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
  5724. Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
  5725. //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
  5726. Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
  5727. out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
  5728. // now optimize the collision mesh by finding triangle bboxes...
  5729. Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
  5730. Mod_Q3BSP_BuildBBoxes(loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle, out->num_triangles, loadmodel->surfmesh.data_vertex3f, &out->deprecatedq3data_bbox6f, &out->deprecatedq3num_bboxstride, mod_q3bsp_curves_stride.integer);
  5731. // store collision geometry for BIH collision tree
  5732. surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
  5733. surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
  5734. Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
  5735. Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
  5736. Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
  5737. #if 1
  5738. // remove this once the legacy code is removed
  5739. {
  5740. int nc = out->num_collisiontriangles;
  5741. #endif
  5742. out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
  5743. #if 1
  5744. if(nc != out->num_collisiontriangles)
  5745. {
  5746. Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
  5747. }
  5748. }
  5749. #endif
  5750. if (developer_extra.integer)
  5751. Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve became %i:%i vertices / %i:%i triangles (%i:%i degenerate)\n", patchsize[0], patchsize[1], out->num_vertices, out->num_collisionvertices, oldnumtriangles, oldnumtriangles2, oldnumtriangles - out->num_triangles, oldnumtriangles2 - out->num_collisiontriangles);
  5752. collisionvertices += finalvertices;
  5753. collisiontriangles += out->num_collisiontriangles;
  5754. break;
  5755. default:
  5756. break;
  5757. }
  5758. meshvertices += out->num_vertices;
  5759. meshtriangles += out->num_triangles;
  5760. for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
  5761. if ((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
  5762. invalidelements++;
  5763. if (invalidelements)
  5764. {
  5765. Con_Printf("Mod_Q3BSP_LoadFaces: Warning: face #%i has %i invalid elements, type = %i, texture->name = \"%s\", texture->surfaceflags = %i, firstvertex = %i, numvertices = %i, firstelement = %i, numelements = %i, elements list:\n", i, invalidelements, type, out->texture->name, out->texture->surfaceflags, firstvertex, out->num_vertices, firstelement, out->num_triangles * 3);
  5766. for (j = 0;j < out->num_triangles * 3;j++)
  5767. {
  5768. Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
  5769. if ((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
  5770. (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
  5771. }
  5772. Con_Print("\n");
  5773. }
  5774. // calculate a bounding box
  5775. VectorClear(out->mins);
  5776. VectorClear(out->maxs);
  5777. if (out->num_vertices)
  5778. {
  5779. if (cls.state != ca_dedicated && out->lightmaptexture)
  5780. {
  5781. // figure out which part of the merged lightmap this fits into
  5782. int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
  5783. int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
  5784. int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
  5785. lightmapindex &= mergewidth * mergeheight - 1;
  5786. lightmaptcscale[0] = 1.0f / mergewidth;
  5787. lightmaptcscale[1] = 1.0f / mergeheight;
  5788. lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
  5789. lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
  5790. // modify the lightmap texcoords to match this region of the merged lightmap
  5791. for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
  5792. {
  5793. v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
  5794. v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
  5795. }
  5796. }
  5797. VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
  5798. VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
  5799. for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
  5800. {
  5801. out->mins[0] = min(out->mins[0], v[0]);
  5802. out->maxs[0] = max(out->maxs[0], v[0]);
  5803. out->mins[1] = min(out->mins[1], v[1]);
  5804. out->maxs[1] = max(out->maxs[1], v[1]);
  5805. out->mins[2] = min(out->mins[2], v[2]);
  5806. out->maxs[2] = max(out->maxs[2], v[2]);
  5807. }
  5808. out->mins[0] -= 1.0f;
  5809. out->mins[1] -= 1.0f;
  5810. out->mins[2] -= 1.0f;
  5811. out->maxs[0] += 1.0f;
  5812. out->maxs[1] += 1.0f;
  5813. out->maxs[2] += 1.0f;
  5814. }
  5815. // set lightmap styles for consistency with q1bsp
  5816. //out->lightmapinfo->styles[0] = 0;
  5817. //out->lightmapinfo->styles[1] = 255;
  5818. //out->lightmapinfo->styles[2] = 255;
  5819. //out->lightmapinfo->styles[3] = 255;
  5820. }
  5821. i = oldi;
  5822. out = oldout;
  5823. for (;i < count;i++, out++)
  5824. {
  5825. if(out->num_vertices && out->num_triangles)
  5826. continue;
  5827. if(out->num_vertices == 0)
  5828. {
  5829. Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
  5830. if(out->num_triangles == 0)
  5831. Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
  5832. }
  5833. else if(out->num_triangles == 0)
  5834. Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s, near %f %f %f) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)",
  5835. (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
  5836. (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
  5837. (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
  5838. }
  5839. // for per pixel lighting
  5840. Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
  5841. // generate ushort elements array if possible
  5842. if (loadmodel->surfmesh.data_element3s)
  5843. for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
  5844. loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
  5845. // free the no longer needed vertex data
  5846. loadmodel->brushq3.num_vertices = 0;
  5847. if (loadmodel->brushq3.data_vertex3f)
  5848. Mem_Free(loadmodel->brushq3.data_vertex3f);
  5849. loadmodel->brushq3.data_vertex3f = NULL;
  5850. loadmodel->brushq3.data_normal3f = NULL;
  5851. loadmodel->brushq3.data_texcoordtexture2f = NULL;
  5852. loadmodel->brushq3.data_texcoordlightmap2f = NULL;
  5853. loadmodel->brushq3.data_color4f = NULL;
  5854. // free the no longer needed triangle data
  5855. loadmodel->brushq3.num_triangles = 0;
  5856. if (loadmodel->brushq3.data_element3i)
  5857. Mem_Free(loadmodel->brushq3.data_element3i);
  5858. loadmodel->brushq3.data_element3i = NULL;
  5859. if(patchtess)
  5860. Mem_Free(patchtess);
  5861. }
  5862. static void Mod_Q3BSP_LoadModels(lump_t *l)
  5863. {
  5864. q3dmodel_t *in;
  5865. q3dmodel_t *out;
  5866. int i, j, n, c, count;
  5867. in = (q3dmodel_t *)(mod_base + l->fileofs);
  5868. if (l->filelen % sizeof(*in))
  5869. Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
  5870. count = l->filelen / sizeof(*in);
  5871. out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  5872. loadmodel->brushq3.data_models = out;
  5873. loadmodel->brushq3.num_models = count;
  5874. for (i = 0;i < count;i++, in++, out++)
  5875. {
  5876. for (j = 0;j < 3;j++)
  5877. {
  5878. out->mins[j] = LittleFloat(in->mins[j]);
  5879. out->maxs[j] = LittleFloat(in->maxs[j]);
  5880. }
  5881. n = LittleLong(in->firstface);
  5882. c = LittleLong(in->numfaces);
  5883. if (n < 0 || n + c > loadmodel->num_surfaces)
  5884. Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
  5885. out->firstface = n;
  5886. out->numfaces = c;
  5887. n = LittleLong(in->firstbrush);
  5888. c = LittleLong(in->numbrushes);
  5889. if (n < 0 || n + c > loadmodel->brush.num_brushes)
  5890. Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
  5891. out->firstbrush = n;
  5892. out->numbrushes = c;
  5893. }
  5894. }
  5895. static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
  5896. {
  5897. int *in;
  5898. int *out;
  5899. int i, n, count;
  5900. in = (int *)(mod_base + l->fileofs);
  5901. if (l->filelen % sizeof(*in))
  5902. Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
  5903. count = l->filelen / sizeof(*in);
  5904. out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  5905. loadmodel->brush.data_leafbrushes = out;
  5906. loadmodel->brush.num_leafbrushes = count;
  5907. for (i = 0;i < count;i++, in++, out++)
  5908. {
  5909. n = LittleLong(*in);
  5910. if (n < 0 || n >= loadmodel->brush.num_brushes)
  5911. Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
  5912. *out = n;
  5913. }
  5914. }
  5915. static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
  5916. {
  5917. int *in;
  5918. int *out;
  5919. int i, n, count;
  5920. in = (int *)(mod_base + l->fileofs);
  5921. if (l->filelen % sizeof(*in))
  5922. Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
  5923. count = l->filelen / sizeof(*in);
  5924. out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  5925. loadmodel->brush.data_leafsurfaces = out;
  5926. loadmodel->brush.num_leafsurfaces = count;
  5927. for (i = 0;i < count;i++, in++, out++)
  5928. {
  5929. n = LittleLong(*in);
  5930. if (n < 0 || n >= loadmodel->num_surfaces)
  5931. Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
  5932. *out = n;
  5933. }
  5934. }
  5935. static void Mod_Q3BSP_LoadLeafs(lump_t *l)
  5936. {
  5937. q3dleaf_t *in;
  5938. mleaf_t *out;
  5939. int i, j, n, c, count;
  5940. in = (q3dleaf_t *)(mod_base + l->fileofs);
  5941. if (l->filelen % sizeof(*in))
  5942. Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
  5943. count = l->filelen / sizeof(*in);
  5944. out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  5945. loadmodel->brush.data_leafs = out;
  5946. loadmodel->brush.num_leafs = count;
  5947. for (i = 0;i < count;i++, in++, out++)
  5948. {
  5949. out->parent = NULL;
  5950. out->plane = NULL;
  5951. out->clusterindex = LittleLong(in->clusterindex);
  5952. out->areaindex = LittleLong(in->areaindex);
  5953. for (j = 0;j < 3;j++)
  5954. {
  5955. // yes the mins/maxs are ints
  5956. out->mins[j] = LittleLong(in->mins[j]) - 1;
  5957. out->maxs[j] = LittleLong(in->maxs[j]) + 1;
  5958. }
  5959. n = LittleLong(in->firstleafface);
  5960. c = LittleLong(in->numleaffaces);
  5961. if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
  5962. Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
  5963. out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
  5964. out->numleafsurfaces = c;
  5965. n = LittleLong(in->firstleafbrush);
  5966. c = LittleLong(in->numleafbrushes);
  5967. if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
  5968. Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
  5969. out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
  5970. out->numleafbrushes = c;
  5971. }
  5972. }
  5973. static void Mod_Q3BSP_LoadNodes(lump_t *l)
  5974. {
  5975. q3dnode_t *in;
  5976. mnode_t *out;
  5977. int i, j, n, count;
  5978. in = (q3dnode_t *)(mod_base + l->fileofs);
  5979. if (l->filelen % sizeof(*in))
  5980. Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
  5981. count = l->filelen / sizeof(*in);
  5982. if (count == 0)
  5983. Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
  5984. out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  5985. loadmodel->brush.data_nodes = out;
  5986. loadmodel->brush.num_nodes = count;
  5987. for (i = 0;i < count;i++, in++, out++)
  5988. {
  5989. out->parent = NULL;
  5990. n = LittleLong(in->planeindex);
  5991. if (n < 0 || n >= loadmodel->brush.num_planes)
  5992. Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
  5993. out->plane = loadmodel->brush.data_planes + n;
  5994. for (j = 0;j < 2;j++)
  5995. {
  5996. n = LittleLong(in->childrenindex[j]);
  5997. if (n >= 0)
  5998. {
  5999. if (n >= loadmodel->brush.num_nodes)
  6000. Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
  6001. out->children[j] = loadmodel->brush.data_nodes + n;
  6002. }
  6003. else
  6004. {
  6005. n = -1 - n;
  6006. if (n >= loadmodel->brush.num_leafs)
  6007. Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
  6008. out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
  6009. }
  6010. }
  6011. for (j = 0;j < 3;j++)
  6012. {
  6013. // yes the mins/maxs are ints
  6014. out->mins[j] = LittleLong(in->mins[j]) - 1;
  6015. out->maxs[j] = LittleLong(in->maxs[j]) + 1;
  6016. }
  6017. }
  6018. // set the parent pointers
  6019. Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
  6020. }
  6021. static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
  6022. {
  6023. q3dlightgrid_t *in;
  6024. q3dlightgrid_t *out;
  6025. int count;
  6026. int i;
  6027. in = (q3dlightgrid_t *)(mod_base + l->fileofs);
  6028. if (l->filelen % sizeof(*in))
  6029. Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
  6030. loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
  6031. loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
  6032. loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
  6033. loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
  6034. loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
  6035. loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
  6036. loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
  6037. loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
  6038. loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
  6039. loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
  6040. loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
  6041. loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
  6042. count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
  6043. Matrix4x4_CreateScale3(&loadmodel->brushq3.num_lightgrid_indexfromworld, loadmodel->brushq3.num_lightgrid_scale[0], loadmodel->brushq3.num_lightgrid_scale[1], loadmodel->brushq3.num_lightgrid_scale[2]);
  6044. Matrix4x4_ConcatTranslate(&loadmodel->brushq3.num_lightgrid_indexfromworld, -loadmodel->brushq3.num_lightgrid_imins[0] * loadmodel->brushq3.num_lightgrid_cellsize[0], -loadmodel->brushq3.num_lightgrid_imins[1] * loadmodel->brushq3.num_lightgrid_cellsize[1], -loadmodel->brushq3.num_lightgrid_imins[2] * loadmodel->brushq3.num_lightgrid_cellsize[2]);
  6045. // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
  6046. if (l->filelen)
  6047. {
  6048. if (l->filelen < count * (int)sizeof(*in))
  6049. {
  6050. Con_Printf("Mod_Q3BSP_LoadLightGrid: invalid lightgrid lump size %i bytes, should be %i bytes (%ix%ix%i)", l->filelen, (int)(count * sizeof(*in)), loadmodel->brushq3.num_lightgrid_isize[0], loadmodel->brushq3.num_lightgrid_isize[1], loadmodel->brushq3.num_lightgrid_isize[2]);
  6051. return; // ignore the grid if we cannot understand it
  6052. }
  6053. if (l->filelen != count * (int)sizeof(*in))
  6054. Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
  6055. out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
  6056. loadmodel->brushq3.data_lightgrid = out;
  6057. loadmodel->brushq3.num_lightgrid = count;
  6058. // no swapping or validation necessary
  6059. memcpy(out, in, count * (int)sizeof(*out));
  6060. if(mod_q3bsp_sRGBlightmaps.integer)
  6061. {
  6062. if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
  6063. {
  6064. // we fix the brightness consistently via lightmapscale
  6065. }
  6066. else
  6067. {
  6068. for(i = 0; i < count; ++i)
  6069. {
  6070. out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
  6071. out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
  6072. out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
  6073. out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
  6074. out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
  6075. out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
  6076. }
  6077. }
  6078. }
  6079. else
  6080. {
  6081. if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
  6082. {
  6083. for(i = 0; i < count; ++i)
  6084. {
  6085. out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
  6086. out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
  6087. out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
  6088. out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
  6089. out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
  6090. out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
  6091. }
  6092. }
  6093. else
  6094. {
  6095. // all is good
  6096. }
  6097. }
  6098. }
  6099. }
  6100. static void Mod_Q3BSP_LoadPVS(lump_t *l)
  6101. {
  6102. q3dpvs_t *in;
  6103. int totalchains;
  6104. if (l->filelen == 0)
  6105. {
  6106. int i;
  6107. // unvised maps often have cluster indices even without pvs, so check
  6108. // leafs to find real number of clusters
  6109. loadmodel->brush.num_pvsclusters = 1;
  6110. for (i = 0;i < loadmodel->brush.num_leafs;i++)
  6111. loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
  6112. // create clusters
  6113. loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
  6114. totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
  6115. loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
  6116. memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
  6117. return;
  6118. }
  6119. in = (q3dpvs_t *)(mod_base + l->fileofs);
  6120. if (l->filelen < 9)
  6121. Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
  6122. loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
  6123. loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
  6124. if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
  6125. Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
  6126. totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
  6127. if (l->filelen < totalchains + (int)sizeof(*in))
  6128. Host_Error("Mod_Q3BSP_LoadPVS: lump too small ((numclusters = %i) * (chainlength = %i) + sizeof(q3dpvs_t) == %i bytes, lump is %i bytes)", loadmodel->brush.num_pvsclusters, loadmodel->brush.num_pvsclusterbytes, (int)(totalchains + sizeof(*in)), l->filelen);
  6129. loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
  6130. memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
  6131. }
  6132. static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
  6133. {
  6134. int i, j, k, index[3];
  6135. float transformed[3], blend1, blend2, blend, stylescale = 1;
  6136. q3dlightgrid_t *a, *s;
  6137. // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
  6138. switch(vid.renderpath)
  6139. {
  6140. case RENDERPATH_GL20:
  6141. case RENDERPATH_D3D9:
  6142. case RENDERPATH_D3D10:
  6143. case RENDERPATH_D3D11:
  6144. case RENDERPATH_SOFT:
  6145. case RENDERPATH_GLES2:
  6146. // LordHavoc: FIXME: is this true?
  6147. stylescale = 1; // added while render
  6148. break;
  6149. case RENDERPATH_GL11:
  6150. case RENDERPATH_GL13:
  6151. case RENDERPATH_GLES1:
  6152. stylescale = r_refdef.scene.rtlightstylevalue[0];
  6153. break;
  6154. }
  6155. if (!model->brushq3.num_lightgrid)
  6156. {
  6157. ambientcolor[0] = stylescale;
  6158. ambientcolor[1] = stylescale;
  6159. ambientcolor[2] = stylescale;
  6160. return;
  6161. }
  6162. Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
  6163. //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
  6164. //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
  6165. transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
  6166. transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
  6167. transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
  6168. index[0] = (int)floor(transformed[0]);
  6169. index[1] = (int)floor(transformed[1]);
  6170. index[2] = (int)floor(transformed[2]);
  6171. //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
  6172. // now lerp the values
  6173. VectorClear(diffusenormal);
  6174. a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
  6175. for (k = 0;k < 2;k++)
  6176. {
  6177. blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
  6178. if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
  6179. continue;
  6180. for (j = 0;j < 2;j++)
  6181. {
  6182. blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
  6183. if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
  6184. continue;
  6185. for (i = 0;i < 2;i++)
  6186. {
  6187. blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
  6188. if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
  6189. continue;
  6190. s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
  6191. VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
  6192. VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
  6193. // this uses the mod_md3_sin table because the values are
  6194. // already in the 0-255 range, the 64+ bias fetches a cosine
  6195. // instead of a sine value
  6196. diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
  6197. diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
  6198. diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
  6199. //Con_Printf("blend %f: ambient %i %i %i, diffuse %i %i %i, diffusepitch %i diffuseyaw %i (%f %f, normal %f %f %f)\n", blend, s->ambientrgb[0], s->ambientrgb[1], s->ambientrgb[2], s->diffusergb[0], s->diffusergb[1], s->diffusergb[2], s->diffusepitch, s->diffuseyaw, pitch, yaw, (cos(yaw) * cospitch), (sin(yaw) * cospitch), (-sin(pitch)));
  6200. }
  6201. }
  6202. }
  6203. // normalize the light direction before turning
  6204. VectorNormalize(diffusenormal);
  6205. //Con_Printf("result: ambient %f %f %f diffuse %f %f %f diffusenormal %f %f %f\n", ambientcolor[0], ambientcolor[1], ambientcolor[2], diffusecolor[0], diffusecolor[1], diffusecolor[2], diffusenormal[0], diffusenormal[1], diffusenormal[2]);
  6206. }
  6207. static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3], double endpos[3])
  6208. {
  6209. double t1, t2;
  6210. double midf, mid[3];
  6211. int ret, side;
  6212. // check for empty
  6213. while (node->plane)
  6214. {
  6215. // find the point distances
  6216. mplane_t *plane = node->plane;
  6217. if (plane->type < 3)
  6218. {
  6219. t1 = p1[plane->type] - plane->dist;
  6220. t2 = p2[plane->type] - plane->dist;
  6221. }
  6222. else
  6223. {
  6224. t1 = DotProduct (plane->normal, p1) - plane->dist;
  6225. t2 = DotProduct (plane->normal, p2) - plane->dist;
  6226. }
  6227. if (t1 < 0)
  6228. {
  6229. if (t2 < 0)
  6230. {
  6231. node = node->children[1];
  6232. continue;
  6233. }
  6234. side = 1;
  6235. }
  6236. else
  6237. {
  6238. if (t2 >= 0)
  6239. {
  6240. node = node->children[0];
  6241. continue;
  6242. }
  6243. side = 0;
  6244. }
  6245. midf = t1 / (t1 - t2);
  6246. VectorLerp(p1, midf, p2, mid);
  6247. // recurse both sides, front side first
  6248. // return 2 if empty is followed by solid (hit something)
  6249. // do not return 2 if both are solid or both empty,
  6250. // or if start is solid and end is empty
  6251. // as these degenerate cases usually indicate the eye is in solid and
  6252. // should see the target point anyway
  6253. ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid, endpos);
  6254. if (ret != 0)
  6255. return ret;
  6256. ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2, endpos);
  6257. if (ret != 1)
  6258. return ret;
  6259. VectorCopy(mid, endpos);
  6260. return 2;
  6261. }
  6262. return ((mleaf_t *)node)->clusterindex < 0;
  6263. }
  6264. static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
  6265. {
  6266. if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
  6267. {
  6268. trace_t trace;
  6269. model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
  6270. return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
  6271. }
  6272. else
  6273. {
  6274. double tracestart[3], traceend[3], traceendpos[3];
  6275. VectorCopy(start, tracestart);
  6276. VectorCopy(end, traceend);
  6277. VectorCopy(end, traceendpos);
  6278. Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend, traceendpos);
  6279. return BoxesOverlap(traceendpos, traceendpos, acceptmins, acceptmaxs);
  6280. }
  6281. }
  6282. void Mod_CollisionBIH_TracePoint(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  6283. {
  6284. const bih_t *bih;
  6285. const bih_leaf_t *leaf;
  6286. const bih_node_t *node;
  6287. const colbrushf_t *brush;
  6288. int axis;
  6289. int nodenum;
  6290. int nodestackpos = 0;
  6291. int nodestack[1024];
  6292. memset(trace, 0, sizeof(*trace));
  6293. trace->fraction = 1;
  6294. trace->hitsupercontentsmask = hitsupercontentsmask;
  6295. trace->skipsupercontentsmask = skipsupercontentsmask;
  6296. trace->skipmaterialflagsmask = skipmaterialflagsmask;
  6297. bih = &model->collision_bih;
  6298. if(!bih->nodes)
  6299. return;
  6300. nodenum = bih->rootnode;
  6301. nodestack[nodestackpos++] = nodenum;
  6302. while (nodestackpos)
  6303. {
  6304. nodenum = nodestack[--nodestackpos];
  6305. node = bih->nodes + nodenum;
  6306. #if 1
  6307. if (!BoxesOverlap(start, start, node->mins, node->maxs))
  6308. continue;
  6309. #endif
  6310. if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
  6311. {
  6312. axis = node->type - BIH_SPLITX;
  6313. if (start[axis] >= node->frontmin)
  6314. nodestack[nodestackpos++] = node->front;
  6315. if (start[axis] <= node->backmax)
  6316. nodestack[nodestackpos++] = node->back;
  6317. }
  6318. else if (node->type == BIH_UNORDERED)
  6319. {
  6320. for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
  6321. {
  6322. leaf = bih->leafs + node->children[axis];
  6323. #if 1
  6324. if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
  6325. continue;
  6326. #endif
  6327. switch(leaf->type)
  6328. {
  6329. case BIH_BRUSH:
  6330. brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
  6331. Collision_TracePointBrushFloat(trace, start, brush);
  6332. break;
  6333. case BIH_COLLISIONTRIANGLE:
  6334. // collision triangle - skipped because they have no volume
  6335. break;
  6336. case BIH_RENDERTRIANGLE:
  6337. // render triangle - skipped because they have no volume
  6338. break;
  6339. }
  6340. }
  6341. }
  6342. }
  6343. }
  6344. static void Mod_CollisionBIH_TraceLineShared(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask, const bih_t *bih)
  6345. {
  6346. const bih_leaf_t *leaf;
  6347. const bih_node_t *node;
  6348. const colbrushf_t *brush;
  6349. const int *e;
  6350. const texture_t *texture;
  6351. vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
  6352. vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
  6353. int axis, nodenum, nodestackpos = 0, nodestack[1024];
  6354. if(!bih->nodes)
  6355. return;
  6356. if (VectorCompare(start, end))
  6357. {
  6358. Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  6359. return;
  6360. }
  6361. nodenum = bih->rootnode;
  6362. memset(trace, 0, sizeof(*trace));
  6363. trace->fraction = 1;
  6364. trace->hitsupercontentsmask = hitsupercontentsmask;
  6365. trace->skipsupercontentsmask = skipsupercontentsmask;
  6366. trace->skipmaterialflagsmask = skipmaterialflagsmask;
  6367. // push first node
  6368. nodestackline[nodestackpos][0] = start[0];
  6369. nodestackline[nodestackpos][1] = start[1];
  6370. nodestackline[nodestackpos][2] = start[2];
  6371. nodestackline[nodestackpos][3] = end[0];
  6372. nodestackline[nodestackpos][4] = end[1];
  6373. nodestackline[nodestackpos][5] = end[2];
  6374. nodestack[nodestackpos++] = nodenum;
  6375. while (nodestackpos)
  6376. {
  6377. nodenum = nodestack[--nodestackpos];
  6378. node = bih->nodes + nodenum;
  6379. VectorCopy(nodestackline[nodestackpos], nodestart);
  6380. VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
  6381. sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
  6382. sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
  6383. sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
  6384. sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
  6385. sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
  6386. sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
  6387. if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs) && !collision_bih_fullrecursion.integer)
  6388. continue;
  6389. if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
  6390. {
  6391. // recurse children of the split
  6392. axis = node->type - BIH_SPLITX;
  6393. d1 = node->backmax - nodestart[axis];
  6394. d2 = node->backmax - nodeend[axis];
  6395. d3 = nodestart[axis] - node->frontmin;
  6396. d4 = nodeend[axis] - node->frontmin;
  6397. if (collision_bih_fullrecursion.integer)
  6398. d1 = d2 = d3 = d4 = 1; // force full recursion
  6399. switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
  6400. {
  6401. case 0: /* >>>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6402. case 1: /* <>>> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6403. case 2: /* ><>> */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6404. case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6405. case 4: /* >><> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6406. case 5: /* <><> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6407. case 6: /* ><<> */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6408. case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6409. case 8: /* >>>< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6410. case 9: /* <>>< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6411. case 10: /* ><>< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6412. case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6413. case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
  6414. case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
  6415. case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
  6416. case 15: /* <<<< */ break;
  6417. }
  6418. }
  6419. else if (node->type == BIH_UNORDERED)
  6420. {
  6421. // calculate sweep bounds for this node
  6422. // copy node bounds into local variables
  6423. VectorCopy(node->mins, nodebigmins);
  6424. VectorCopy(node->maxs, nodebigmaxs);
  6425. // clip line to this node bounds
  6426. axis = 0; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
  6427. axis = 1; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
  6428. axis = 2; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
  6429. // some of the line intersected the enlarged node box
  6430. // calculate sweep bounds for this node
  6431. sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
  6432. sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
  6433. sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
  6434. sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
  6435. sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
  6436. sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
  6437. for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
  6438. {
  6439. leaf = bih->leafs + node->children[axis];
  6440. if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
  6441. continue;
  6442. switch(leaf->type)
  6443. {
  6444. case BIH_BRUSH:
  6445. brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
  6446. Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
  6447. break;
  6448. case BIH_COLLISIONTRIANGLE:
  6449. if (!mod_q3bsp_curves_collisions.integer)
  6450. continue;
  6451. e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
  6452. texture = model->data_textures + leaf->textureindex;
  6453. Collision_TraceLineTriangleFloat(trace, start, end, model->brush.data_collisionvertex3f + e[0] * 3, model->brush.data_collisionvertex3f + e[1] * 3, model->brush.data_collisionvertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
  6454. break;
  6455. case BIH_RENDERTRIANGLE:
  6456. e = model->surfmesh.data_element3i + 3*leaf->itemindex;
  6457. texture = model->data_textures + leaf->textureindex;
  6458. Collision_TraceLineTriangleFloat(trace, start, end, model->surfmesh.data_vertex3f + e[0] * 3, model->surfmesh.data_vertex3f + e[1] * 3, model->surfmesh.data_vertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
  6459. break;
  6460. }
  6461. }
  6462. }
  6463. }
  6464. }
  6465. void Mod_CollisionBIH_TraceLine(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  6466. {
  6467. if (VectorCompare(start, end))
  6468. {
  6469. Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  6470. return;
  6471. }
  6472. Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->collision_bih);
  6473. }
  6474. void Mod_CollisionBIH_TraceBrush(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *thisbrush_start, colbrushf_t *thisbrush_end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  6475. {
  6476. const bih_t *bih;
  6477. const bih_leaf_t *leaf;
  6478. const bih_node_t *node;
  6479. const colbrushf_t *brush;
  6480. const int *e;
  6481. const texture_t *texture;
  6482. vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
  6483. vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
  6484. vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
  6485. int axis, nodenum, nodestackpos = 0, nodestack[1024];
  6486. if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
  6487. {
  6488. if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
  6489. Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  6490. else
  6491. Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  6492. return;
  6493. }
  6494. bih = &model->collision_bih;
  6495. if(!bih->nodes)
  6496. return;
  6497. nodenum = bih->rootnode;
  6498. // box trace, performed as brush trace
  6499. memset(trace, 0, sizeof(*trace));
  6500. trace->fraction = 1;
  6501. trace->hitsupercontentsmask = hitsupercontentsmask;
  6502. trace->skipsupercontentsmask = skipsupercontentsmask;
  6503. trace->skipmaterialflagsmask = skipmaterialflagsmask;
  6504. // calculate tracebox-like parameters for efficient culling
  6505. VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
  6506. VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
  6507. VectorSubtract(thisbrush_start->mins, start, startmins);
  6508. VectorSubtract(thisbrush_start->maxs, start, startmaxs);
  6509. VectorSubtract(thisbrush_end->mins, end, endmins);
  6510. VectorSubtract(thisbrush_end->maxs, end, endmaxs);
  6511. mins[0] = min(startmins[0], endmins[0]);
  6512. mins[1] = min(startmins[1], endmins[1]);
  6513. mins[2] = min(startmins[2], endmins[2]);
  6514. maxs[0] = max(startmaxs[0], endmaxs[0]);
  6515. maxs[1] = max(startmaxs[1], endmaxs[1]);
  6516. maxs[2] = max(startmaxs[2], endmaxs[2]);
  6517. // push first node
  6518. nodestackline[nodestackpos][0] = start[0];
  6519. nodestackline[nodestackpos][1] = start[1];
  6520. nodestackline[nodestackpos][2] = start[2];
  6521. nodestackline[nodestackpos][3] = end[0];
  6522. nodestackline[nodestackpos][4] = end[1];
  6523. nodestackline[nodestackpos][5] = end[2];
  6524. nodestack[nodestackpos++] = nodenum;
  6525. while (nodestackpos)
  6526. {
  6527. nodenum = nodestack[--nodestackpos];
  6528. node = bih->nodes + nodenum;
  6529. VectorCopy(nodestackline[nodestackpos], nodestart);
  6530. VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
  6531. sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
  6532. sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
  6533. sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
  6534. sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
  6535. sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
  6536. sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
  6537. if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
  6538. continue;
  6539. if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
  6540. {
  6541. // recurse children of the split
  6542. axis = node->type - BIH_SPLITX;
  6543. d1 = node->backmax - nodestart[axis] - mins[axis];
  6544. d2 = node->backmax - nodeend[axis] - mins[axis];
  6545. d3 = nodestart[axis] - node->frontmin + maxs[axis];
  6546. d4 = nodeend[axis] - node->frontmin + maxs[axis];
  6547. switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
  6548. {
  6549. case 0: /* >>>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6550. case 1: /* <>>> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6551. case 2: /* ><>> */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6552. case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6553. case 4: /* >><> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6554. case 5: /* <><> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6555. case 6: /* ><<> */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6556. case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6557. case 8: /* >>>< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6558. case 9: /* <>>< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6559. case 10: /* ><>< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6560. case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
  6561. case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
  6562. case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
  6563. case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
  6564. case 15: /* <<<< */ break;
  6565. }
  6566. }
  6567. else if (node->type == BIH_UNORDERED)
  6568. {
  6569. // calculate sweep bounds for this node
  6570. // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
  6571. VectorSubtract(node->mins, maxs, nodebigmins);
  6572. VectorSubtract(node->maxs, mins, nodebigmaxs);
  6573. // clip line to this node bounds
  6574. axis = 0; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
  6575. axis = 1; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
  6576. axis = 2; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
  6577. // some of the line intersected the enlarged node box
  6578. // calculate sweep bounds for this node
  6579. sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
  6580. sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
  6581. sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
  6582. sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
  6583. sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
  6584. sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
  6585. for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
  6586. {
  6587. leaf = bih->leafs + node->children[axis];
  6588. if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
  6589. continue;
  6590. switch(leaf->type)
  6591. {
  6592. case BIH_BRUSH:
  6593. brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
  6594. Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
  6595. break;
  6596. case BIH_COLLISIONTRIANGLE:
  6597. if (!mod_q3bsp_curves_collisions.integer)
  6598. continue;
  6599. e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
  6600. texture = model->data_textures + leaf->textureindex;
  6601. Collision_TraceBrushTriangleFloat(trace, thisbrush_start, thisbrush_end, model->brush.data_collisionvertex3f + e[0] * 3, model->brush.data_collisionvertex3f + e[1] * 3, model->brush.data_collisionvertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
  6602. break;
  6603. case BIH_RENDERTRIANGLE:
  6604. e = model->surfmesh.data_element3i + 3*leaf->itemindex;
  6605. texture = model->data_textures + leaf->textureindex;
  6606. Collision_TraceBrushTriangleFloat(trace, thisbrush_start, thisbrush_end, model->surfmesh.data_vertex3f + e[0] * 3, model->surfmesh.data_vertex3f + e[1] * 3, model->surfmesh.data_vertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
  6607. break;
  6608. }
  6609. }
  6610. }
  6611. }
  6612. }
  6613. void Mod_CollisionBIH_TraceBox(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  6614. {
  6615. colboxbrushf_t thisbrush_start, thisbrush_end;
  6616. vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
  6617. // box trace, performed as brush trace
  6618. VectorAdd(start, boxmins, boxstartmins);
  6619. VectorAdd(start, boxmaxs, boxstartmaxs);
  6620. VectorAdd(end, boxmins, boxendmins);
  6621. VectorAdd(end, boxmaxs, boxendmaxs);
  6622. Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
  6623. Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
  6624. Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  6625. }
  6626. int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
  6627. {
  6628. trace_t trace;
  6629. Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0, 0, 0);
  6630. return trace.startsupercontents;
  6631. }
  6632. qboolean Mod_CollisionBIH_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
  6633. {
  6634. trace_t trace;
  6635. Mod_CollisionBIH_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
  6636. return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
  6637. }
  6638. void Mod_CollisionBIH_TracePoint_Mesh(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  6639. {
  6640. #if 0
  6641. // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
  6642. vec3_t end;
  6643. int hitsupercontents;
  6644. VectorSet(end, start[0], start[1], model->normalmins[2]);
  6645. #endif
  6646. memset(trace, 0, sizeof(*trace));
  6647. trace->fraction = 1;
  6648. trace->hitsupercontentsmask = hitsupercontentsmask;
  6649. trace->skipsupercontentsmask = skipsupercontentsmask;
  6650. trace->skipmaterialflagsmask = skipmaterialflagsmask;
  6651. #if 0
  6652. Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  6653. hitsupercontents = trace->hitsupercontents;
  6654. memset(trace, 0, sizeof(*trace));
  6655. trace->fraction = 1;
  6656. trace->hitsupercontentsmask = hitsupercontentsmask;
  6657. trace->skipsupercontentsmask = skipsupercontentsmask;
  6658. trace->skipmaterialflagsmask = skipmaterialflagsmask;
  6659. trace->startsupercontents = hitsupercontents;
  6660. #endif
  6661. }
  6662. int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
  6663. {
  6664. #if 0
  6665. // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
  6666. trace_t trace;
  6667. vec3_t end;
  6668. VectorSet(end, start[0], start[1], model->normalmins[2]);
  6669. memset(&trace, 0, sizeof(trace));
  6670. trace.fraction = 1;
  6671. trace.hitsupercontentsmask = hitsupercontentsmask;
  6672. trace.skipsupercontentsmask = skipsupercontentsmask;
  6673. trace.skipmaterialflagsmask = skipmaterialflagsmask;
  6674. Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  6675. return trace.hitsupercontents;
  6676. #else
  6677. return 0;
  6678. #endif
  6679. }
  6680. static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
  6681. {
  6682. int i;
  6683. mleaf_t *leaf;
  6684. colbrushf_t *brush;
  6685. // find which leaf the point is in
  6686. while (node->plane)
  6687. node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
  6688. // point trace the brushes
  6689. leaf = (mleaf_t *)node;
  6690. for (i = 0;i < leaf->numleafbrushes;i++)
  6691. {
  6692. brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
  6693. if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
  6694. {
  6695. brush->markframe = markframe;
  6696. Collision_TracePointBrushFloat(trace, point, brush);
  6697. }
  6698. }
  6699. // can't do point traces on curves (they have no thickness)
  6700. }
  6701. static void Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t start, const vec3_t end, vec_t startfrac, vec_t endfrac, const vec3_t linestart, const vec3_t lineend, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
  6702. {
  6703. int i, startside, endside;
  6704. float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
  6705. mleaf_t *leaf;
  6706. msurface_t *surface;
  6707. mplane_t *plane;
  6708. colbrushf_t *brush;
  6709. // walk the tree until we hit a leaf, recursing for any split cases
  6710. while (node->plane)
  6711. {
  6712. #if 0
  6713. if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
  6714. return;
  6715. Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
  6716. node = node->children[1];
  6717. #else
  6718. // abort if this part of the bsp tree can not be hit by this trace
  6719. // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
  6720. // return;
  6721. plane = node->plane;
  6722. // axial planes are much more common than non-axial, so an optimized
  6723. // axial case pays off here
  6724. if (plane->type < 3)
  6725. {
  6726. dist1 = start[plane->type] - plane->dist;
  6727. dist2 = end[plane->type] - plane->dist;
  6728. }
  6729. else
  6730. {
  6731. dist1 = DotProduct(start, plane->normal) - plane->dist;
  6732. dist2 = DotProduct(end, plane->normal) - plane->dist;
  6733. }
  6734. startside = dist1 < 0;
  6735. endside = dist2 < 0;
  6736. if (startside == endside)
  6737. {
  6738. // most of the time the line fragment is on one side of the plane
  6739. node = node->children[startside];
  6740. }
  6741. else
  6742. {
  6743. // line crosses node plane, split the line
  6744. dist1 = PlaneDiff(linestart, plane);
  6745. dist2 = PlaneDiff(lineend, plane);
  6746. midfrac = dist1 / (dist1 - dist2);
  6747. VectorLerp(linestart, midfrac, lineend, mid);
  6748. // take the near side first
  6749. Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
  6750. // if we found an impact on the front side, don't waste time
  6751. // exploring the far side
  6752. if (midfrac <= trace->fraction)
  6753. Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
  6754. return;
  6755. }
  6756. #endif
  6757. }
  6758. // abort if this part of the bsp tree can not be hit by this trace
  6759. // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
  6760. // return;
  6761. // hit a leaf
  6762. nodesegmentmins[0] = min(start[0], end[0]) - 1;
  6763. nodesegmentmins[1] = min(start[1], end[1]) - 1;
  6764. nodesegmentmins[2] = min(start[2], end[2]) - 1;
  6765. nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
  6766. nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
  6767. nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
  6768. // line trace the brushes
  6769. leaf = (mleaf_t *)node;
  6770. #if 0
  6771. if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
  6772. return;
  6773. #endif
  6774. for (i = 0;i < leaf->numleafbrushes;i++)
  6775. {
  6776. brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
  6777. if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
  6778. {
  6779. brush->markframe = markframe;
  6780. Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
  6781. }
  6782. }
  6783. // can't do point traces on curves (they have no thickness)
  6784. if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
  6785. {
  6786. // line trace the curves
  6787. for (i = 0;i < leaf->numleafsurfaces;i++)
  6788. {
  6789. surface = model->data_surfaces + leaf->firstleafsurface[i];
  6790. if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
  6791. {
  6792. surface->deprecatedq3collisionmarkframe = markframe;
  6793. Collision_TraceLineTriangleMeshFloat(trace, linestart, lineend, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
  6794. }
  6795. }
  6796. }
  6797. }
  6798. static void Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
  6799. {
  6800. int i;
  6801. int sides;
  6802. mleaf_t *leaf;
  6803. colbrushf_t *brush;
  6804. msurface_t *surface;
  6805. mplane_t *plane;
  6806. float nodesegmentmins[3], nodesegmentmaxs[3];
  6807. // walk the tree until we hit a leaf, recursing for any split cases
  6808. while (node->plane)
  6809. {
  6810. #if 0
  6811. if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
  6812. return;
  6813. Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
  6814. node = node->children[1];
  6815. #else
  6816. // abort if this part of the bsp tree can not be hit by this trace
  6817. // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
  6818. // return;
  6819. plane = node->plane;
  6820. // axial planes are much more common than non-axial, so an optimized
  6821. // axial case pays off here
  6822. if (plane->type < 3)
  6823. {
  6824. // this is an axial plane, compare bounding box directly to it and
  6825. // recurse sides accordingly
  6826. // recurse down node sides
  6827. // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
  6828. //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
  6829. //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
  6830. sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
  6831. }
  6832. else
  6833. {
  6834. // this is a non-axial plane, so check if the start and end boxes
  6835. // are both on one side of the plane to handle 'diagonal' cases
  6836. sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
  6837. }
  6838. if (sides == 3)
  6839. {
  6840. // segment crosses plane
  6841. Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
  6842. sides = 2;
  6843. }
  6844. // if sides == 0 then the trace itself is bogus (Not A Number values),
  6845. // in this case we simply pretend the trace hit nothing
  6846. if (sides == 0)
  6847. return; // ERROR: NAN bounding box!
  6848. // take whichever side the segment box is on
  6849. node = node->children[sides - 1];
  6850. #endif
  6851. }
  6852. // abort if this part of the bsp tree can not be hit by this trace
  6853. // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
  6854. // return;
  6855. nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
  6856. nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
  6857. nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
  6858. nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
  6859. nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
  6860. nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
  6861. // hit a leaf
  6862. leaf = (mleaf_t *)node;
  6863. #if 0
  6864. if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
  6865. return;
  6866. #endif
  6867. for (i = 0;i < leaf->numleafbrushes;i++)
  6868. {
  6869. brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
  6870. if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
  6871. {
  6872. brush->markframe = markframe;
  6873. Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
  6874. }
  6875. }
  6876. if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
  6877. {
  6878. for (i = 0;i < leaf->numleafsurfaces;i++)
  6879. {
  6880. surface = model->data_surfaces + leaf->firstleafsurface[i];
  6881. if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
  6882. {
  6883. surface->deprecatedq3collisionmarkframe = markframe;
  6884. Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
  6885. }
  6886. }
  6887. }
  6888. }
  6889. static int markframe = 0;
  6890. static void Mod_Q3BSP_TracePoint(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  6891. {
  6892. int i;
  6893. q3mbrush_t *brush;
  6894. memset(trace, 0, sizeof(*trace));
  6895. trace->fraction = 1;
  6896. trace->hitsupercontentsmask = hitsupercontentsmask;
  6897. trace->skipsupercontentsmask = skipsupercontentsmask;
  6898. trace->skipmaterialflagsmask = skipmaterialflagsmask;
  6899. if (mod_collision_bih.integer)
  6900. Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  6901. else if (model->brush.submodel)
  6902. {
  6903. for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
  6904. if (brush->colbrushf)
  6905. Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
  6906. }
  6907. else
  6908. Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
  6909. }
  6910. static void Mod_Q3BSP_TraceLine(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  6911. {
  6912. int i;
  6913. float segmentmins[3], segmentmaxs[3];
  6914. msurface_t *surface;
  6915. q3mbrush_t *brush;
  6916. if (VectorCompare(start, end))
  6917. {
  6918. Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  6919. return;
  6920. }
  6921. memset(trace, 0, sizeof(*trace));
  6922. trace->fraction = 1;
  6923. trace->hitsupercontentsmask = hitsupercontentsmask;
  6924. trace->skipsupercontentsmask = skipsupercontentsmask;
  6925. trace->skipmaterialflagsmask = skipmaterialflagsmask;
  6926. segmentmins[0] = min(start[0], end[0]) - 1;
  6927. segmentmins[1] = min(start[1], end[1]) - 1;
  6928. segmentmins[2] = min(start[2], end[2]) - 1;
  6929. segmentmaxs[0] = max(start[0], end[0]) + 1;
  6930. segmentmaxs[1] = max(start[1], end[1]) + 1;
  6931. segmentmaxs[2] = max(start[2], end[2]) + 1;
  6932. if (mod_collision_bih.integer)
  6933. Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  6934. else if (model->brush.submodel)
  6935. {
  6936. for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
  6937. if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
  6938. Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
  6939. if (mod_q3bsp_curves_collisions.integer)
  6940. for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
  6941. if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
  6942. Collision_TraceLineTriangleMeshFloat(trace, start, end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
  6943. }
  6944. else
  6945. Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
  6946. }
  6947. static void Mod_Q3BSP_TraceBrush(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *start, colbrushf_t *end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  6948. {
  6949. float segmentmins[3], segmentmaxs[3];
  6950. int i;
  6951. msurface_t *surface;
  6952. q3mbrush_t *brush;
  6953. if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
  6954. {
  6955. if (VectorCompare(start->mins, end->mins))
  6956. Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  6957. else
  6958. Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  6959. return;
  6960. }
  6961. // box trace, performed as brush trace
  6962. memset(trace, 0, sizeof(*trace));
  6963. trace->fraction = 1;
  6964. trace->hitsupercontentsmask = hitsupercontentsmask;
  6965. trace->skipsupercontentsmask = skipsupercontentsmask;
  6966. trace->skipmaterialflagsmask = skipmaterialflagsmask;
  6967. segmentmins[0] = min(start->mins[0], end->mins[0]) - 1;
  6968. segmentmins[1] = min(start->mins[1], end->mins[1]) - 1;
  6969. segmentmins[2] = min(start->mins[2], end->mins[2]) - 1;
  6970. segmentmaxs[0] = max(start->maxs[0], end->maxs[0]) + 1;
  6971. segmentmaxs[1] = max(start->maxs[1], end->maxs[1]) + 1;
  6972. segmentmaxs[2] = max(start->maxs[2], end->maxs[2]) + 1;
  6973. if (mod_collision_bih.integer)
  6974. Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  6975. else if (model->brush.submodel)
  6976. {
  6977. for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
  6978. if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
  6979. Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
  6980. if (mod_q3bsp_curves_collisions.integer)
  6981. for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
  6982. if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
  6983. Collision_TraceBrushTriangleMeshFloat(trace, start, end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
  6984. }
  6985. else
  6986. Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
  6987. }
  6988. static void Mod_Q3BSP_TraceBox(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  6989. {
  6990. colboxbrushf_t thisbrush_start, thisbrush_end;
  6991. vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
  6992. // box trace, performed as brush trace
  6993. VectorAdd(start, boxmins, boxstartmins);
  6994. VectorAdd(start, boxmaxs, boxstartmaxs);
  6995. VectorAdd(end, boxmins, boxendmins);
  6996. VectorAdd(end, boxmaxs, boxendmaxs);
  6997. Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
  6998. Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
  6999. Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
  7000. }
  7001. static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
  7002. {
  7003. int i;
  7004. int supercontents = 0;
  7005. q3mbrush_t *brush;
  7006. if (mod_collision_bih.integer)
  7007. {
  7008. supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
  7009. }
  7010. // test if the point is inside each brush
  7011. else if (model->brush.submodel)
  7012. {
  7013. // submodels are effectively one leaf
  7014. for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
  7015. if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
  7016. supercontents |= brush->colbrushf->supercontents;
  7017. }
  7018. else
  7019. {
  7020. mnode_t *node = model->brush.data_nodes;
  7021. mleaf_t *leaf;
  7022. // find which leaf the point is in
  7023. while (node->plane)
  7024. node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
  7025. leaf = (mleaf_t *)node;
  7026. // now check the brushes in the leaf
  7027. for (i = 0;i < leaf->numleafbrushes;i++)
  7028. {
  7029. brush = model->brush.data_brushes + leaf->firstleafbrush[i];
  7030. if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
  7031. supercontents |= brush->colbrushf->supercontents;
  7032. }
  7033. }
  7034. return supercontents;
  7035. }
  7036. void Mod_CollisionBIH_TraceLineAgainstSurfaces(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
  7037. {
  7038. Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->render_bih);
  7039. }
  7040. bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
  7041. {
  7042. int j;
  7043. int bihnumleafs;
  7044. int bihmaxnodes;
  7045. int brushindex;
  7046. int triangleindex;
  7047. int bihleafindex;
  7048. int nummodelbrushes = model->nummodelbrushes;
  7049. int nummodelsurfaces = model->nummodelsurfaces;
  7050. const int *e;
  7051. const int *collisionelement3i;
  7052. const float *collisionvertex3f;
  7053. const int *renderelement3i;
  7054. const float *rendervertex3f;
  7055. bih_leaf_t *bihleafs;
  7056. bih_node_t *bihnodes;
  7057. int *temp_leafsort;
  7058. int *temp_leafsortscratch;
  7059. const msurface_t *surface;
  7060. const q3mbrush_t *brush;
  7061. // find out how many BIH leaf nodes we need
  7062. bihnumleafs = 0;
  7063. if (userendersurfaces)
  7064. {
  7065. for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
  7066. bihnumleafs += surface->num_triangles;
  7067. }
  7068. else
  7069. {
  7070. for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
  7071. if (brush->colbrushf)
  7072. bihnumleafs++;
  7073. for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
  7074. {
  7075. if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
  7076. bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
  7077. else
  7078. bihnumleafs += surface->num_collisiontriangles;
  7079. }
  7080. }
  7081. if (!bihnumleafs)
  7082. return NULL;
  7083. // allocate the memory for the BIH leaf nodes
  7084. bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
  7085. // now populate the BIH leaf nodes
  7086. bihleafindex = 0;
  7087. // add render surfaces
  7088. renderelement3i = model->surfmesh.data_element3i;
  7089. rendervertex3f = model->surfmesh.data_vertex3f;
  7090. for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
  7091. {
  7092. for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
  7093. {
  7094. if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
  7095. continue;
  7096. bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
  7097. bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
  7098. bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
  7099. bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
  7100. bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
  7101. bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
  7102. bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
  7103. bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
  7104. bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
  7105. bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
  7106. bihleafindex++;
  7107. }
  7108. }
  7109. if (!userendersurfaces)
  7110. {
  7111. // add collision brushes
  7112. for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
  7113. {
  7114. if (!brush->colbrushf)
  7115. continue;
  7116. bihleafs[bihleafindex].type = BIH_BRUSH;
  7117. bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
  7118. bihleafs[bihleafindex].surfaceindex = -1;
  7119. bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
  7120. VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
  7121. VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
  7122. bihleafindex++;
  7123. }
  7124. // add collision surfaces
  7125. collisionelement3i = model->brush.data_collisionelement3i;
  7126. collisionvertex3f = model->brush.data_collisionvertex3f;
  7127. for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
  7128. {
  7129. for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
  7130. {
  7131. bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
  7132. bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
  7133. bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
  7134. bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
  7135. bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
  7136. bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
  7137. bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
  7138. bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
  7139. bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
  7140. bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
  7141. bihleafindex++;
  7142. }
  7143. }
  7144. }
  7145. // allocate buffers for the produced and temporary data
  7146. bihmaxnodes = bihnumleafs + 1;
  7147. bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
  7148. temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
  7149. temp_leafsortscratch = temp_leafsort + bihnumleafs;
  7150. // now build it
  7151. BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
  7152. // we're done with the temporary data
  7153. Mem_Free(temp_leafsort);
  7154. // resize the BIH nodes array if it over-allocated
  7155. if (out->maxnodes > out->numnodes)
  7156. {
  7157. out->maxnodes = out->numnodes;
  7158. out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
  7159. }
  7160. return out;
  7161. }
  7162. static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents)
  7163. {
  7164. int supercontents = 0;
  7165. if (nativecontents & CONTENTSQ3_SOLID)
  7166. supercontents |= SUPERCONTENTS_SOLID;
  7167. if (nativecontents & CONTENTSQ3_WATER)
  7168. supercontents |= SUPERCONTENTS_WATER;
  7169. if (nativecontents & CONTENTSQ3_SLIME)
  7170. supercontents |= SUPERCONTENTS_SLIME;
  7171. if (nativecontents & CONTENTSQ3_LAVA)
  7172. supercontents |= SUPERCONTENTS_LAVA;
  7173. if (nativecontents & CONTENTSQ3_BODY)
  7174. supercontents |= SUPERCONTENTS_BODY;
  7175. if (nativecontents & CONTENTSQ3_CORPSE)
  7176. supercontents |= SUPERCONTENTS_CORPSE;
  7177. if (nativecontents & CONTENTSQ3_NODROP)
  7178. supercontents |= SUPERCONTENTS_NODROP;
  7179. if (nativecontents & CONTENTSQ3_PLAYERCLIP)
  7180. supercontents |= SUPERCONTENTS_PLAYERCLIP;
  7181. if (nativecontents & CONTENTSQ3_MONSTERCLIP)
  7182. supercontents |= SUPERCONTENTS_MONSTERCLIP;
  7183. if (nativecontents & CONTENTSQ3_DONOTENTER)
  7184. supercontents |= SUPERCONTENTS_DONOTENTER;
  7185. if (nativecontents & CONTENTSQ3_BOTCLIP)
  7186. supercontents |= SUPERCONTENTS_BOTCLIP;
  7187. if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
  7188. supercontents |= SUPERCONTENTS_OPAQUE;
  7189. return supercontents;
  7190. }
  7191. static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents)
  7192. {
  7193. int nativecontents = 0;
  7194. if (supercontents & SUPERCONTENTS_SOLID)
  7195. nativecontents |= CONTENTSQ3_SOLID;
  7196. if (supercontents & SUPERCONTENTS_WATER)
  7197. nativecontents |= CONTENTSQ3_WATER;
  7198. if (supercontents & SUPERCONTENTS_SLIME)
  7199. nativecontents |= CONTENTSQ3_SLIME;
  7200. if (supercontents & SUPERCONTENTS_LAVA)
  7201. nativecontents |= CONTENTSQ3_LAVA;
  7202. if (supercontents & SUPERCONTENTS_BODY)
  7203. nativecontents |= CONTENTSQ3_BODY;
  7204. if (supercontents & SUPERCONTENTS_CORPSE)
  7205. nativecontents |= CONTENTSQ3_CORPSE;
  7206. if (supercontents & SUPERCONTENTS_NODROP)
  7207. nativecontents |= CONTENTSQ3_NODROP;
  7208. if (supercontents & SUPERCONTENTS_PLAYERCLIP)
  7209. nativecontents |= CONTENTSQ3_PLAYERCLIP;
  7210. if (supercontents & SUPERCONTENTS_MONSTERCLIP)
  7211. nativecontents |= CONTENTSQ3_MONSTERCLIP;
  7212. if (supercontents & SUPERCONTENTS_DONOTENTER)
  7213. nativecontents |= CONTENTSQ3_DONOTENTER;
  7214. if (supercontents & SUPERCONTENTS_BOTCLIP)
  7215. nativecontents |= CONTENTSQ3_BOTCLIP;
  7216. if (!(supercontents & SUPERCONTENTS_OPAQUE))
  7217. nativecontents |= CONTENTSQ3_TRANSLUCENT;
  7218. return nativecontents;
  7219. }
  7220. static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
  7221. {
  7222. int numleafs;
  7223. while (node->plane)
  7224. {
  7225. Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
  7226. node = node->children[1];
  7227. }
  7228. numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
  7229. if (loadmodel->brush.num_leafs < numleafs)
  7230. loadmodel->brush.num_leafs = numleafs;
  7231. }
  7232. static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
  7233. {
  7234. int i, j, lumps;
  7235. q3dheader_t *header;
  7236. float corner[3], yawradius, modelradius;
  7237. mod->modeldatatypestring = "Q3BSP";
  7238. mod->type = mod_brushq3;
  7239. mod->brush.ishlbsp = false;
  7240. mod->brush.isbsp2rmqe = false;
  7241. mod->brush.isbsp2 = false;
  7242. mod->brush.isq2bsp = false;
  7243. mod->brush.isq3bsp = true;
  7244. mod->brush.skymasking = true;
  7245. mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
  7246. mod->numskins = 1;
  7247. header = (q3dheader_t *)buffer;
  7248. if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
  7249. Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
  7250. i = LittleLong(header->version);
  7251. if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
  7252. Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
  7253. mod->soundfromcenter = true;
  7254. mod->TraceBox = Mod_Q3BSP_TraceBox;
  7255. mod->TraceBrush = Mod_Q3BSP_TraceBrush;
  7256. mod->TraceLine = Mod_Q3BSP_TraceLine;
  7257. mod->TracePoint = Mod_Q3BSP_TracePoint;
  7258. mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
  7259. mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
  7260. mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
  7261. mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
  7262. mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
  7263. mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
  7264. mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
  7265. mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
  7266. mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
  7267. mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
  7268. mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
  7269. mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
  7270. mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
  7271. mod->brush.AmbientSoundLevelsForPoint = NULL;
  7272. mod->brush.RoundUpToHullSize = NULL;
  7273. mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
  7274. mod->Draw = R_Q1BSP_Draw;
  7275. mod->DrawDepth = R_Q1BSP_DrawDepth;
  7276. mod->DrawDebug = R_Q1BSP_DrawDebug;
  7277. mod->DrawPrepass = R_Q1BSP_DrawPrepass;
  7278. mod->GetLightInfo = R_Q1BSP_GetLightInfo;
  7279. mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
  7280. mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
  7281. mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
  7282. mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
  7283. mod->DrawLight = R_Q1BSP_DrawLight;
  7284. mod_base = (unsigned char *)header;
  7285. // swap all the lumps
  7286. header->ident = LittleLong(header->ident);
  7287. header->version = LittleLong(header->version);
  7288. lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
  7289. for (i = 0;i < lumps;i++)
  7290. {
  7291. j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
  7292. if((char *) bufferend < (char *) buffer + j)
  7293. Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
  7294. j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
  7295. if((char *) bufferend < (char *) buffer + j)
  7296. Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
  7297. }
  7298. /*
  7299. * NO, do NOT clear them!
  7300. * they contain actual data referenced by other stuff.
  7301. * Instead, before using the advertisements lump, check header->versio
  7302. * again!
  7303. * Sorry, but otherwise it breaks memory of the first lump.
  7304. for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
  7305. {
  7306. header->lumps[i].fileofs = 0;
  7307. header->lumps[i].filelen = 0;
  7308. }
  7309. */
  7310. mod->brush.qw_md4sum = 0;
  7311. mod->brush.qw_md4sum2 = 0;
  7312. for (i = 0;i < lumps;i++)
  7313. {
  7314. if (i == Q3LUMP_ENTITIES)
  7315. continue;
  7316. mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
  7317. if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
  7318. continue;
  7319. mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
  7320. // all this checksumming can take a while, so let's send keepalives here too
  7321. CL_KeepaliveMessage(false);
  7322. }
  7323. Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
  7324. Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
  7325. Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
  7326. if (header->version == Q3BSPVERSION_IG)
  7327. Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
  7328. else
  7329. Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
  7330. Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
  7331. Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
  7332. Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
  7333. Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
  7334. Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
  7335. Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
  7336. Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
  7337. Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
  7338. Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
  7339. Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
  7340. Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
  7341. Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
  7342. Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
  7343. loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
  7344. // the MakePortals code works fine on the q3bsp data as well
  7345. if (mod_bsp_portalize.integer)
  7346. Mod_Q1BSP_MakePortals();
  7347. // FIXME: shader alpha should replace r_wateralpha support in q3bsp
  7348. loadmodel->brush.supportwateralpha = true;
  7349. // make a single combined shadow mesh to allow optimized shadow volume creation
  7350. Mod_Q1BSP_CreateShadowMesh(loadmodel);
  7351. loadmodel->brush.num_leafs = 0;
  7352. Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
  7353. if (loadmodel->brush.numsubmodels)
  7354. loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
  7355. mod = loadmodel;
  7356. for (i = 0;i < loadmodel->brush.numsubmodels;i++)
  7357. {
  7358. if (i > 0)
  7359. {
  7360. char name[10];
  7361. // duplicate the basic information
  7362. dpsnprintf(name, sizeof(name), "*%i", i);
  7363. mod = Mod_FindName(name, loadmodel->name);
  7364. // copy the base model to this one
  7365. *mod = *loadmodel;
  7366. // rename the clone back to its proper name
  7367. strlcpy(mod->name, name, sizeof(mod->name));
  7368. mod->brush.parentmodel = loadmodel;
  7369. // textures and memory belong to the main model
  7370. mod->texturepool = NULL;
  7371. mod->mempool = NULL;
  7372. mod->brush.GetPVS = NULL;
  7373. mod->brush.FatPVS = NULL;
  7374. mod->brush.BoxTouchingPVS = NULL;
  7375. mod->brush.BoxTouchingLeafPVS = NULL;
  7376. mod->brush.BoxTouchingVisibleLeafs = NULL;
  7377. mod->brush.FindBoxClusters = NULL;
  7378. mod->brush.LightPoint = NULL;
  7379. mod->brush.AmbientSoundLevelsForPoint = NULL;
  7380. }
  7381. mod->brush.submodel = i;
  7382. if (loadmodel->brush.submodels)
  7383. loadmodel->brush.submodels[i] = mod;
  7384. // make the model surface list (used by shadowing/lighting)
  7385. mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
  7386. mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
  7387. mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
  7388. mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
  7389. mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
  7390. Mod_MakeSortedSurfaces(mod);
  7391. VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
  7392. VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
  7393. // enlarge the bounding box to enclose all geometry of this model,
  7394. // because q3map2 sometimes lies (mostly to affect the lightgrid),
  7395. // which can in turn mess up the farclip (as well as culling when
  7396. // outside the level - an unimportant concern)
  7397. //printf("Editing model %d... BEFORE re-bounding: %f %f %f - %f %f %f\n", i, mod->normalmins[0], mod->normalmins[1], mod->normalmins[2], mod->normalmaxs[0], mod->normalmaxs[1], mod->normalmaxs[2]);
  7398. for (j = 0;j < mod->nummodelsurfaces;j++)
  7399. {
  7400. const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
  7401. const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
  7402. int k;
  7403. if (!surface->num_vertices)
  7404. continue;
  7405. for (k = 0;k < surface->num_vertices;k++, v += 3)
  7406. {
  7407. mod->normalmins[0] = min(mod->normalmins[0], v[0]);
  7408. mod->normalmins[1] = min(mod->normalmins[1], v[1]);
  7409. mod->normalmins[2] = min(mod->normalmins[2], v[2]);
  7410. mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
  7411. mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
  7412. mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
  7413. }
  7414. }
  7415. //printf("Editing model %d... AFTER re-bounding: %f %f %f - %f %f %f\n", i, mod->normalmins[0], mod->normalmins[1], mod->normalmins[2], mod->normalmaxs[0], mod->normalmaxs[1], mod->normalmaxs[2]);
  7416. corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
  7417. corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
  7418. corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
  7419. modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
  7420. yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
  7421. mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
  7422. mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
  7423. mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
  7424. mod->yawmins[0] = mod->yawmins[1] = -yawradius;
  7425. mod->yawmins[2] = mod->normalmins[2];
  7426. mod->yawmaxs[2] = mod->normalmaxs[2];
  7427. mod->radius = modelradius;
  7428. mod->radius2 = modelradius * modelradius;
  7429. // this gets altered below if sky or water is used
  7430. mod->DrawSky = NULL;
  7431. mod->DrawAddWaterPlanes = NULL;
  7432. for (j = 0;j < mod->nummodelsurfaces;j++)
  7433. if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
  7434. break;
  7435. if (j < mod->nummodelsurfaces)
  7436. mod->DrawSky = R_Q1BSP_DrawSky;
  7437. for (j = 0;j < mod->nummodelsurfaces;j++)
  7438. if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
  7439. break;
  7440. if (j < mod->nummodelsurfaces)
  7441. mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
  7442. Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
  7443. Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
  7444. // generate VBOs and other shared data before cloning submodels
  7445. if (i == 0)
  7446. Mod_BuildVBOs();
  7447. }
  7448. if (mod_q3bsp_sRGBlightmaps.integer)
  7449. {
  7450. if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
  7451. {
  7452. // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
  7453. // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
  7454. // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
  7455. // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
  7456. //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
  7457. }
  7458. else // if this is NOT set, regular rendering looks right by this requirement anyway
  7459. {
  7460. /*
  7461. // we want color 1 to do the same as without sRGB
  7462. // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
  7463. loadmodel->lightmapscale *= 2.476923f; // fixes max level
  7464. */
  7465. // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
  7466. // we need to undo that
  7467. loadmodel->lightmapscale *= 2.336f; // fixes neutral level
  7468. }
  7469. }
  7470. Con_DPrintf("Stats for q3bsp model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
  7471. }
  7472. void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
  7473. {
  7474. int i = LittleLong(((int *)buffer)[1]);
  7475. if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
  7476. Mod_Q3BSP_Load(mod,buffer, bufferend);
  7477. else if (i == Q2BSPVERSION)
  7478. Mod_Q2BSP_Load(mod,buffer, bufferend);
  7479. else
  7480. Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
  7481. }
  7482. void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
  7483. {
  7484. Host_Error("Mod_MAP_Load: not yet implemented");
  7485. }
  7486. typedef struct objvertex_s
  7487. {
  7488. int nextindex;
  7489. int submodelindex;
  7490. int textureindex;
  7491. float v[3];
  7492. float vt[2];
  7493. float vn[3];
  7494. }
  7495. objvertex_t;
  7496. static unsigned char nobsp_pvs[1] = {1};
  7497. void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
  7498. {
  7499. const char *textbase = (char *)buffer, *text = textbase;
  7500. char *s;
  7501. char *argv[512];
  7502. char line[1024];
  7503. char materialname[MAX_QPATH];
  7504. int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
  7505. int index1, index2, index3;
  7506. objvertex_t vfirst, vprev, vcurrent;
  7507. int argc;
  7508. int linelen;
  7509. int numtriangles = 0;
  7510. int maxtriangles = 0;
  7511. objvertex_t *vertices = NULL;
  7512. int linenumber = 0;
  7513. int maxtextures = 0, numtextures = 0, textureindex = 0;
  7514. int maxv = 0, numv = 1;
  7515. int maxvt = 0, numvt = 1;
  7516. int maxvn = 0, numvn = 1;
  7517. char *texturenames = NULL;
  7518. float dist, modelradius, modelyawradius, yawradius;
  7519. float *obj_v = NULL;
  7520. float *obj_vt = NULL;
  7521. float *obj_vn = NULL;
  7522. float mins[3];
  7523. float maxs[3];
  7524. float corner[3];
  7525. objvertex_t *thisvertex = NULL;
  7526. int vertexhashindex;
  7527. int *vertexhashtable = NULL;
  7528. objvertex_t *vertexhashdata = NULL;
  7529. objvertex_t *vdata = NULL;
  7530. int vertexhashsize = 0;
  7531. int vertexhashcount = 0;
  7532. skinfile_t *skinfiles = NULL;
  7533. unsigned char *data = NULL;
  7534. int *submodelfirstsurface;
  7535. msurface_t *tempsurface;
  7536. msurface_t *tempsurfaces;
  7537. memset(&vfirst, 0, sizeof(vfirst));
  7538. memset(&vprev, 0, sizeof(vprev));
  7539. memset(&vcurrent, 0, sizeof(vcurrent));
  7540. dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
  7541. loadmodel->modeldatatypestring = "OBJ";
  7542. loadmodel->type = mod_obj;
  7543. loadmodel->soundfromcenter = true;
  7544. loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
  7545. loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
  7546. loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
  7547. loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
  7548. loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
  7549. loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
  7550. loadmodel->brush.TraceLineOfSight = NULL;
  7551. loadmodel->brush.SuperContentsFromNativeContents = NULL;
  7552. loadmodel->brush.NativeContentsFromSuperContents = NULL;
  7553. loadmodel->brush.GetPVS = NULL;
  7554. loadmodel->brush.FatPVS = NULL;
  7555. loadmodel->brush.BoxTouchingPVS = NULL;
  7556. loadmodel->brush.BoxTouchingLeafPVS = NULL;
  7557. loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
  7558. loadmodel->brush.FindBoxClusters = NULL;
  7559. loadmodel->brush.LightPoint = NULL;
  7560. loadmodel->brush.FindNonSolidLocation = NULL;
  7561. loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
  7562. loadmodel->brush.RoundUpToHullSize = NULL;
  7563. loadmodel->brush.PointInLeaf = NULL;
  7564. loadmodel->Draw = R_Q1BSP_Draw;
  7565. loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
  7566. loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
  7567. loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
  7568. loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
  7569. loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
  7570. loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
  7571. loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
  7572. loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
  7573. loadmodel->DrawLight = R_Q1BSP_DrawLight;
  7574. skinfiles = Mod_LoadSkinFiles();
  7575. if (loadmodel->numskins < 1)
  7576. loadmodel->numskins = 1;
  7577. // make skinscenes for the skins (no groups)
  7578. loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
  7579. for (i = 0;i < loadmodel->numskins;i++)
  7580. {
  7581. loadmodel->skinscenes[i].firstframe = i;
  7582. loadmodel->skinscenes[i].framecount = 1;
  7583. loadmodel->skinscenes[i].loop = true;
  7584. loadmodel->skinscenes[i].framerate = 10;
  7585. }
  7586. VectorClear(mins);
  7587. VectorClear(maxs);
  7588. // we always have model 0, i.e. the first "submodel"
  7589. loadmodel->brush.numsubmodels = 1;
  7590. // parse the OBJ text now
  7591. for(;;)
  7592. {
  7593. static char emptyarg[1] = "";
  7594. if (!*text)
  7595. break;
  7596. linenumber++;
  7597. linelen = 0;
  7598. for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
  7599. line[linelen] = text[linelen];
  7600. line[linelen] = 0;
  7601. for (argc = 0;argc < 4;argc++)
  7602. argv[argc] = emptyarg;
  7603. argc = 0;
  7604. s = line;
  7605. while (*s == ' ' || *s == '\t')
  7606. s++;
  7607. while (*s)
  7608. {
  7609. argv[argc++] = s;
  7610. while (*s > ' ')
  7611. s++;
  7612. if (!*s)
  7613. break;
  7614. *s++ = 0;
  7615. while (*s == ' ' || *s == '\t')
  7616. s++;
  7617. }
  7618. text += linelen;
  7619. if (*text == '\r')
  7620. text++;
  7621. if (*text == '\n')
  7622. text++;
  7623. if (!argc)
  7624. continue;
  7625. if (argv[0][0] == '#')
  7626. continue;
  7627. if (!strcmp(argv[0], "v"))
  7628. {
  7629. if (maxv <= numv)
  7630. {
  7631. maxv = max(maxv * 2, 1024);
  7632. obj_v = (float *)Mem_Realloc(tempmempool, obj_v, maxv * sizeof(float[3]));
  7633. }
  7634. if(mod_obj_orientation.integer)
  7635. {
  7636. obj_v[numv*3+0] = atof(argv[1]);
  7637. obj_v[numv*3+2] = atof(argv[2]);
  7638. obj_v[numv*3+1] = atof(argv[3]);
  7639. }
  7640. else
  7641. {
  7642. obj_v[numv*3+0] = atof(argv[1]);
  7643. obj_v[numv*3+1] = atof(argv[2]);
  7644. obj_v[numv*3+2] = atof(argv[3]);
  7645. }
  7646. numv++;
  7647. }
  7648. else if (!strcmp(argv[0], "vt"))
  7649. {
  7650. if (maxvt <= numvt)
  7651. {
  7652. maxvt = max(maxvt * 2, 1024);
  7653. obj_vt = (float *)Mem_Realloc(tempmempool, obj_vt, maxvt * sizeof(float[2]));
  7654. }
  7655. obj_vt[numvt*2+0] = atof(argv[1]);
  7656. obj_vt[numvt*2+1] = 1-atof(argv[2]);
  7657. numvt++;
  7658. }
  7659. else if (!strcmp(argv[0], "vn"))
  7660. {
  7661. if (maxvn <= numvn)
  7662. {
  7663. maxvn = max(maxvn * 2, 1024);
  7664. obj_vn = (float *)Mem_Realloc(tempmempool, obj_vn, maxvn * sizeof(float[3]));
  7665. }
  7666. if(mod_obj_orientation.integer)
  7667. {
  7668. obj_vn[numvn*3+0] = atof(argv[1]);
  7669. obj_vn[numvn*3+2] = atof(argv[2]);
  7670. obj_vn[numvn*3+1] = atof(argv[3]);
  7671. }
  7672. else
  7673. {
  7674. obj_vn[numvn*3+0] = atof(argv[1]);
  7675. obj_vn[numvn*3+1] = atof(argv[2]);
  7676. obj_vn[numvn*3+2] = atof(argv[3]);
  7677. }
  7678. numvn++;
  7679. }
  7680. else if (!strcmp(argv[0], "f"))
  7681. {
  7682. if (!numtextures)
  7683. {
  7684. if (maxtextures <= numtextures)
  7685. {
  7686. maxtextures = max(maxtextures * 2, 256);
  7687. texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
  7688. }
  7689. textureindex = numtextures++;
  7690. strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
  7691. }
  7692. for (j = 1;j < argc;j++)
  7693. {
  7694. index1 = atoi(argv[j]);
  7695. while(argv[j][0] && argv[j][0] != '/')
  7696. argv[j]++;
  7697. if (argv[j][0])
  7698. argv[j]++;
  7699. index2 = atoi(argv[j]);
  7700. while(argv[j][0] && argv[j][0] != '/')
  7701. argv[j]++;
  7702. if (argv[j][0])
  7703. argv[j]++;
  7704. index3 = atoi(argv[j]);
  7705. // negative refers to a recent vertex
  7706. // zero means not specified
  7707. // positive means an absolute vertex index
  7708. if (index1 < 0)
  7709. index1 = numv - index1;
  7710. if (index2 < 0)
  7711. index2 = numvt - index2;
  7712. if (index3 < 0)
  7713. index3 = numvn - index3;
  7714. vcurrent.nextindex = -1;
  7715. vcurrent.textureindex = textureindex;
  7716. vcurrent.submodelindex = submodelindex;
  7717. if (obj_v && index1 >= 0 && index1 < numv)
  7718. VectorCopy(obj_v + 3*index1, vcurrent.v);
  7719. if (obj_vt && index2 >= 0 && index2 < numvt)
  7720. Vector2Copy(obj_vt + 2*index2, vcurrent.vt);
  7721. if (obj_vn && index3 >= 0 && index3 < numvn)
  7722. VectorCopy(obj_vn + 3*index3, vcurrent.vn);
  7723. if (numtriangles == 0)
  7724. {
  7725. VectorCopy(vcurrent.v, mins);
  7726. VectorCopy(vcurrent.v, maxs);
  7727. }
  7728. else
  7729. {
  7730. mins[0] = min(mins[0], vcurrent.v[0]);
  7731. mins[1] = min(mins[1], vcurrent.v[1]);
  7732. mins[2] = min(mins[2], vcurrent.v[2]);
  7733. maxs[0] = max(maxs[0], vcurrent.v[0]);
  7734. maxs[1] = max(maxs[1], vcurrent.v[1]);
  7735. maxs[2] = max(maxs[2], vcurrent.v[2]);
  7736. }
  7737. if (j == 1)
  7738. vfirst = vcurrent;
  7739. else if (j >= 3)
  7740. {
  7741. if (maxtriangles <= numtriangles)
  7742. {
  7743. maxtriangles = max(maxtriangles * 2, 32768);
  7744. vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
  7745. }
  7746. if(mod_obj_orientation.integer)
  7747. {
  7748. vertices[numtriangles*3+0] = vfirst;
  7749. vertices[numtriangles*3+1] = vprev;
  7750. vertices[numtriangles*3+2] = vcurrent;
  7751. }
  7752. else
  7753. {
  7754. vertices[numtriangles*3+0] = vfirst;
  7755. vertices[numtriangles*3+2] = vprev;
  7756. vertices[numtriangles*3+1] = vcurrent;
  7757. }
  7758. numtriangles++;
  7759. }
  7760. vprev = vcurrent;
  7761. }
  7762. }
  7763. else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
  7764. {
  7765. submodelindex = atof(argv[1]);
  7766. loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
  7767. }
  7768. else if (!strcmp(argv[0], "usemtl"))
  7769. {
  7770. for (i = 0;i < numtextures;i++)
  7771. if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
  7772. break;
  7773. if (i < numtextures)
  7774. textureindex = i;
  7775. else
  7776. {
  7777. if (maxtextures <= numtextures)
  7778. {
  7779. maxtextures = max(maxtextures * 2, 256);
  7780. texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
  7781. }
  7782. textureindex = numtextures++;
  7783. strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
  7784. }
  7785. }
  7786. }
  7787. // now that we have the OBJ data loaded as-is, we can convert it
  7788. // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
  7789. VectorCopy(mins, loadmodel->normalmins);
  7790. VectorCopy(maxs, loadmodel->normalmaxs);
  7791. dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
  7792. modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
  7793. modelyawradius = dist*dist+modelyawradius*modelyawradius;
  7794. modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
  7795. modelradius = modelyawradius + modelradius * modelradius;
  7796. modelyawradius = sqrt(modelyawradius);
  7797. modelradius = sqrt(modelradius);
  7798. loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
  7799. loadmodel->yawmins[2] = loadmodel->normalmins[2];
  7800. loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
  7801. loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
  7802. loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
  7803. loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
  7804. loadmodel->radius = modelradius;
  7805. loadmodel->radius2 = modelradius * modelradius;
  7806. // allocate storage for triangles
  7807. loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
  7808. // allocate vertex hash structures to build an optimal vertex subset
  7809. vertexhashsize = numtriangles*2;
  7810. vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
  7811. memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
  7812. vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
  7813. vertexhashcount = 0;
  7814. // gather surface stats for assigning vertex/triangle ranges
  7815. firstvertex = 0;
  7816. firsttriangle = 0;
  7817. elementindex = 0;
  7818. loadmodel->num_surfaces = 0;
  7819. // allocate storage for the worst case number of surfaces, later we resize
  7820. tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
  7821. submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
  7822. tempsurface = tempsurfaces;
  7823. for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
  7824. {
  7825. submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
  7826. for (textureindex = 0;textureindex < numtextures;textureindex++)
  7827. {
  7828. for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
  7829. {
  7830. thisvertex = vertices + vertexindex;
  7831. if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
  7832. break;
  7833. }
  7834. // skip the surface creation if there are no triangles for it
  7835. if (vertexindex == numtriangles*3)
  7836. continue;
  7837. // create a surface for these vertices
  7838. surfacevertices = 0;
  7839. surfaceelements = 0;
  7840. // we hack in a texture index in the surface to be fixed up later...
  7841. tempsurface->texture = (texture_t *)((size_t)textureindex);
  7842. // calculate bounds as we go
  7843. VectorCopy(thisvertex->v, tempsurface->mins);
  7844. VectorCopy(thisvertex->v, tempsurface->maxs);
  7845. for (;vertexindex < numtriangles*3;vertexindex++)
  7846. {
  7847. thisvertex = vertices + vertexindex;
  7848. if (thisvertex->submodelindex != submodelindex)
  7849. continue;
  7850. if (thisvertex->textureindex != textureindex)
  7851. continue;
  7852. // add vertex to surface bounds
  7853. tempsurface->mins[0] = min(tempsurface->mins[0], thisvertex->v[0]);
  7854. tempsurface->mins[1] = min(tempsurface->mins[1], thisvertex->v[1]);
  7855. tempsurface->mins[2] = min(tempsurface->mins[2], thisvertex->v[2]);
  7856. tempsurface->maxs[0] = max(tempsurface->maxs[0], thisvertex->v[0]);
  7857. tempsurface->maxs[1] = max(tempsurface->maxs[1], thisvertex->v[1]);
  7858. tempsurface->maxs[2] = max(tempsurface->maxs[2], thisvertex->v[2]);
  7859. // add the vertex if it is not found in the merged set, and
  7860. // get its index (triangle element) for the surface
  7861. vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
  7862. for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
  7863. {
  7864. vdata = vertexhashdata + i;
  7865. if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
  7866. break;
  7867. }
  7868. if (i < 0)
  7869. {
  7870. i = vertexhashcount++;
  7871. vdata = vertexhashdata + i;
  7872. *vdata = *thisvertex;
  7873. vdata->nextindex = vertexhashtable[vertexhashindex];
  7874. vertexhashtable[vertexhashindex] = i;
  7875. surfacevertices++;
  7876. }
  7877. loadmodel->surfmesh.data_element3i[elementindex++] = i;
  7878. surfaceelements++;
  7879. }
  7880. surfacetriangles = surfaceelements / 3;
  7881. tempsurface->num_vertices = surfacevertices;
  7882. tempsurface->num_triangles = surfacetriangles;
  7883. tempsurface->num_firstvertex = firstvertex;
  7884. tempsurface->num_firsttriangle = firsttriangle;
  7885. firstvertex += tempsurface->num_vertices;
  7886. firsttriangle += tempsurface->num_triangles;
  7887. tempsurface++;
  7888. loadmodel->num_surfaces++;
  7889. }
  7890. }
  7891. submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
  7892. numvertices = firstvertex;
  7893. loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
  7894. tempsurfaces = NULL;
  7895. // allocate storage for final mesh data
  7896. loadmodel->num_textures = numtextures * loadmodel->numskins;
  7897. loadmodel->num_texturesperskin = numtextures;
  7898. data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + numtriangles * sizeof(int[3]) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0) + (r_enableshadowvolumes.integer ? numtriangles * sizeof(int[3]) : 0) + numvertices * sizeof(float[14]) + loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
  7899. loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
  7900. loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
  7901. loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
  7902. loadmodel->surfmesh.num_vertices = numvertices;
  7903. loadmodel->surfmesh.num_triangles = numtriangles;
  7904. if (r_enableshadowvolumes.integer)
  7905. loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
  7906. loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
  7907. loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
  7908. loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
  7909. loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
  7910. loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
  7911. if (loadmodel->surfmesh.num_vertices <= 65536) {
  7912. loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
  7913. }
  7914. for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
  7915. {
  7916. VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
  7917. VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
  7918. Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
  7919. }
  7920. // load the textures
  7921. for (textureindex = 0;textureindex < numtextures;textureindex++)
  7922. Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
  7923. Mod_FreeSkinFiles(skinfiles);
  7924. // set the surface textures to their real values now that we loaded them...
  7925. for (i = 0;i < loadmodel->num_surfaces;i++)
  7926. loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
  7927. // free data
  7928. Mem_Free(vertices);
  7929. Mem_Free(texturenames);
  7930. Mem_Free(obj_v);
  7931. Mem_Free(obj_vt);
  7932. Mem_Free(obj_vn);
  7933. Mem_Free(vertexhashtable);
  7934. Mem_Free(vertexhashdata);
  7935. // make a single combined shadow mesh to allow optimized shadow volume creation
  7936. Mod_Q1BSP_CreateShadowMesh(loadmodel);
  7937. // compute all the mesh information that was not loaded from the file
  7938. if (loadmodel->surfmesh.data_element3s)
  7939. for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
  7940. loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
  7941. Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
  7942. // generate normals if the file did not have them
  7943. if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
  7944. Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, r_smoothnormals_areaweighting.integer != 0);
  7945. Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
  7946. if (loadmodel->surfmesh.data_neighbor3i)
  7947. Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
  7948. // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
  7949. loadmodel->brush.num_visleafs = 1;
  7950. loadmodel->brush.num_leafs = 1;
  7951. loadmodel->brush.num_nodes = 0;
  7952. loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
  7953. loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
  7954. loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
  7955. loadmodel->brush.num_pvsclusters = 1;
  7956. loadmodel->brush.num_pvsclusterbytes = 1;
  7957. loadmodel->brush.data_pvsclusters = nobsp_pvs;
  7958. //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
  7959. //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
  7960. loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
  7961. VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
  7962. VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
  7963. loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
  7964. loadmodel->brush.data_leafs->clusterindex = 0;
  7965. loadmodel->brush.data_leafs->areaindex = 0;
  7966. loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
  7967. loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
  7968. loadmodel->brush.data_leafs->numleafbrushes = 0;
  7969. loadmodel->brush.data_leafs->firstleafbrush = NULL;
  7970. loadmodel->brush.supportwateralpha = true;
  7971. if (loadmodel->brush.numsubmodels)
  7972. loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
  7973. mod = loadmodel;
  7974. for (i = 0;i < loadmodel->brush.numsubmodels;i++)
  7975. {
  7976. if (i > 0)
  7977. {
  7978. char name[10];
  7979. // duplicate the basic information
  7980. dpsnprintf(name, sizeof(name), "*%i", i);
  7981. mod = Mod_FindName(name, loadmodel->name);
  7982. // copy the base model to this one
  7983. *mod = *loadmodel;
  7984. // rename the clone back to its proper name
  7985. strlcpy(mod->name, name, sizeof(mod->name));
  7986. mod->brush.parentmodel = loadmodel;
  7987. // textures and memory belong to the main model
  7988. mod->texturepool = NULL;
  7989. mod->mempool = NULL;
  7990. mod->brush.GetPVS = NULL;
  7991. mod->brush.FatPVS = NULL;
  7992. mod->brush.BoxTouchingPVS = NULL;
  7993. mod->brush.BoxTouchingLeafPVS = NULL;
  7994. mod->brush.BoxTouchingVisibleLeafs = NULL;
  7995. mod->brush.FindBoxClusters = NULL;
  7996. mod->brush.LightPoint = NULL;
  7997. mod->brush.AmbientSoundLevelsForPoint = NULL;
  7998. }
  7999. mod->brush.submodel = i;
  8000. if (loadmodel->brush.submodels)
  8001. loadmodel->brush.submodels[i] = mod;
  8002. // make the model surface list (used by shadowing/lighting)
  8003. mod->firstmodelsurface = submodelfirstsurface[i];
  8004. mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
  8005. mod->firstmodelbrush = 0;
  8006. mod->nummodelbrushes = 0;
  8007. mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
  8008. Mod_MakeSortedSurfaces(mod);
  8009. VectorClear(mod->normalmins);
  8010. VectorClear(mod->normalmaxs);
  8011. l = false;
  8012. for (j = 0;j < mod->nummodelsurfaces;j++)
  8013. {
  8014. const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
  8015. const float *v3f = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
  8016. int k;
  8017. if (!surface->num_vertices)
  8018. continue;
  8019. if (!l)
  8020. {
  8021. l = true;
  8022. VectorCopy(v3f, mod->normalmins);
  8023. VectorCopy(v3f, mod->normalmaxs);
  8024. }
  8025. for (k = 0;k < surface->num_vertices;k++, v3f += 3)
  8026. {
  8027. mod->normalmins[0] = min(mod->normalmins[0], v3f[0]);
  8028. mod->normalmins[1] = min(mod->normalmins[1], v3f[1]);
  8029. mod->normalmins[2] = min(mod->normalmins[2], v3f[2]);
  8030. mod->normalmaxs[0] = max(mod->normalmaxs[0], v3f[0]);
  8031. mod->normalmaxs[1] = max(mod->normalmaxs[1], v3f[1]);
  8032. mod->normalmaxs[2] = max(mod->normalmaxs[2], v3f[2]);
  8033. }
  8034. }
  8035. corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
  8036. corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
  8037. corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
  8038. modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
  8039. yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
  8040. mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
  8041. mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
  8042. mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
  8043. mod->yawmins[0] = mod->yawmins[1] = -yawradius;
  8044. mod->yawmins[2] = mod->normalmins[2];
  8045. mod->yawmaxs[2] = mod->normalmaxs[2];
  8046. mod->radius = modelradius;
  8047. mod->radius2 = modelradius * modelradius;
  8048. // this gets altered below if sky or water is used
  8049. mod->DrawSky = NULL;
  8050. mod->DrawAddWaterPlanes = NULL;
  8051. for (j = 0;j < mod->nummodelsurfaces;j++)
  8052. if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
  8053. break;
  8054. if (j < mod->nummodelsurfaces)
  8055. mod->DrawSky = R_Q1BSP_DrawSky;
  8056. for (j = 0;j < mod->nummodelsurfaces;j++)
  8057. if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
  8058. break;
  8059. if (j < mod->nummodelsurfaces)
  8060. mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
  8061. Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
  8062. mod->render_bih = mod->collision_bih;
  8063. // generate VBOs and other shared data before cloning submodels
  8064. if (i == 0)
  8065. Mod_BuildVBOs();
  8066. }
  8067. mod = loadmodel;
  8068. Mem_Free(submodelfirstsurface);
  8069. Con_DPrintf("Stats for obj model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
  8070. }