added r_sortsurfaces cvar, default off, sorting them seems to be a very minor slowdow...
[divverent/darkplaces.git] / model_alias.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20
21 #include "quakedef.h"
22
23 static cvar_t r_mipskins = {CVAR_SAVE, "r_mipskins", "0"};
24
25 void Mod_AliasInit (void)
26 {
27         Cvar_RegisterVariable(&r_mipskins);
28 }
29
30 // LordHavoc: proper bounding box considerations
31 static float aliasbboxmin[3], aliasbboxmax[3], modelyawradius, modelradius;
32
33 static float vertst[MAXALIASVERTS][2];
34 static int vertusage[MAXALIASVERTS];
35 static int vertonseam[MAXALIASVERTS];
36 static int vertremap[MAXALIASVERTS];
37 static int temptris[MAXALIASTRIS][3];
38
39 static void Mod_ConvertAliasVerts (int inverts, vec3_t scale, vec3_t translate, trivertx_t *v, trivertx_t *out)
40 {
41         int i, j, invalidnormals = 0;
42         float dist;
43         vec3_t temp;
44         for (i = 0;i < inverts;i++)
45         {
46                 if (vertremap[i] < 0 && vertremap[i+inverts] < 0) // only used vertices need apply...
47                         continue;
48
49                 temp[0] = v[i].v[0] * scale[0] + translate[0];
50                 temp[1] = v[i].v[1] * scale[1] + translate[1];
51                 temp[2] = v[i].v[2] * scale[2] + translate[2];
52                 // update bounding box
53                 if (temp[0] < aliasbboxmin[0]) aliasbboxmin[0] = temp[0];
54                 if (temp[1] < aliasbboxmin[1]) aliasbboxmin[1] = temp[1];
55                 if (temp[2] < aliasbboxmin[2]) aliasbboxmin[2] = temp[2];
56                 if (temp[0] > aliasbboxmax[0]) aliasbboxmax[0] = temp[0];
57                 if (temp[1] > aliasbboxmax[1]) aliasbboxmax[1] = temp[1];
58                 if (temp[2] > aliasbboxmax[2]) aliasbboxmax[2] = temp[2];
59                 dist = temp[0]*temp[0]+temp[1]*temp[1];
60                 if (modelyawradius < dist)
61                         modelyawradius = dist;
62                 dist += temp[2]*temp[2];
63                 if (modelradius < dist)
64                         modelradius = dist;
65
66                 j = vertremap[i]; // not onseam
67                 if (j >= 0)
68                 {
69                         VectorCopy(v[i].v, out[j].v);
70                         out[j].lightnormalindex = v[i].lightnormalindex;
71                         if (out[j].lightnormalindex >= NUMVERTEXNORMALS)
72                         {
73                                 invalidnormals++;
74                                 out[j].lightnormalindex = 0;
75                         }
76                 }
77                 j = vertremap[i+inverts]; // onseam
78                 if (j >= 0)
79                 {
80                         VectorCopy(v[i].v, out[j].v);
81                         out[j].lightnormalindex = v[i].lightnormalindex;
82                         if (out[j].lightnormalindex >= NUMVERTEXNORMALS)
83                         {
84                                 invalidnormals++;
85                                 out[j].lightnormalindex = 0;
86                         }
87                 }
88         }
89         if (invalidnormals)
90                 Con_Printf("Mod_ConvertAliasVerts: \"%s\", %i invalid normal indices found\n", loadmodel->name, invalidnormals);
91 }
92
93 static void Mod_MDL_LoadFrames (qbyte * datapointer, int inverts, int outverts, vec3_t scale, vec3_t translate)
94 {
95         daliasframetype_t       *pframetype;
96         daliasframe_t           *pinframe;
97         daliasgroup_t           *group;
98         daliasinterval_t        *intervals;
99         int                                     i, f, pose, groupframes;
100         float                           interval;
101         animscene_t                     *scene;
102         pose = 0;
103         scene = loadmodel->animscenes;
104         for (f = 0;f < loadmodel->numframes;f++)
105         {
106                 pframetype = (daliasframetype_t *)datapointer;
107                 datapointer += sizeof(daliasframetype_t);
108                 if (LittleLong (pframetype->type) == ALIAS_SINGLE)
109                 {
110                         // a single frame is still treated as a group
111                         interval = 0.1f;
112                         groupframes = 1;
113                 }
114                 else
115                 {
116                         // read group header
117                         group = (daliasgroup_t *)datapointer;
118                         datapointer += sizeof(daliasgroup_t);
119                         groupframes = LittleLong (group->numframes);
120
121                         // intervals (time per frame)
122                         intervals = (daliasinterval_t *)datapointer;
123                         datapointer += sizeof(daliasinterval_t) * groupframes;
124
125                         interval = LittleFloat (intervals->interval); // FIXME: support variable framerate groups
126                         if (interval < 0.01f)
127                                 Host_Error("Mod_LoadAliasGroup: invalid interval");
128                 }
129
130                 // get scene name from first frame
131                 pinframe = (daliasframe_t *)datapointer;
132
133                 strcpy(scene->name, pinframe->name);
134                 scene->firstframe = pose;
135                 scene->framecount = groupframes;
136                 scene->framerate = 1.0f / interval;
137                 scene->loop = true;
138                 scene++;
139
140                 // read frames
141                 for (i = 0;i < groupframes;i++)
142                 {
143                         pinframe = (daliasframe_t *)datapointer;
144                         datapointer += sizeof(daliasframe_t);
145
146                         // convert to MD2 frame headers
147                         strcpy(loadmodel->mdlmd2data_frames[pose].name, pinframe->name);
148                         VectorCopy(scale, loadmodel->mdlmd2data_frames[pose].scale);
149                         VectorCopy(translate, loadmodel->mdlmd2data_frames[pose].translate);
150
151                         Mod_ConvertAliasVerts(inverts, scale, translate, (trivertx_t *)datapointer, loadmodel->mdlmd2data_pose + pose * outverts);
152                         datapointer += sizeof(trivertx_t) * inverts;
153                         pose++;
154                 }
155         }
156 }
157
158 static rtexture_t *GL_SkinSplitShirt(qbyte *in, qbyte *out, int width, int height, int bits, char *name, int precache)
159 {
160         int i, pixels, passed;
161         qbyte pixeltest[16];
162         for (i = 0;i < 16;i++)
163                 pixeltest[i] = (bits & (1 << i)) != 0;
164         pixels = width*height;
165         passed = 0;
166         while(pixels--)
167         {
168                 if (pixeltest[*in >> 4] && *in != 0 && *in != 255)
169                 {
170                         passed++;
171                         // turn to white while copying
172                         if (*in >= 128 && *in < 224) // backwards ranges
173                                 *out = (*in & 15) ^ 15;
174                         else
175                                 *out = *in & 15;
176                 }
177                 else
178                         *out = 0;
179                 in++;
180                 out++;
181         }
182         if (passed)
183                 return R_LoadTexture (loadmodel->texturepool, name, width, height, out - width*height, TEXTYPE_QPALETTE, (r_mipskins.integer ? TEXF_MIPMAP : 0) | (precache ? TEXF_PRECACHE : 0));
184         else
185                 return NULL;
186 }
187
188 static rtexture_t *GL_SkinSplit(qbyte *in, qbyte *out, int width, int height, int bits, char *name, int precache)
189 {
190         int i, pixels, passed;
191         qbyte pixeltest[16];
192         for (i = 0;i < 16;i++)
193                 pixeltest[i] = (bits & (1 << i)) != 0;
194         pixels = width*height;
195         passed = 0;
196         while(pixels--)
197         {
198                 if (pixeltest[*in >> 4] && *in != 0 && *in != 255)
199                 {
200                         passed++;
201                         *out = *in;
202                 }
203                 else
204                         *out = 0;
205                 in++;
206                 out++;
207         }
208         if (passed)
209                 return R_LoadTexture (loadmodel->texturepool, name, width, height, out - width*height, TEXTYPE_QPALETTE, (r_mipskins.integer ? TEXF_MIPMAP : 0) | (precache ? TEXF_PRECACHE : 0));
210         else
211                 return NULL;
212 }
213
214 static void Mod_LoadSkin (char *basename, qbyte *skindata, qbyte *skintemp, int width, int height, skinframe_t *skinframe, int precache)
215 {
216         skinframe->base   = loadtextureimagewithmask(loadmodel->texturepool, va("%s_normal", basename), 0, 0, false, r_mipskins.integer, precache);
217         skinframe->fog    = image_masktex;
218         skinframe->pants  = NULL;
219         skinframe->shirt  = NULL;
220         skinframe->glow   = loadtextureimage(loadmodel->texturepool, va("%s_glow"  , basename), 0, 0, false, r_mipskins.integer, precache);
221         skinframe->merged = NULL;
222         if (skinframe->base)
223         {
224                 skinframe->pants  = loadtextureimage(loadmodel->texturepool, va("%s_pants" , basename), 0, 0, false, r_mipskins.integer, precache);
225                 skinframe->shirt  = loadtextureimage(loadmodel->texturepool, va("%s_shirt" , basename), 0, 0, false, r_mipskins.integer, precache);
226         }
227         else
228         {
229                 skinframe->base   = loadtextureimagewithmask(loadmodel->texturepool, basename, 0, 0, false, true, true);
230                 skinframe->fog    = image_masktex;
231                 if (!skinframe->base)
232                 {
233                         skinframe->pants  = GL_SkinSplitShirt(skindata, skintemp, width, height, 0x0040, va("%s_pants", basename), false); // pants
234                         skinframe->shirt  = GL_SkinSplitShirt(skindata, skintemp, width, height, 0x0002, va("%s_shirt", basename), false); // shirt
235                         skinframe->glow   = GL_SkinSplit     (skindata, skintemp, width, height, 0xC000, va("%s_glow", basename), precache); // glow
236                         if (skinframe->pants || skinframe->shirt)
237                         {
238                                 skinframe->base   = GL_SkinSplit (skindata, skintemp, width, height, 0x3FBD, va("%s_normal", basename), false); // normal (no special colors)
239                                 skinframe->merged = GL_SkinSplit (skindata, skintemp, width, height, 0x3FFF, va("%s_body", basename), precache); // body (normal + pants + shirt, but not glow)
240                         }
241                         else
242                                 skinframe->base   = GL_SkinSplit (skindata, skintemp, width, height, 0x3FFF, va("%s_base", basename), precache); // no special colors
243                         // quake model skins don't have alpha
244                         skinframe->fog = NULL;
245                 }
246         }
247 }
248
249 #define BOUNDI(VALUE,MIN,MAX) if (VALUE < MIN || VALUE >= MAX) Host_Error("model %s has an invalid ##VALUE (%d exceeds %d - %d)\n", loadmodel->name, VALUE, MIN, MAX);
250 #define BOUNDF(VALUE,MIN,MAX) if (VALUE < MIN || VALUE >= MAX) Host_Error("model %s has an invalid ##VALUE (%f exceeds %f - %f)\n", loadmodel->name, VALUE, MIN, MAX);
251 void Mod_LoadAliasModel (model_t *mod, void *buffer)
252 {
253         int                                             i, j, version, numverts, totalposes, totalskins, skinwidth, skinheight, totalverts, groupframes, groupskins;
254         mdl_t                                   *pinmodel;
255         stvert_t                                *pinstverts;
256         dtriangle_t                             *pintriangles;
257         daliasskintype_t                *pinskintype;
258         daliasskingroup_t               *pinskingroup;
259         daliasskininterval_t    *pinskinintervals;
260         daliasframetype_t               *pinframetype;
261         daliasgroup_t                   *pinframegroup;
262         float                                   scales, scalet, scale[3], translate[3], interval;
263         qbyte                                   *datapointer, *startframes, *startskins;
264         char                                    name[MAX_QPATH];
265         qbyte                                   *skintemp = NULL;
266         modelyawradius = 0;
267         modelradius = 0;
268
269         datapointer = buffer;
270         pinmodel = (mdl_t *)datapointer;
271         datapointer += sizeof(mdl_t);
272
273         version = LittleLong (pinmodel->version);
274         if (version != ALIAS_VERSION)
275                 Host_Error ("%s has wrong version number (%i should be %i)",
276                                  loadmodel->name, version, ALIAS_VERSION);
277
278         loadmodel->type = mod_alias;
279         loadmodel->aliastype = ALIASTYPE_MDLMD2;
280
281         loadmodel->numskins = LittleLong(pinmodel->numskins);
282         BOUNDI(loadmodel->numskins,0,256);
283         skinwidth = LittleLong (pinmodel->skinwidth);
284         BOUNDI(skinwidth,0,4096);
285         skinheight = LittleLong (pinmodel->skinheight);
286         BOUNDI(skinheight,0,4096);
287         loadmodel->numverts = numverts = LittleLong(pinmodel->numverts);
288         BOUNDI(loadmodel->numverts,0,MAXALIASVERTS);
289         loadmodel->numtris = LittleLong(pinmodel->numtris);
290         BOUNDI(loadmodel->numtris,0,MAXALIASTRIS);
291         loadmodel->numframes = LittleLong(pinmodel->numframes);
292         BOUNDI(loadmodel->numframes,0,65536);
293         loadmodel->synctype = LittleLong (pinmodel->synctype);
294         BOUNDI(loadmodel->synctype,0,2);
295         loadmodel->flags = LittleLong (pinmodel->flags);
296
297         for (i = 0;i < 3;i++)
298         {
299                 scale[i] = LittleFloat (pinmodel->scale[i]);
300                 translate[i] = LittleFloat (pinmodel->scale_origin[i]);
301         }
302
303         startskins = datapointer;
304         totalskins = 0;
305         for (i = 0;i < loadmodel->numskins;i++)
306         {
307                 pinskintype = (daliasskintype_t *)datapointer;
308                 datapointer += sizeof(daliasskintype_t);
309                 if (LittleLong(pinskintype->type) == ALIAS_SKIN_SINGLE)
310                         groupskins = 1;
311                 else
312                 {
313                         pinskingroup = (daliasskingroup_t *)datapointer;
314                         datapointer += sizeof(daliasskingroup_t);
315                         groupskins = LittleLong(pinskingroup->numskins);
316                         datapointer += sizeof(daliasskininterval_t) * groupskins;
317                 }
318
319                 for (j = 0;j < groupskins;j++)
320                 {
321                         datapointer += skinwidth * skinheight;
322                         totalskins++;
323                 }
324         }
325
326         pinstverts = (stvert_t *)datapointer;
327         datapointer += sizeof(stvert_t) * numverts;
328
329         pintriangles = (dtriangle_t *)datapointer;
330         datapointer += sizeof(dtriangle_t) * loadmodel->numtris;
331
332         startframes = datapointer;
333         totalposes = 0;
334         for (i = 0;i < loadmodel->numframes;i++)
335         {
336                 pinframetype = (daliasframetype_t *)datapointer;
337                 datapointer += sizeof(daliasframetype_t);
338                 if (LittleLong (pinframetype->type) == ALIAS_SINGLE)
339                         groupframes = 1;
340                 else
341                 {
342                         pinframegroup = (daliasgroup_t *)datapointer;
343                         datapointer += sizeof(daliasgroup_t);
344                         groupframes = LittleLong(pinframegroup->numframes);
345                         datapointer += sizeof(daliasinterval_t) * groupframes;
346                 }
347
348                 for (j = 0;j < groupframes;j++)
349                 {
350                         datapointer += sizeof(daliasframe_t);
351                         datapointer += sizeof(trivertx_t) * numverts;
352                         totalposes++;
353                 }
354         }
355
356         // load the skins
357         skintemp = Mem_Alloc(tempmempool, skinwidth * skinheight);
358         loadmodel->skinscenes = Mem_Alloc(loadmodel->mempool, loadmodel->numskins * sizeof(animscene_t));
359         loadmodel->skinframes = Mem_Alloc(loadmodel->mempool, totalskins * sizeof(skinframe_t));
360         totalskins = 0;
361         datapointer = startskins;
362         for (i = 0;i < loadmodel->numskins;i++)
363         {
364                 pinskintype = (daliasskintype_t *)datapointer;
365                 datapointer += sizeof(daliasskintype_t);
366
367                 if (pinskintype->type == ALIAS_SKIN_SINGLE)
368                 {
369                         groupskins = 1;
370                         interval = 0.1f;
371                 }
372                 else
373                 {
374                         pinskingroup = (daliasskingroup_t *)datapointer;
375                         datapointer += sizeof(daliasskingroup_t);
376
377                         groupskins = LittleLong (pinskingroup->numskins);
378
379                         pinskinintervals = (daliasskininterval_t *)datapointer;
380                         datapointer += sizeof(daliasskininterval_t) * groupskins;
381
382                         interval = LittleFloat(pinskinintervals[0].interval);
383                         if (interval < 0.01f)
384                                 Host_Error("Mod_LoadAliasModel: invalid interval\n");
385                 }
386
387                 sprintf(loadmodel->skinscenes[i].name, "skin %i", i);
388                 loadmodel->skinscenes[i].firstframe = totalskins;
389                 loadmodel->skinscenes[i].framecount = groupskins;
390                 loadmodel->skinscenes[i].framerate = 1.0f / interval;
391                 loadmodel->skinscenes[i].loop = true;
392
393                 for (j = 0;j < groupskins;j++)
394                 {
395                         if (groupskins > 1)
396                                 sprintf (name, "%s_%i_%i", loadmodel->name, i, j);
397                         else
398                                 sprintf (name, "%s_%i", loadmodel->name, i);
399                         Mod_LoadSkin(name, (qbyte *)datapointer, skintemp, skinwidth, skinheight, loadmodel->skinframes + totalskins, i == 0);
400                         datapointer += skinwidth * skinheight;
401                         totalskins++;
402                 }
403         }
404         Mem_Free(skintemp);
405
406         // store texture coordinates into temporary array, they will be stored after usage is determined (triangle data)
407         scales = 1.0 / skinwidth;
408         scalet = 1.0 / skinheight;
409         for (i = 0;i < numverts;i++)
410         {
411                 vertonseam[i] = LittleLong(pinstverts[i].onseam);
412                 vertst[i][0] = LittleLong(pinstverts[i].s) * scales;
413                 vertst[i][1] = LittleLong(pinstverts[i].t) * scalet;
414                 vertst[i+numverts][0] = vertst[i][0] + 0.5;
415                 vertst[i+numverts][1] = vertst[i][1];
416                 vertusage[i] = 0;
417                 vertusage[i+numverts] = 0;
418         }
419
420 // load triangle data
421         loadmodel->mdlmd2data_indices = Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * loadmodel->numtris);
422
423         // count the vertices used
424         for (i = 0;i < numverts*2;i++)
425                 vertusage[i] = 0;
426         for (i = 0;i < loadmodel->numtris;i++)
427         {
428                 temptris[i][0] = LittleLong(pintriangles[i].vertindex[0]);
429                 temptris[i][1] = LittleLong(pintriangles[i].vertindex[1]);
430                 temptris[i][2] = LittleLong(pintriangles[i].vertindex[2]);
431                 if (!LittleLong(pintriangles[i].facesfront)) // backface
432                 {
433                         if (vertonseam[temptris[i][0]]) temptris[i][0] += numverts;
434                         if (vertonseam[temptris[i][1]]) temptris[i][1] += numverts;
435                         if (vertonseam[temptris[i][2]]) temptris[i][2] += numverts;
436                 }
437                 vertusage[temptris[i][0]]++;
438                 vertusage[temptris[i][1]]++;
439                 vertusage[temptris[i][2]]++;
440         }
441         // build remapping table and compact array
442         totalverts = 0;
443         for (i = 0;i < numverts*2;i++)
444         {
445                 if (vertusage[i])
446                 {
447                         vertremap[i] = totalverts;
448                         vertst[totalverts][0] = vertst[i][0];
449                         vertst[totalverts][1] = vertst[i][1];
450                         totalverts++;
451                 }
452                 else
453                         vertremap[i] = -1; // not used at all
454         }
455         loadmodel->numverts = totalverts;
456         // remap the triangle references
457         for (i = 0;i < loadmodel->numtris;i++)
458         {
459                 loadmodel->mdlmd2data_indices[i*3+0] = vertremap[temptris[i][0]];
460                 loadmodel->mdlmd2data_indices[i*3+1] = vertremap[temptris[i][1]];
461                 loadmodel->mdlmd2data_indices[i*3+2] = vertremap[temptris[i][2]];
462         }
463         // store the texture coordinates
464         loadmodel->mdlmd2data_texcoords = Mem_Alloc(loadmodel->mempool, sizeof(float[2]) * totalverts);
465         for (i = 0;i < totalverts;i++)
466         {
467                 loadmodel->mdlmd2data_texcoords[i*2+0] = vertst[i][0];
468                 loadmodel->mdlmd2data_texcoords[i*2+1] = vertst[i][1];
469         }
470
471 // load the frames
472         loadmodel->animscenes = Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numframes);
473         loadmodel->mdlmd2data_frames = Mem_Alloc(loadmodel->mempool, sizeof(md2frame_t) * totalposes);
474         loadmodel->mdlmd2data_pose = Mem_Alloc(loadmodel->mempool, sizeof(trivertx_t) * totalposes * totalverts);
475
476         // LordHavoc: doing proper bbox for model
477         aliasbboxmin[0] = aliasbboxmin[1] = aliasbboxmin[2] = 1000000000;
478         aliasbboxmax[0] = aliasbboxmax[1] = aliasbboxmax[2] = -1000000000;
479
480         Mod_MDL_LoadFrames (startframes, numverts, totalverts, scale, translate);
481
482         modelyawradius = sqrt(modelyawradius);
483         modelradius = sqrt(modelradius);
484         for (j = 0;j < 3;j++)
485         {
486                 loadmodel->normalmins[j] = aliasbboxmin[j];
487                 loadmodel->normalmaxs[j] = aliasbboxmax[j];
488                 loadmodel->rotatedmins[j] = -modelradius;
489                 loadmodel->rotatedmaxs[j] = modelradius;
490         }
491         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -(loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius);
492         loadmodel->yawmins[2] = loadmodel->normalmins[2];
493         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
494
495         loadmodel->Draw = R_DrawAliasModel;
496         loadmodel->DrawSky = NULL;
497         loadmodel->DrawShadow = NULL;
498 }
499
500 static void Mod_MD2_ConvertVerts (vec3_t scale, vec3_t translate, trivertx_t *v, trivertx_t *out, int *vertremap)
501 {
502         int i, invalidnormals = 0;
503         float dist;
504         trivertx_t *in;
505         vec3_t temp;
506         for (i = 0;i < loadmodel->numverts;i++)
507         {
508                 in = v + vertremap[i];
509                 VectorCopy(in->v, out[i].v);
510                 temp[0] = in->v[0] * scale[0] + translate[0];
511                 temp[1] = in->v[1] * scale[1] + translate[1];
512                 temp[2] = in->v[2] * scale[2] + translate[2];
513                 // update bounding box
514                 if (temp[0] < aliasbboxmin[0]) aliasbboxmin[0] = temp[0];
515                 if (temp[1] < aliasbboxmin[1]) aliasbboxmin[1] = temp[1];
516                 if (temp[2] < aliasbboxmin[2]) aliasbboxmin[2] = temp[2];
517                 if (temp[0] > aliasbboxmax[0]) aliasbboxmax[0] = temp[0];
518                 if (temp[1] > aliasbboxmax[1]) aliasbboxmax[1] = temp[1];
519                 if (temp[2] > aliasbboxmax[2]) aliasbboxmax[2] = temp[2];
520                 dist = temp[0]*temp[0]+temp[1]*temp[1];
521                 if (modelyawradius < dist)
522                         modelyawradius = dist;
523                 dist += temp[2]*temp[2];
524                 if (modelradius < dist)
525                         modelradius = dist;
526                 out[i].lightnormalindex = in->lightnormalindex;
527                 if (out[i].lightnormalindex >= NUMVERTEXNORMALS)
528                 {
529                         invalidnormals++;
530                         out[i].lightnormalindex = 0;
531                 }
532         }
533         if (invalidnormals)
534                 Con_Printf("Mod_MD2_ConvertVerts: \"%s\", %i invalid normal indices found\n", loadmodel->name, invalidnormals);
535 }
536
537 void Mod_LoadQ2AliasModel (model_t *mod, void *buffer)
538 {
539         int *vertremap;
540         md2_t *pinmodel;
541         qbyte *base;
542         int version, end;
543         int i, j, k, hashindex, num, numxyz, numst, xyz, st;
544         float *stverts, s, t;
545         struct md2verthash_s
546         {
547                 struct md2verthash_s *next;
548                 int xyz;
549                 float st[2];
550         }
551         *hash, **md2verthash, *md2verthashdata;
552         qbyte *datapointer;
553         md2frame_t *pinframe;
554         char *inskin;
555         md2triangle_t *intri;
556         unsigned short *inst;
557         int skinwidth, skinheight;
558
559         pinmodel = buffer;
560         base = buffer;
561
562         version = LittleLong (pinmodel->version);
563         if (version != MD2ALIAS_VERSION)
564                 Host_Error ("%s has wrong version number (%i should be %i)",
565                         loadmodel->name, version, MD2ALIAS_VERSION);
566
567         loadmodel->type = mod_alias;
568         loadmodel->aliastype = ALIASTYPE_MDLMD2;
569         loadmodel->Draw = R_DrawAliasModel;
570         loadmodel->DrawSky = NULL;
571         loadmodel->DrawShadow = NULL;
572
573         if (LittleLong(pinmodel->num_tris < 1) || LittleLong(pinmodel->num_tris) > MD2MAX_TRIANGLES)
574                 Host_Error ("%s has invalid number of triangles: %i", loadmodel->name, LittleLong(pinmodel->num_tris));
575         if (LittleLong(pinmodel->num_xyz < 1) || LittleLong(pinmodel->num_xyz) > MD2MAX_VERTS)
576                 Host_Error ("%s has invalid number of vertices: %i", loadmodel->name, LittleLong(pinmodel->num_xyz));
577         if (LittleLong(pinmodel->num_frames < 1) || LittleLong(pinmodel->num_frames) > MD2MAX_FRAMES)
578                 Host_Error ("%s has invalid number of frames: %i", loadmodel->name, LittleLong(pinmodel->num_frames));
579         if (LittleLong(pinmodel->num_skins < 0) || LittleLong(pinmodel->num_skins) > MAX_SKINS)
580                 Host_Error ("%s has invalid number of skins: %i", loadmodel->name, LittleLong(pinmodel->num_skins));
581
582         end = LittleLong(pinmodel->ofs_end);
583         if (LittleLong(pinmodel->num_skins) >= 1 && (LittleLong(pinmodel->ofs_skins <= 0) || LittleLong(pinmodel->ofs_skins) >= end))
584                 Host_Error ("%s is not a valid model", loadmodel->name);
585         if (LittleLong(pinmodel->ofs_st <= 0) || LittleLong(pinmodel->ofs_st) >= end)
586                 Host_Error ("%s is not a valid model", loadmodel->name);
587         if (LittleLong(pinmodel->ofs_tris <= 0) || LittleLong(pinmodel->ofs_tris) >= end)
588                 Host_Error ("%s is not a valid model", loadmodel->name);
589         if (LittleLong(pinmodel->ofs_frames <= 0) || LittleLong(pinmodel->ofs_frames) >= end)
590                 Host_Error ("%s is not a valid model", loadmodel->name);
591         if (LittleLong(pinmodel->ofs_glcmds <= 0) || LittleLong(pinmodel->ofs_glcmds) >= end)
592                 Host_Error ("%s is not a valid model", loadmodel->name);
593
594         loadmodel->numskins = LittleLong(pinmodel->num_skins);
595         numxyz = LittleLong(pinmodel->num_xyz);
596         numst = LittleLong(pinmodel->num_st);
597         loadmodel->numtris = LittleLong(pinmodel->num_tris);
598         loadmodel->numframes = LittleLong(pinmodel->num_frames);
599
600         loadmodel->flags = 0; // there are no MD2 flags
601         loadmodel->synctype = ST_RAND;
602
603         // load the skins
604         inskin = (void*)(base + LittleLong(pinmodel->ofs_skins));
605         if (loadmodel->numskins)
606         {
607                 loadmodel->skinscenes = Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
608                 loadmodel->skinframes = Mem_Alloc(loadmodel->mempool, sizeof(skinframe_t) * loadmodel->numskins);
609                 for (i = 0;i < loadmodel->numskins;i++)
610                 {
611                         loadmodel->skinscenes[i].firstframe = i;
612                         loadmodel->skinscenes[i].framecount = 1;
613                         loadmodel->skinscenes[i].loop = true;
614                         loadmodel->skinscenes[i].framerate = 10;
615                         loadmodel->skinframes[i].base = loadtextureimagewithmask (loadmodel->texturepool, inskin, 0, 0, true, r_mipskins.integer, true);
616                         loadmodel->skinframes[i].fog = image_masktex;
617                         loadmodel->skinframes[i].pants = NULL;
618                         loadmodel->skinframes[i].shirt = NULL;
619                         loadmodel->skinframes[i].glow = NULL;
620                         loadmodel->skinframes[i].merged = NULL;
621                         inskin += MD2MAX_SKINNAME;
622                 }
623         }
624
625         // load the triangles and stvert data
626         inst = (void*)(base + LittleLong(pinmodel->ofs_st));
627         intri = (void*)(base + LittleLong(pinmodel->ofs_tris));
628         skinwidth = LittleLong(pinmodel->skinwidth);
629         skinheight = LittleLong(pinmodel->skinheight);
630
631         stverts = Mem_Alloc(tempmempool, numst * sizeof(float[2]));
632         s = 1.0f / skinwidth;
633         t = 1.0f / skinheight;
634         for (i = 0;i < numst;i++)
635         {
636                 j = (unsigned short) LittleShort(inst[i*2+0]);
637                 k = (unsigned short) LittleShort(inst[i*2+1]);
638                 if (j >= skinwidth || k >= skinheight)
639                 {
640                         Mem_Free(stverts);
641                         Host_Error("Mod_MD2_LoadGeometry: invalid skin coordinate (%i %i) on vert %i of model %s\n", j, k, i, loadmodel->name);
642                 }
643                 stverts[i*2+0] = j * s;
644                 stverts[i*2+1] = k * t;
645         }
646
647         md2verthash = Mem_Alloc(tempmempool, 256 * sizeof(hash));
648         md2verthashdata = Mem_Alloc(tempmempool, loadmodel->numtris * 3 * sizeof(*hash));
649         // swap the triangle list
650         num = 0;
651         loadmodel->mdlmd2data_indices = Mem_Alloc(loadmodel->mempool, loadmodel->numtris * sizeof(int[3]));
652         for (i = 0;i < loadmodel->numtris;i++)
653         {
654                 for (j = 0;j < 3;j++)
655                 {
656                         xyz = (unsigned short) LittleShort (intri[i].index_xyz[j]);
657                         st = (unsigned short) LittleShort (intri[i].index_st[j]);
658                         if (xyz >= numxyz || st >= numst)
659                         {
660                                 Mem_Free(md2verthash);
661                                 Mem_Free(md2verthashdata);
662                                 Mem_Free(stverts);
663                                 if (xyz >= numxyz)
664                                         Host_Error("Mod_MD2_LoadGeometry: invalid xyz index (%i) on triangle %i of model %s\n", xyz, i, loadmodel->name);
665                                 if (st >= numst)
666                                         Host_Error("Mod_MD2_LoadGeometry: invalid st index (%i) on triangle %i of model %s\n", st, i, loadmodel->name);
667                         }
668                         s = stverts[st*2+0];
669                         t = stverts[st*2+1];
670                         hashindex = (xyz * 17 + st) & 255;
671                         for (hash = md2verthash[hashindex];hash;hash = hash->next)
672                                 if (hash->xyz == xyz && hash->st[0] == s && hash->st[1] == t)
673                                         break;
674                         if (hash == NULL)
675                         {
676                                 hash = md2verthashdata + num++;
677                                 hash->xyz = xyz;
678                                 hash->st[0] = s;
679                                 hash->st[1] = t;
680                                 hash->next = md2verthash[hashindex];
681                                 md2verthash[hashindex] = hash;
682                         }
683                         loadmodel->mdlmd2data_indices[i*3+j] = (hash - md2verthashdata);
684                 }
685         }
686
687         Mem_Free(stverts);
688
689         loadmodel->numverts = num;
690         vertremap = Mem_Alloc(loadmodel->mempool, num * sizeof(int));
691         loadmodel->mdlmd2data_texcoords = Mem_Alloc(loadmodel->mempool, num * sizeof(float[2]));
692         for (i = 0;i < num;i++)
693         {
694                 hash = md2verthashdata + i;
695                 vertremap[i] = hash->xyz;
696                 loadmodel->mdlmd2data_texcoords[i*2+0] = hash->st[0];
697                 loadmodel->mdlmd2data_texcoords[i*2+1] = hash->st[1];
698         }
699
700         Mem_Free(md2verthash);
701         Mem_Free(md2verthashdata);
702
703         // load frames
704         // LordHavoc: doing proper bbox for model
705         aliasbboxmin[0] = aliasbboxmin[1] = aliasbboxmin[2] = 1000000000;
706         aliasbboxmax[0] = aliasbboxmax[1] = aliasbboxmax[2] = -1000000000;
707         modelyawradius = 0;
708         modelradius = 0;
709
710         datapointer = (base + LittleLong(pinmodel->ofs_frames));
711         // load the frames
712         loadmodel->animscenes = Mem_Alloc(loadmodel->mempool, loadmodel->numframes * sizeof(animscene_t));
713         loadmodel->mdlmd2data_frames = Mem_Alloc(loadmodel->mempool, loadmodel->numframes * sizeof(md2frame_t));
714         loadmodel->mdlmd2data_pose = Mem_Alloc(loadmodel->mempool, loadmodel->numverts * loadmodel->numframes * sizeof(trivertx_t));
715
716         for (i = 0;i < loadmodel->numframes;i++)
717         {
718                 pinframe = (md2frame_t *)datapointer;
719                 datapointer += sizeof(md2frame_t);
720                 strcpy(loadmodel->mdlmd2data_frames[i].name, pinframe->name);
721                 for (j = 0;j < 3;j++)
722                 {
723                         loadmodel->mdlmd2data_frames[i].scale[j] = LittleFloat(pinframe->scale[j]);
724                         loadmodel->mdlmd2data_frames[i].translate[j] = LittleFloat(pinframe->translate[j]);
725                 }
726                 Mod_MD2_ConvertVerts (loadmodel->mdlmd2data_frames[i].scale, loadmodel->mdlmd2data_frames[i].translate, (void *)datapointer, &loadmodel->mdlmd2data_pose[i * loadmodel->numverts], vertremap);
727                 datapointer += numxyz * sizeof(trivertx_t);
728
729                 strcpy(loadmodel->animscenes[i].name, loadmodel->mdlmd2data_frames[i].name);
730                 loadmodel->animscenes[i].firstframe = i;
731                 loadmodel->animscenes[i].framecount = 1;
732                 loadmodel->animscenes[i].framerate = 10;
733                 loadmodel->animscenes[i].loop = true;
734         }
735
736         Mem_Free(vertremap);
737
738         // LordHavoc: model bbox
739         modelyawradius = sqrt(modelyawradius);
740         modelradius = sqrt(modelradius);
741         for (j = 0;j < 3;j++)
742         {
743                 loadmodel->normalmins[j] = aliasbboxmin[j];
744                 loadmodel->normalmaxs[j] = aliasbboxmax[j];
745                 loadmodel->rotatedmins[j] = -modelradius;
746                 loadmodel->rotatedmaxs[j] = modelradius;
747         }
748         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -(loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius);
749         loadmodel->yawmins[2] = loadmodel->normalmins[2];
750         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
751 }
752
753 static void zymswapintblock(int *m, int size)
754 {
755         size /= 4;
756         while(size--)
757         {
758                 *m = BigLong(*m);
759                 m++;
760         }
761 }
762
763 void Mod_LoadZymoticModel(model_t *mod, void *buffer)
764 {
765         int i, pbase, *bonecount, numposes;
766         unsigned int count, a, b, c, *renderlist, *renderlistend;
767         rtexture_t **texture;
768         char *shadername;
769         zymtype1header_t *pinmodel, *pheader;
770         zymscene_t *scene;
771         zymbone_t *bone;
772         float corner[2], modelradius;
773
774         pinmodel = (void *)buffer;
775
776         if (memcmp(pinmodel->id, "ZYMOTICMODEL", 12))
777                 Host_Error ("Mod_LoadZymoticModel: %s is not a zymotic model\n");
778
779         if (BigLong(pinmodel->type) != 1)
780                 Host_Error ("Mod_LoadZymoticModel: only type 1 (skeletal pose) models are currently supported (name = %s)\n", loadmodel->name);
781
782         loadmodel->type = mod_alias;
783         loadmodel->aliastype = ALIASTYPE_ZYM;
784
785         loadmodel->zymdata_header = pheader = Mem_Alloc(loadmodel->mempool, BigLong(pinmodel->filesize));
786
787         pbase = (int) pheader;
788
789         memcpy(pheader, pinmodel, BigLong(pinmodel->filesize));
790
791         // byteswap header
792 #define SWAPLONG(var) var = BigLong(var)
793 #define SWAPFLOAT(var) var = BigFloat(var)
794 #define SWAPVEC(var) SWAPFLOAT(var[0]);SWAPFLOAT(var[1]);SWAPFLOAT(var[2])
795         SWAPLONG(pheader->type);
796         SWAPLONG(pheader->filesize);
797         SWAPVEC(pheader->mins);
798         SWAPVEC(pheader->maxs);
799         SWAPFLOAT(pheader->radius);
800         SWAPLONG(pheader->numverts);
801         SWAPLONG(pheader->numtris);
802         SWAPLONG(pheader->numshaders);
803         SWAPLONG(pheader->numbones);
804         SWAPLONG(pheader->numscenes);
805
806 #define SWAPLUMPINFO(var) SWAPLONG(pheader->lump_##var.start);SWAPLONG(pheader->lump_##var.length)
807         SWAPLUMPINFO(scenes);
808         SWAPLUMPINFO(poses);
809         SWAPLUMPINFO(bones);
810         SWAPLUMPINFO(vertbonecounts);
811         SWAPLUMPINFO(verts);
812         SWAPLUMPINFO(texcoords);
813         SWAPLUMPINFO(render);
814         SWAPLUMPINFO(shaders);
815         SWAPLUMPINFO(trizone);
816
817         loadmodel->flags = 0; // there are no flags
818         loadmodel->numframes = pheader->numscenes;
819         loadmodel->synctype = ST_SYNC;
820         loadmodel->numtris = pheader->numtris;
821
822         // FIXME: add skin support and texturing and shaders and...
823         loadmodel->skinscenes = Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) + sizeof(skinframe_t));
824         loadmodel->skinscenes[0].firstframe = 0;
825         loadmodel->skinscenes[0].framecount = 1;
826         loadmodel->skinscenes[0].loop = true;
827         loadmodel->skinscenes[0].framerate = 10;
828         loadmodel->skinframes = (void *)(loadmodel->skinscenes + 1);
829         loadmodel->skinframes->base = NULL;
830         loadmodel->skinframes->fog = NULL;
831         loadmodel->skinframes->pants = NULL;
832         loadmodel->skinframes->shirt = NULL;
833         loadmodel->skinframes->glow = NULL;
834         loadmodel->skinframes->merged = NULL;
835         loadmodel->numskins = 1;
836         numposes = pheader->lump_poses.length / sizeof(float[3][4]) / pheader->numbones;
837
838         // go through the lumps, swapping things
839
840 //      zymlump_t lump_scenes; // zymscene_t scene[numscenes]; // name and other information for each scene (see zymscene struct)
841         scene = (void *) (pheader->lump_scenes.start + pbase);
842         loadmodel->animscenes = Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numframes);
843         for (i = 0;i < pheader->numscenes;i++)
844         {
845                 SWAPVEC(scene->mins);
846                 SWAPVEC(scene->maxs);
847                 SWAPFLOAT(scene->radius);
848                 SWAPFLOAT(scene->framerate);
849                 SWAPLONG(scene->flags);
850                 SWAPLONG(scene->start);
851                 SWAPLONG(scene->length);
852
853                 memcpy(loadmodel->animscenes[i].name, scene->name, 32);
854                 loadmodel->animscenes[i].firstframe = scene->start;
855                 loadmodel->animscenes[i].framecount = scene->length;
856                 loadmodel->animscenes[i].framerate = scene->framerate;
857                 loadmodel->animscenes[i].loop = (scene->flags & ZYMSCENEFLAG_NOLOOP) == 0;
858
859                 if ((unsigned int) loadmodel->animscenes[i].firstframe >= numposes)
860                         Host_Error("Mod_LoadZymoticModel: scene firstframe (%i) >= numposes (%i)\n", loadmodel->animscenes[i].firstframe, numposes);
861                 if ((unsigned int) loadmodel->animscenes[i].firstframe + (unsigned int) loadmodel->animscenes[i].framecount > numposes)
862                         Host_Error("Mod_LoadZymoticModel: scene firstframe (%i) + framecount (%i) >= numposes (%i)\n", loadmodel->animscenes[i].firstframe, loadmodel->animscenes[i].framecount, numposes);
863                 if (loadmodel->animscenes[i].framerate < 0)
864                         Host_Error("Mod_LoadZymoticModel: scene framerate (%f) < 0\n", loadmodel->animscenes[i].framerate);
865                 scene++;
866         }
867
868 //      zymlump_t lump_poses; // float pose[numposes][numbones][3][4]; // animation data
869         zymswapintblock((void *) (pheader->lump_poses.start + pbase), pheader->lump_poses.length);
870
871 //      zymlump_t lump_bones; // zymbone_t bone[numbones];
872         bone = (void *) (pheader->lump_bones.start + pbase);
873         for (i = 0;i < pheader->numbones;i++)
874         {
875                 SWAPLONG(bone[i].flags);
876                 SWAPLONG(bone[i].parent);
877                 if (bone[i].parent >= i)
878                         Host_Error("Mod_LoadZymoticModel: bone[i].parent >= i in %s\n", loadmodel->name);
879         }
880
881 //      zymlump_t lump_vertbonecounts; // int vertbonecounts[numvertices]; // how many bones influence each vertex (separate mainly to make this compress better)
882         zymswapintblock((void *) (pheader->lump_vertbonecounts.start + pbase), pheader->lump_vertbonecounts.length);
883         bonecount = (void *) (pheader->lump_vertbonecounts.start + pbase);
884         for (i = 0;i < pheader->numbones;i++)
885                 if (bonecount[i] < 1)
886                         Host_Error("Mod_LoadZymoticModel: bone vertex count < 1 in %s\n", loadmodel->name);
887
888 //      zymlump_t lump_verts; // zymvertex_t vert[numvertices]; // see vertex struct
889         zymswapintblock((void *) (pheader->lump_verts.start + pbase), pheader->lump_verts.length);
890
891 //      zymlump_t lump_texcoords; // float texcoords[numvertices][2];
892         zymswapintblock((void *) (pheader->lump_texcoords.start + pbase), pheader->lump_texcoords.length);
893
894 //      zymlump_t lump_render; // int renderlist[rendersize]; // sorted by shader with run lengths (int count), shaders are sequentially used, each run can be used with glDrawElements (each triangle is 3 int indices)
895         zymswapintblock((void *) (pheader->lump_render.start + pbase), pheader->lump_render.length);
896         // validate renderlist and swap winding order of tris
897         renderlist = (void *) (pheader->lump_render.start + pbase);
898         renderlistend = (void *) ((qbyte *) renderlist + pheader->lump_render.length);
899         i = pheader->numshaders * sizeof(int) + pheader->numtris * sizeof(int[3]);
900         if (pheader->lump_render.length != i)
901                 Host_Error("Mod_LoadZymoticModel: renderlist is wrong size in %s (is %i bytes, should be %i bytes)\n", loadmodel->name, pheader->lump_render.length, i);
902         for (i = 0;i < pheader->numshaders;i++)
903         {
904                 if (renderlist >= renderlistend)
905                         Host_Error("Mod_LoadZymoticModel: corrupt renderlist in %s (wrong size)\n", loadmodel->name);
906                 count = *renderlist++;
907                 if (renderlist + count * 3 > renderlistend)
908                         Host_Error("Mod_LoadZymoticModel: corrupt renderlist in %s (wrong size)\n", loadmodel->name);
909                 while (count--)
910                 {
911                         a = renderlist[0];
912                         b = renderlist[1];
913                         c = renderlist[2];
914                         if (a >= pheader->numverts || b >= pheader->numverts || c >= pheader->numverts)
915                                 Host_Error("Mod_LoadZymoticModel: corrupt renderlist in %s (out of bounds index)\n", loadmodel->name);
916                         renderlist[0] = c;
917                         renderlist[1] = b;
918                         renderlist[2] = a;
919                         renderlist += 3;
920                 }
921         }
922
923 //      zymlump_t lump_shaders; // char shadername[numshaders][32]; // shaders used on this model
924         shadername = (void *) (pheader->lump_shaders.start + pbase);
925         texture = (void *) shadername;
926         for (i = 0;i < pheader->numshaders;i++)
927         {
928                 rtexture_t *rt;
929                 rt = loadtextureimage(loadmodel->texturepool, shadername, 0, 0, true, r_mipskins.integer, true);
930                 shadername += 32;
931                 *texture++ = rt; // reuse shader name list for texture pointers
932         }
933
934 //      zymlump_t lump_trizone; // byte trizone[numtris]; // see trizone explanation
935         zymswapintblock((void *) (pheader->lump_trizone.start + pbase), pheader->lump_trizone.length);
936
937         // model bbox
938         modelradius = pheader->radius;
939         for (i = 0;i < 3;i++)
940         {
941                 loadmodel->normalmins[i] = pheader->mins[i];
942                 loadmodel->normalmaxs[i] = pheader->maxs[i];
943                 loadmodel->rotatedmins[i] = -modelradius;
944                 loadmodel->rotatedmaxs[i] = modelradius;
945         }
946         corner[0] = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
947         corner[1] = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
948         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
949         if (loadmodel->yawmaxs[0] > modelradius)
950                 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelradius;
951         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -loadmodel->yawmaxs[0];
952         loadmodel->yawmins[2] = loadmodel->normalmins[2];
953         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
954
955         loadmodel->Draw = R_DrawAliasModel;
956         loadmodel->DrawSky = NULL;
957         loadmodel->DrawShadow = NULL;
958 }
959