made zym and dpm model loaders warn and ignore the model if it is missing geometry...
[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 #include "image.h"
23 #include "r_shadow.h"
24
25 cvar_t r_skeletal_debugbone = {0, "r_skeletal_debugbone", "-1", "development cvar for testing skeletal model code"};
26 cvar_t r_skeletal_debugbonecomponent = {0, "r_skeletal_debugbonecomponent", "3", "development cvar for testing skeletal model code"};
27 cvar_t r_skeletal_debugbonevalue = {0, "r_skeletal_debugbonevalue", "100", "development cvar for testing skeletal model code"};
28 cvar_t r_skeletal_debugtranslatex = {0, "r_skeletal_debugtranslatex", "1", "development cvar for testing skeletal model code"};
29 cvar_t r_skeletal_debugtranslatey = {0, "r_skeletal_debugtranslatey", "1", "development cvar for testing skeletal model code"};
30 cvar_t r_skeletal_debugtranslatez = {0, "r_skeletal_debugtranslatez", "1", "development cvar for testing skeletal model code"};
31
32 void Mod_AliasInit (void)
33 {
34         Cvar_RegisterVariable(&r_skeletal_debugbone);
35         Cvar_RegisterVariable(&r_skeletal_debugbonecomponent);
36         Cvar_RegisterVariable(&r_skeletal_debugbonevalue);
37         Cvar_RegisterVariable(&r_skeletal_debugtranslatex);
38         Cvar_RegisterVariable(&r_skeletal_debugtranslatey);
39         Cvar_RegisterVariable(&r_skeletal_debugtranslatez);
40 }
41
42 void Mod_Alias_GetMesh_Vertex3f(const model_t *model, const frameblend_t *frameblend, const surfmesh_t *mesh, float *out3f)
43 {
44         if (mesh->num_vertexboneweights)
45         {
46                 int i, k, blends;
47                 surfmeshvertexboneweight_t *v;
48                 float *out, *matrix, m[12], bonepose[256][12];
49                 // vertex weighted skeletal
50                 // interpolate matrices and concatenate them to their parents
51                 for (i = 0;i < model->num_bones;i++)
52                 {
53                         for (k = 0;k < 12;k++)
54                                 m[k] = 0;
55                         for (blends = 0;blends < 4 && frameblend[blends].lerp > 0;blends++)
56                         {
57                                 matrix = model->data_poses + (frameblend[blends].frame * model->num_bones + i) * 12;
58                                 for (k = 0;k < 12;k++)
59                                         m[k] += matrix[k] * frameblend[blends].lerp;
60                         }
61                         if (i == r_skeletal_debugbone.integer)
62                                 m[r_skeletal_debugbonecomponent.integer % 12] += r_skeletal_debugbonevalue.value;
63                         m[3] *= r_skeletal_debugtranslatex.value;
64                         m[7] *= r_skeletal_debugtranslatey.value;
65                         m[11] *= r_skeletal_debugtranslatez.value;
66                         if (model->data_bones[i].parent >= 0)
67                                 R_ConcatTransforms(bonepose[model->data_bones[i].parent], m, bonepose[i]);
68                         else
69                                 for (k = 0;k < 12;k++)
70                                         bonepose[i][k] = m[k];
71                 }
72                 // blend the vertex bone weights
73                 memset(out3f, 0, mesh->num_vertices * sizeof(float[3]));
74                 v = mesh->data_vertexboneweights;
75                 for (i = 0;i < mesh->num_vertexboneweights;i++, v++)
76                 {
77                         out = out3f + v->vertexindex * 3;
78                         matrix = bonepose[v->boneindex];
79                         // FIXME: this can very easily be optimized with SSE or 3DNow
80                         out[0] += v->origin[0] * matrix[0] + v->origin[1] * matrix[1] + v->origin[2] * matrix[ 2] + v->origin[3] * matrix[ 3];
81                         out[1] += v->origin[0] * matrix[4] + v->origin[1] * matrix[5] + v->origin[2] * matrix[ 6] + v->origin[3] * matrix[ 7];
82                         out[2] += v->origin[0] * matrix[8] + v->origin[1] * matrix[9] + v->origin[2] * matrix[10] + v->origin[3] * matrix[11];
83                 }
84         }
85         else
86         {
87                 int i, vertcount;
88                 float lerp1, lerp2, lerp3, lerp4;
89                 const float *vertsbase, *verts1, *verts2, *verts3, *verts4;
90                 // vertex morph
91                 if (!mesh->data_morphvertex3f)
92                         Host_Error("model %s has no skeletal or vertex morph animation data", model->name);
93                 vertsbase = mesh->data_morphvertex3f;
94                 vertcount = mesh->num_vertices;
95                 verts1 = vertsbase + frameblend[0].frame * vertcount * 3;
96                 lerp1 = frameblend[0].lerp;
97                 if (frameblend[1].lerp)
98                 {
99                         verts2 = vertsbase + frameblend[1].frame * vertcount * 3;
100                         lerp2 = frameblend[1].lerp;
101                         if (frameblend[2].lerp)
102                         {
103                                 verts3 = vertsbase + frameblend[2].frame * vertcount * 3;
104                                 lerp3 = frameblend[2].lerp;
105                                 if (frameblend[3].lerp)
106                                 {
107                                         verts4 = vertsbase + frameblend[3].frame * vertcount * 3;
108                                         lerp4 = frameblend[3].lerp;
109                                         for (i = 0;i < vertcount * 3;i++)
110                                                 VectorMAMAMAM(lerp1, verts1 + i, lerp2, verts2 + i, lerp3, verts3 + i, lerp4, verts4 + i, out3f + i);
111                                 }
112                                 else
113                                         for (i = 0;i < vertcount * 3;i++)
114                                                 VectorMAMAM(lerp1, verts1 + i, lerp2, verts2 + i, lerp3, verts3 + i, out3f + i);
115                         }
116                         else
117                                 for (i = 0;i < vertcount * 3;i++)
118                                         VectorMAM(lerp1, verts1 + i, lerp2, verts2 + i, out3f + i);
119                 }
120                 else
121                         memcpy(out3f, verts1, vertcount * sizeof(float[3]));
122         }
123 }
124
125 int Mod_Alias_GetTagMatrix(const model_t *model, int poseframe, int tagindex, matrix4x4_t *outmatrix)
126 {
127         const float *boneframe;
128         float tempbonematrix[12], bonematrix[12];
129         *outmatrix = identitymatrix;
130         if (model->num_bones)
131         {
132                 if (tagindex < 0 || tagindex >= model->num_bones)
133                         return 4;
134                 if (poseframe >= model->num_poses)
135                         return 6;
136                 boneframe = model->data_poses + poseframe * model->num_bones * 12;
137                 memcpy(bonematrix, boneframe + tagindex * 12, sizeof(float[12]));
138                 while (model->data_bones[tagindex].parent >= 0)
139                 {
140                         memcpy(tempbonematrix, bonematrix, sizeof(float[12]));
141                         R_ConcatTransforms(boneframe + model->data_bones[tagindex].parent * 12, tempbonematrix, bonematrix);
142                         tagindex = model->data_bones[tagindex].parent;
143                 }
144                 outmatrix->m[0][0] = bonematrix[0];
145                 outmatrix->m[0][1] = bonematrix[1];
146                 outmatrix->m[0][2] = bonematrix[2];
147                 outmatrix->m[0][3] = bonematrix[3];
148                 outmatrix->m[1][0] = bonematrix[4];
149                 outmatrix->m[1][1] = bonematrix[5];
150                 outmatrix->m[1][2] = bonematrix[6];
151                 outmatrix->m[1][3] = bonematrix[7];
152                 outmatrix->m[2][0] = bonematrix[8];
153                 outmatrix->m[2][1] = bonematrix[9];
154                 outmatrix->m[2][2] = bonematrix[10];
155                 outmatrix->m[2][3] = bonematrix[11];
156                 outmatrix->m[3][0] = 0;
157                 outmatrix->m[3][1] = 0;
158                 outmatrix->m[3][2] = 0;
159                 outmatrix->m[3][3] = 1;
160         }
161         else if (model->num_tags)
162         {
163                 if (tagindex < 0 || tagindex >= model->num_tags)
164                         return 4;
165                 if (poseframe >= model->num_tagframes)
166                         return 6;
167                 *outmatrix = model->data_tags[poseframe * model->num_tags + tagindex].matrix;
168         }
169         return 0;
170 }
171
172 int Mod_Alias_GetTagIndexForName(const model_t *model, unsigned int skin, const char *tagname)
173 {
174         int i;
175         if (model->data_overridetagnamesforskin && skin < (unsigned int)model->numskins && model->data_overridetagnamesforskin[(unsigned int)skin].num_overridetagnames)
176                 for (i = 0;i < model->data_overridetagnamesforskin[skin].num_overridetagnames;i++)
177                         if (!strcasecmp(tagname, model->data_overridetagnamesforskin[skin].data_overridetagnames[i].name))
178                                 return i + 1;
179         if (model->num_bones)
180                 for (i = 0;i < model->num_bones;i++)
181                         if (!strcasecmp(tagname, model->data_bones[i].name))
182                                 return i + 1;
183         if (model->num_tags)
184                 for (i = 0;i < model->num_tags;i++)
185                         if (!strcasecmp(tagname, model->data_tags[i].name))
186                                 return i + 1;
187         return 0;
188 }
189
190 static void Mod_Alias_Mesh_CompileFrameZero(surfmesh_t *mesh)
191 {
192         frameblend_t frameblend[4] = {{0, 1}, {0, 0}, {0, 0}, {0, 0}};
193         mesh->data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, mesh->num_vertices * sizeof(float[3][4]));
194         mesh->data_svector3f = mesh->data_vertex3f + mesh->num_vertices * 3;
195         mesh->data_tvector3f = mesh->data_vertex3f + mesh->num_vertices * 6;
196         mesh->data_normal3f = mesh->data_vertex3f + mesh->num_vertices * 9;
197         Mod_Alias_GetMesh_Vertex3f(loadmodel, frameblend, mesh, mesh->data_vertex3f);
198         Mod_BuildTextureVectorsAndNormals(0, mesh->num_vertices, mesh->num_triangles, mesh->data_vertex3f, mesh->data_texcoordtexture2f, mesh->data_element3i, mesh->data_svector3f, mesh->data_tvector3f, mesh->data_normal3f, true);
199 }
200
201 static void Mod_MDLMD2MD3_TraceBox(model_t *model, int frame, trace_t *trace, const vec3_t boxstartmins, const vec3_t boxstartmaxs, const vec3_t boxendmins, const vec3_t boxendmaxs, int hitsupercontentsmask)
202 {
203         int i, linetrace;
204         float segmentmins[3], segmentmaxs[3];
205         frameblend_t frameblend[4];
206         msurface_t *surface;
207         surfmesh_t *mesh;
208         colbrushf_t *thisbrush_start = NULL, *thisbrush_end = NULL;
209         matrix4x4_t startmatrix, endmatrix;
210         memset(trace, 0, sizeof(*trace));
211         trace->fraction = 1;
212         trace->realfraction = 1;
213         trace->hitsupercontentsmask = hitsupercontentsmask;
214         segmentmins[0] = min(boxstartmins[0], boxendmins[0]);
215         segmentmins[1] = min(boxstartmins[1], boxendmins[1]);
216         segmentmins[2] = min(boxstartmins[2], boxendmins[2]);
217         segmentmaxs[0] = max(boxstartmaxs[0], boxendmaxs[0]);
218         segmentmaxs[1] = max(boxstartmaxs[1], boxendmaxs[1]);
219         segmentmaxs[2] = max(boxstartmaxs[2], boxendmaxs[2]);
220         linetrace = VectorCompare(boxstartmins, boxstartmaxs) && VectorCompare(boxendmins, boxendmaxs);
221         if (!linetrace)
222         {
223                 // box trace, performed as brush trace
224                 startmatrix = identitymatrix;
225                 endmatrix = identitymatrix;
226                 thisbrush_start = Collision_BrushForBox(&startmatrix, boxstartmins, boxstartmaxs);
227                 thisbrush_end = Collision_BrushForBox(&endmatrix, boxendmins, boxendmaxs);
228         }
229         memset(frameblend, 0, sizeof(frameblend));
230         frameblend[0].frame = frame;
231         frameblend[0].lerp = 1;
232         for (i = 0, surface = model->data_surfaces;i < model->num_surfaces;i++, surface++)
233         {
234                 mesh = surface->groupmesh;
235                 Mod_Alias_GetMesh_Vertex3f(model, frameblend, mesh, varray_vertex3f);
236                 if (linetrace)
237                         Collision_TraceLineTriangleMeshFloat(trace, boxstartmins, boxendmins, mesh->num_triangles, mesh->data_element3i, varray_vertex3f, SUPERCONTENTS_SOLID, segmentmins, segmentmaxs);
238                 else
239                         Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, mesh->num_triangles, mesh->data_element3i, varray_vertex3f, SUPERCONTENTS_SOLID, segmentmins, segmentmaxs);
240         }
241 }
242
243 static void Mod_CalcAliasModelBBoxes (void)
244 {
245         int vnum, meshnum;
246         float dist, yawradius, radius;
247         surfmesh_t *mesh;
248         float *v;
249         VectorClear(loadmodel->normalmins);
250         VectorClear(loadmodel->normalmaxs);
251         yawradius = 0;
252         radius = 0;
253         for (meshnum = 0;meshnum < loadmodel->num_surfaces;meshnum++)
254         {
255                 mesh = loadmodel->meshlist[meshnum];
256                 for (vnum = 0, v = mesh->data_morphvertex3f;vnum < mesh->num_vertices * mesh->num_morphframes;vnum++, v += 3)
257                 {
258                         if (loadmodel->normalmins[0] > v[0]) loadmodel->normalmins[0] = v[0];
259                         if (loadmodel->normalmins[1] > v[1]) loadmodel->normalmins[1] = v[1];
260                         if (loadmodel->normalmins[2] > v[2]) loadmodel->normalmins[2] = v[2];
261                         if (loadmodel->normalmaxs[0] < v[0]) loadmodel->normalmaxs[0] = v[0];
262                         if (loadmodel->normalmaxs[1] < v[1]) loadmodel->normalmaxs[1] = v[1];
263                         if (loadmodel->normalmaxs[2] < v[2]) loadmodel->normalmaxs[2] = v[2];
264                         dist = v[0] * v[0] + v[1] * v[1];
265                         if (yawradius < dist)
266                                 yawradius = dist;
267                         dist += v[2] * v[2];
268                         if (radius < dist)
269                                 radius = dist;
270                 }
271         }
272         radius = sqrt(radius);
273         yawradius = sqrt(yawradius);
274         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -yawradius;
275         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = yawradius;
276         loadmodel->yawmins[2] = loadmodel->normalmins[2];
277         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
278         loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -radius;
279         loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = radius;
280         loadmodel->radius = radius;
281         loadmodel->radius2 = radius * radius;
282 }
283
284 static void Mod_ConvertAliasVerts (int inverts, vec3_t scale, vec3_t translate, trivertx_t *v, float *out3f, int *vertremap)
285 {
286         int i, j;
287         vec3_t temp;
288         for (i = 0;i < inverts;i++)
289         {
290                 if (vertremap[i] < 0 && vertremap[i+inverts] < 0) // only used vertices need apply...
291                         continue;
292                 temp[0] = v[i].v[0] * scale[0] + translate[0];
293                 temp[1] = v[i].v[1] * scale[1] + translate[1];
294                 temp[2] = v[i].v[2] * scale[2] + translate[2];
295                 j = vertremap[i]; // not onseam
296                 if (j >= 0)
297                         VectorCopy(temp, out3f + j * 3);
298                 j = vertremap[i+inverts]; // onseam
299                 if (j >= 0)
300                         VectorCopy(temp, out3f + j * 3);
301         }
302 }
303
304 static void Mod_MDL_LoadFrames (unsigned char* datapointer, int inverts, vec3_t scale, vec3_t translate, int *vertremap)
305 {
306         int i, f, pose, groupframes;
307         float interval;
308         daliasframetype_t *pframetype;
309         daliasframe_t *pinframe;
310         daliasgroup_t *group;
311         daliasinterval_t *intervals;
312         animscene_t *scene;
313         pose = 0;
314         scene = loadmodel->animscenes;
315         for (f = 0;f < loadmodel->numframes;f++)
316         {
317                 pframetype = (daliasframetype_t *)datapointer;
318                 datapointer += sizeof(daliasframetype_t);
319                 if (LittleLong (pframetype->type) == ALIAS_SINGLE)
320                 {
321                         // a single frame is still treated as a group
322                         interval = 0.1f;
323                         groupframes = 1;
324                 }
325                 else
326                 {
327                         // read group header
328                         group = (daliasgroup_t *)datapointer;
329                         datapointer += sizeof(daliasgroup_t);
330                         groupframes = LittleLong (group->numframes);
331
332                         // intervals (time per frame)
333                         intervals = (daliasinterval_t *)datapointer;
334                         datapointer += sizeof(daliasinterval_t) * groupframes;
335
336                         interval = LittleFloat (intervals->interval); // FIXME: support variable framerate groups
337                         if (interval < 0.01f)
338                         {
339                                 Con_Printf("%s has an invalid interval %f, changing to 0.1\n", loadmodel->name, interval);
340                                 interval = 0.1f;
341                         }
342                 }
343
344                 // get scene name from first frame
345                 pinframe = (daliasframe_t *)datapointer;
346
347                 strcpy(scene->name, pinframe->name);
348                 scene->firstframe = pose;
349                 scene->framecount = groupframes;
350                 scene->framerate = 1.0f / interval;
351                 scene->loop = true;
352                 scene++;
353
354                 // read frames
355                 for (i = 0;i < groupframes;i++)
356                 {
357                         pinframe = (daliasframe_t *)datapointer;
358                         datapointer += sizeof(daliasframe_t);
359                         Mod_ConvertAliasVerts(inverts, scale, translate, (trivertx_t *)datapointer, loadmodel->meshlist[0]->data_morphvertex3f + pose * loadmodel->meshlist[0]->num_vertices * 3, vertremap);
360                         datapointer += sizeof(trivertx_t) * inverts;
361                         pose++;
362                 }
363         }
364 }
365
366 static skinframe_t missingskinframe;
367 static void Mod_BuildAliasSkinFromSkinFrame(texture_t *skin, skinframe_t *skinframe)
368 {
369         // hack
370         if (skinframe == NULL)
371         {
372                 skinframe = &missingskinframe;
373                 memset(skinframe, 0, sizeof(*skinframe));
374                 skinframe->base = r_texture_notexture;
375         }
376
377         skin->skin = *skinframe;
378         skin->currentframe = skin;
379         skin->basematerialflags = MATERIALFLAG_WALL;
380         if (skin->skin.fog)
381                 skin->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT;
382         skin->currentmaterialflags = skin->basematerialflags;
383 }
384
385 static void Mod_BuildAliasSkinsFromSkinFiles(texture_t *skin, skinfile_t *skinfile, char *meshname, char *shadername)
386 {
387         int i;
388         skinfileitem_t *skinfileitem;
389         skinframe_t tempskinframe;
390         if (skinfile)
391         {
392                 // the skin += loadmodel->num_surfaces part of this is because data_textures on alias models is arranged as [numskins][numsurfaces]
393                 for (i = 0;skinfile;skinfile = skinfile->next, i++, skin += loadmodel->num_surfaces)
394                 {
395                         memset(skin, 0, sizeof(*skin));
396                         for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = skinfileitem->next)
397                         {
398                                 // leave the skin unitialized (nodraw) if the replacement is "common/nodraw" or "textures/common/nodraw"
399                                 if (!strcmp(skinfileitem->name, meshname) && strcmp(skinfileitem->replacement, "common/nodraw") && strcmp(skinfileitem->replacement, "textures/common/nodraw"))
400                                 {
401                                         memset(&tempskinframe, 0, sizeof(tempskinframe));
402                                         if (Mod_LoadSkinFrame(&tempskinframe, skinfileitem->replacement, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, true, true))
403                                                 Mod_BuildAliasSkinFromSkinFrame(skin, &tempskinframe);
404                                         else
405                                         {
406                                                 if (cls.state != ca_dedicated)
407                                                         Con_Printf("mesh \"%s\": failed to load skin #%i \"%s\", falling back to mesh's internal shader name \"%s\"\n", meshname, i, skinfileitem->replacement, shadername);
408                                                 if (Mod_LoadSkinFrame(&tempskinframe, shadername, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, true, true))
409                                                         Mod_BuildAliasSkinFromSkinFrame(skin, &tempskinframe);
410                                                 else
411                                                 {
412                                                         if (cls.state != ca_dedicated)
413                                                                 Con_Printf("failed to load skin \"%s\"\n", shadername);
414                                                         Mod_BuildAliasSkinFromSkinFrame(skin, NULL);
415                                                 }
416                                         }
417                                 }
418                         }
419                 }
420         }
421         else
422         {
423                 memset(&tempskinframe, 0, sizeof(tempskinframe));
424                 if (Mod_LoadSkinFrame(&tempskinframe, shadername, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, true, true))
425                         Mod_BuildAliasSkinFromSkinFrame(skin, &tempskinframe);
426                 else
427                 {
428                         if (cls.state != ca_dedicated)
429                                 Con_Printf("Can't find texture \"%s\" for mesh \"%s\", using grey checkerboard\n", shadername, meshname);
430                         Mod_BuildAliasSkinFromSkinFrame(skin, NULL);
431                 }
432         }
433 }
434
435 #define BOUNDI(VALUE,MIN,MAX) if (VALUE < MIN || VALUE >= MAX) Host_Error("model %s has an invalid ##VALUE (%d exceeds %d - %d)", loadmodel->name, VALUE, MIN, MAX);
436 #define BOUNDF(VALUE,MIN,MAX) if (VALUE < MIN || VALUE >= MAX) Host_Error("model %s has an invalid ##VALUE (%f exceeds %f - %f)", loadmodel->name, VALUE, MIN, MAX);
437 void Mod_IDP0_Load(model_t *mod, void *buffer, void *bufferend)
438 {
439         int i, j, version, totalskins, skinwidth, skinheight, groupframes, groupskins, numverts;
440         float scales, scalet, scale[3], translate[3], interval;
441         msurface_t *surface;
442         unsigned char *data;
443         mdl_t *pinmodel;
444         stvert_t *pinstverts;
445         dtriangle_t *pintriangles;
446         daliasskintype_t *pinskintype;
447         daliasskingroup_t *pinskingroup;
448         daliasskininterval_t *pinskinintervals;
449         daliasframetype_t *pinframetype;
450         daliasgroup_t *pinframegroup;
451         unsigned char *datapointer, *startframes, *startskins;
452         char name[MAX_QPATH];
453         skinframe_t tempskinframe;
454         animscene_t *tempskinscenes;
455         texture_t *tempaliasskins;
456         float *vertst;
457         int *vertonseam, *vertremap;
458         skinfile_t *skinfiles;
459
460         datapointer = (unsigned char *)buffer;
461         pinmodel = (mdl_t *)datapointer;
462         datapointer += sizeof(mdl_t);
463
464         version = LittleLong (pinmodel->version);
465         if (version != ALIAS_VERSION)
466                 Host_Error ("%s has wrong version number (%i should be %i)",
467                                  loadmodel->name, version, ALIAS_VERSION);
468
469         loadmodel->type = mod_alias;
470         loadmodel->DrawSky = NULL;
471         loadmodel->Draw = R_Q1BSP_Draw;
472         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
473         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
474         loadmodel->DrawLight = R_Q1BSP_DrawLight;
475         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
476
477         loadmodel->num_surfaces = 1;
478         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
479         loadmodel->nummeshes = loadmodel->num_surfaces;
480         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->nummeshes * sizeof(surfmesh_t *) + loadmodel->nummeshes * sizeof(surfmesh_t));
481         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
482         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
483         loadmodel->meshlist = (surfmesh_t **)data;data += loadmodel->num_surfaces * sizeof(surfmesh_t *);
484         for (i = 0;i < loadmodel->num_surfaces;i++)
485         {
486                 loadmodel->surfacelist[i] = i;
487                 loadmodel->meshlist[i] = (surfmesh_t *)data;data += sizeof(surfmesh_t);
488         }
489
490         loadmodel->numskins = LittleLong(pinmodel->numskins);
491         BOUNDI(loadmodel->numskins,0,65536);
492         skinwidth = LittleLong (pinmodel->skinwidth);
493         BOUNDI(skinwidth,0,65536);
494         skinheight = LittleLong (pinmodel->skinheight);
495         BOUNDI(skinheight,0,65536);
496         numverts = LittleLong(pinmodel->numverts);
497         BOUNDI(numverts,0,65536);
498         loadmodel->meshlist[0]->num_triangles = LittleLong(pinmodel->numtris);
499         BOUNDI(loadmodel->meshlist[0]->num_triangles,0,65536);
500         loadmodel->numframes = LittleLong(pinmodel->numframes);
501         BOUNDI(loadmodel->numframes,0,65536);
502         loadmodel->synctype = (synctype_t)LittleLong (pinmodel->synctype);
503         BOUNDI(loadmodel->synctype,0,2);
504         loadmodel->flags = LittleLong (pinmodel->flags);
505
506         for (i = 0;i < 3;i++)
507         {
508                 scale[i] = LittleFloat (pinmodel->scale[i]);
509                 translate[i] = LittleFloat (pinmodel->scale_origin[i]);
510         }
511
512         startskins = datapointer;
513         totalskins = 0;
514         for (i = 0;i < loadmodel->numskins;i++)
515         {
516                 pinskintype = (daliasskintype_t *)datapointer;
517                 datapointer += sizeof(daliasskintype_t);
518                 if (LittleLong(pinskintype->type) == ALIAS_SKIN_SINGLE)
519                         groupskins = 1;
520                 else
521                 {
522                         pinskingroup = (daliasskingroup_t *)datapointer;
523                         datapointer += sizeof(daliasskingroup_t);
524                         groupskins = LittleLong(pinskingroup->numskins);
525                         datapointer += sizeof(daliasskininterval_t) * groupskins;
526                 }
527
528                 for (j = 0;j < groupskins;j++)
529                 {
530                         datapointer += skinwidth * skinheight;
531                         totalskins++;
532                 }
533         }
534
535         pinstverts = (stvert_t *)datapointer;
536         datapointer += sizeof(stvert_t) * numverts;
537
538         pintriangles = (dtriangle_t *)datapointer;
539         datapointer += sizeof(dtriangle_t) * loadmodel->meshlist[0]->num_triangles;
540
541         startframes = datapointer;
542         loadmodel->meshlist[0]->num_morphframes = 0;
543         for (i = 0;i < loadmodel->numframes;i++)
544         {
545                 pinframetype = (daliasframetype_t *)datapointer;
546                 datapointer += sizeof(daliasframetype_t);
547                 if (LittleLong (pinframetype->type) == ALIAS_SINGLE)
548                         groupframes = 1;
549                 else
550                 {
551                         pinframegroup = (daliasgroup_t *)datapointer;
552                         datapointer += sizeof(daliasgroup_t);
553                         groupframes = LittleLong(pinframegroup->numframes);
554                         datapointer += sizeof(daliasinterval_t) * groupframes;
555                 }
556
557                 for (j = 0;j < groupframes;j++)
558                 {
559                         datapointer += sizeof(daliasframe_t);
560                         datapointer += sizeof(trivertx_t) * numverts;
561                         loadmodel->meshlist[0]->num_morphframes++;
562                 }
563         }
564
565         // store texture coordinates into temporary array, they will be stored
566         // after usage is determined (triangle data)
567         vertst = (float *)Mem_Alloc(tempmempool, numverts * 2 * sizeof(float[2]));
568         vertremap = (int *)Mem_Alloc(tempmempool, numverts * 3 * sizeof(int));
569         vertonseam = vertremap + numverts * 2;
570
571         scales = 1.0 / skinwidth;
572         scalet = 1.0 / skinheight;
573         for (i = 0;i < numverts;i++)
574         {
575                 vertonseam[i] = LittleLong(pinstverts[i].onseam);
576                 vertst[i*2+0] = (LittleLong(pinstverts[i].s) + 0.5) * scales;
577                 vertst[i*2+1] = (LittleLong(pinstverts[i].t) + 0.5) * scalet;
578                 vertst[(i+numverts)*2+0] = vertst[i*2+0] + 0.5;
579                 vertst[(i+numverts)*2+1] = vertst[i*2+1];
580         }
581
582 // load triangle data
583         loadmodel->meshlist[0]->data_element3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * loadmodel->meshlist[0]->num_triangles);
584
585         // read the triangle elements
586         for (i = 0;i < loadmodel->meshlist[0]->num_triangles;i++)
587                 for (j = 0;j < 3;j++)
588                         loadmodel->meshlist[0]->data_element3i[i*3+j] = LittleLong(pintriangles[i].vertindex[j]);
589         // validate (note numverts is used because this is the original data)
590         Mod_ValidateElements(loadmodel->meshlist[0]->data_element3i, loadmodel->meshlist[0]->num_triangles, numverts, __FILE__, __LINE__);
591         // now butcher the elements according to vertonseam and tri->facesfront
592         // and then compact the vertex set to remove duplicates
593         for (i = 0;i < loadmodel->meshlist[0]->num_triangles;i++)
594                 if (!LittleLong(pintriangles[i].facesfront)) // backface
595                         for (j = 0;j < 3;j++)
596                                 if (vertonseam[loadmodel->meshlist[0]->data_element3i[i*3+j]])
597                                         loadmodel->meshlist[0]->data_element3i[i*3+j] += numverts;
598         // count the usage
599         // (this uses vertremap to count usage to save some memory)
600         for (i = 0;i < numverts*2;i++)
601                 vertremap[i] = 0;
602         for (i = 0;i < loadmodel->meshlist[0]->num_triangles*3;i++)
603                 vertremap[loadmodel->meshlist[0]->data_element3i[i]]++;
604         // build remapping table and compact array
605         loadmodel->meshlist[0]->num_vertices = 0;
606         for (i = 0;i < numverts*2;i++)
607         {
608                 if (vertremap[i])
609                 {
610                         vertremap[i] = loadmodel->meshlist[0]->num_vertices;
611                         vertst[loadmodel->meshlist[0]->num_vertices*2+0] = vertst[i*2+0];
612                         vertst[loadmodel->meshlist[0]->num_vertices*2+1] = vertst[i*2+1];
613                         loadmodel->meshlist[0]->num_vertices++;
614                 }
615                 else
616                         vertremap[i] = -1; // not used at all
617         }
618         // remap the elements to the new vertex set
619         for (i = 0;i < loadmodel->meshlist[0]->num_triangles * 3;i++)
620                 loadmodel->meshlist[0]->data_element3i[i] = vertremap[loadmodel->meshlist[0]->data_element3i[i]];
621         // store the texture coordinates
622         loadmodel->meshlist[0]->data_texcoordtexture2f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[2]) * loadmodel->meshlist[0]->num_vertices);
623         for (i = 0;i < loadmodel->meshlist[0]->num_vertices;i++)
624         {
625                 loadmodel->meshlist[0]->data_texcoordtexture2f[i*2+0] = vertst[i*2+0];
626                 loadmodel->meshlist[0]->data_texcoordtexture2f[i*2+1] = vertst[i*2+1];
627         }
628
629 // load the frames
630         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numframes);
631         loadmodel->meshlist[0]->data_morphvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * loadmodel->meshlist[0]->num_morphframes * loadmodel->meshlist[0]->num_vertices);
632         loadmodel->meshlist[0]->data_neighbor3i = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->meshlist[0]->num_triangles * sizeof(int[3]));
633         Mod_MDL_LoadFrames (startframes, numverts, scale, translate, vertremap);
634         Mod_BuildTriangleNeighbors(loadmodel->meshlist[0]->data_neighbor3i, loadmodel->meshlist[0]->data_element3i, loadmodel->meshlist[0]->num_triangles);
635         Mod_CalcAliasModelBBoxes();
636         Mod_Alias_Mesh_CompileFrameZero(loadmodel->meshlist[0]);
637
638         Mem_Free(vertst);
639         Mem_Free(vertremap);
640
641         // load the skins
642         skinfiles = Mod_LoadSkinFiles();
643         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, loadmodel->numskins * sizeof(animscene_t));
644         loadmodel->num_textures = loadmodel->num_surfaces;
645         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * totalskins * sizeof(texture_t));
646         if (skinfiles)
647         {
648                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
649                 Mod_FreeSkinFiles(skinfiles);
650                 for (i = 0;i < loadmodel->numskins;i++)
651                 {
652                         loadmodel->skinscenes[i].firstframe = i;
653                         loadmodel->skinscenes[i].framecount = 1;
654                         loadmodel->skinscenes[i].loop = true;
655                         loadmodel->skinscenes[i].framerate = 10;
656                 }
657         }
658         else
659         {
660                 totalskins = 0;
661                 datapointer = startskins;
662                 for (i = 0;i < loadmodel->numskins;i++)
663                 {
664                         pinskintype = (daliasskintype_t *)datapointer;
665                         datapointer += sizeof(daliasskintype_t);
666
667                         if (pinskintype->type == ALIAS_SKIN_SINGLE)
668                         {
669                                 groupskins = 1;
670                                 interval = 0.1f;
671                         }
672                         else
673                         {
674                                 pinskingroup = (daliasskingroup_t *)datapointer;
675                                 datapointer += sizeof(daliasskingroup_t);
676
677                                 groupskins = LittleLong (pinskingroup->numskins);
678
679                                 pinskinintervals = (daliasskininterval_t *)datapointer;
680                                 datapointer += sizeof(daliasskininterval_t) * groupskins;
681
682                                 interval = LittleFloat(pinskinintervals[0].interval);
683                                 if (interval < 0.01f)
684                                 {
685                                         Con_Printf("%s has an invalid interval %f, changing to 0.1\n", loadmodel->name, interval);
686                                         interval = 0.1f;
687                                 }
688                         }
689
690                         sprintf(loadmodel->skinscenes[i].name, "skin %i", i);
691                         loadmodel->skinscenes[i].firstframe = totalskins;
692                         loadmodel->skinscenes[i].framecount = groupskins;
693                         loadmodel->skinscenes[i].framerate = 1.0f / interval;
694                         loadmodel->skinscenes[i].loop = true;
695
696                         for (j = 0;j < groupskins;j++)
697                         {
698                                 if (groupskins > 1)
699                                         sprintf (name, "%s_%i_%i", loadmodel->name, i, j);
700                                 else
701                                         sprintf (name, "%s_%i", loadmodel->name, i);
702                                 if (!Mod_LoadSkinFrame(&tempskinframe, name, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP, true, true))
703                                         Mod_LoadSkinFrame_Internal(&tempskinframe, name, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP, true, r_fullbrights.integer, (unsigned char *)datapointer, skinwidth, skinheight, 8, NULL, NULL);
704                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + totalskins * loadmodel->num_surfaces, &tempskinframe);
705                                 datapointer += skinwidth * skinheight;
706                                 totalskins++;
707                         }
708                 }
709                 // check for skins that don't exist in the model, but do exist as external images
710                 // (this was added because yummyluv kept pestering me about support for it)
711                 while (Mod_LoadSkinFrame(&tempskinframe, va("%s_%i", loadmodel->name, loadmodel->numskins), (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP, true, true))
712                 {
713                         // expand the arrays to make room
714                         tempskinscenes = loadmodel->skinscenes;
715                         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, (loadmodel->numskins + 1) * sizeof(animscene_t));
716                         memcpy(loadmodel->skinscenes, tempskinscenes, loadmodel->numskins * sizeof(animscene_t));
717                         Mem_Free(tempskinscenes);
718
719                         tempaliasskins = loadmodel->data_textures;
720                         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * (totalskins + 1) * sizeof(texture_t));
721                         memcpy(loadmodel->data_textures, tempaliasskins, loadmodel->num_surfaces * totalskins * sizeof(texture_t));
722                         Mem_Free(tempaliasskins);
723
724                         // store the info about the new skin
725                         Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + totalskins * loadmodel->num_surfaces, &tempskinframe);
726                         strcpy(loadmodel->skinscenes[loadmodel->numskins].name, name);
727                         loadmodel->skinscenes[loadmodel->numskins].firstframe = totalskins;
728                         loadmodel->skinscenes[loadmodel->numskins].framecount = 1;
729                         loadmodel->skinscenes[loadmodel->numskins].framerate = 10.0f;
730                         loadmodel->skinscenes[loadmodel->numskins].loop = true;
731
732                         //increase skin counts
733                         loadmodel->numskins++;
734                         totalskins++;
735                 }
736         }
737
738         surface = loadmodel->data_surfaces;
739         surface->texture = loadmodel->data_textures;
740         surface->groupmesh = loadmodel->meshlist[0];
741         surface->num_firsttriangle = 0;
742         surface->num_triangles = surface->groupmesh->num_triangles;
743         surface->num_firstvertex = 0;
744         surface->num_vertices = surface->groupmesh->num_vertices;
745 }
746
747 static void Mod_MD2_ConvertVerts (vec3_t scale, vec3_t translate, trivertx_t *v, float *out3f, int numverts, int *vertremap)
748 {
749         int i;
750         trivertx_t *in;
751         for (i = 0;i < numverts;i++, out3f += 3)
752         {
753                 in = v + vertremap[i];
754                 out3f[0] = in->v[0] * scale[0] + translate[0];
755                 out3f[1] = in->v[1] * scale[1] + translate[1];
756                 out3f[2] = in->v[2] * scale[2] + translate[2];
757         }
758 }
759
760 void Mod_IDP2_Load(model_t *mod, void *buffer, void *bufferend)
761 {
762         int i, j, k, hashindex, num, numxyz, numst, xyz, st, skinwidth, skinheight, *vertremap, version, end, numverts;
763         float *stverts, s, t, scale[3], translate[3];
764         unsigned char *data;
765         msurface_t *surface;
766         md2_t *pinmodel;
767         unsigned char *base, *datapointer;
768         md2frame_t *pinframe;
769         char *inskin;
770         md2triangle_t *intri;
771         unsigned short *inst;
772         struct md2verthash_s
773         {
774                 struct md2verthash_s *next;
775                 int xyz;
776                 float st[2];
777         }
778         *hash, **md2verthash, *md2verthashdata;
779         skinframe_t tempskinframe;
780         skinfile_t *skinfiles;
781
782         pinmodel = (md2_t *)buffer;
783         base = (unsigned char *)buffer;
784
785         version = LittleLong (pinmodel->version);
786         if (version != MD2ALIAS_VERSION)
787                 Host_Error ("%s has wrong version number (%i should be %i)",
788                         loadmodel->name, version, MD2ALIAS_VERSION);
789
790         loadmodel->type = mod_alias;
791         loadmodel->DrawSky = NULL;
792         loadmodel->Draw = R_Q1BSP_Draw;
793         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
794         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
795         loadmodel->DrawLight = R_Q1BSP_DrawLight;
796         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
797
798         if (LittleLong(pinmodel->num_tris) < 1 || LittleLong(pinmodel->num_tris) > 65536)
799                 Host_Error ("%s has invalid number of triangles: %i", loadmodel->name, LittleLong(pinmodel->num_tris));
800         if (LittleLong(pinmodel->num_xyz) < 1 || LittleLong(pinmodel->num_xyz) > 65536)
801                 Host_Error ("%s has invalid number of vertices: %i", loadmodel->name, LittleLong(pinmodel->num_xyz));
802         if (LittleLong(pinmodel->num_frames) < 1 || LittleLong(pinmodel->num_frames) > 65536)
803                 Host_Error ("%s has invalid number of frames: %i", loadmodel->name, LittleLong(pinmodel->num_frames));
804         if (LittleLong(pinmodel->num_skins) < 0 || LittleLong(pinmodel->num_skins) > 256)
805                 Host_Error ("%s has invalid number of skins: %i", loadmodel->name, LittleLong(pinmodel->num_skins));
806
807         end = LittleLong(pinmodel->ofs_end);
808         if (LittleLong(pinmodel->num_skins) >= 1 && (LittleLong(pinmodel->ofs_skins) <= 0 || LittleLong(pinmodel->ofs_skins) >= end))
809                 Host_Error ("%s is not a valid model", loadmodel->name);
810         if (LittleLong(pinmodel->ofs_st) <= 0 || LittleLong(pinmodel->ofs_st) >= end)
811                 Host_Error ("%s is not a valid model", loadmodel->name);
812         if (LittleLong(pinmodel->ofs_tris) <= 0 || LittleLong(pinmodel->ofs_tris) >= end)
813                 Host_Error ("%s is not a valid model", loadmodel->name);
814         if (LittleLong(pinmodel->ofs_frames) <= 0 || LittleLong(pinmodel->ofs_frames) >= end)
815                 Host_Error ("%s is not a valid model", loadmodel->name);
816         if (LittleLong(pinmodel->ofs_glcmds) <= 0 || LittleLong(pinmodel->ofs_glcmds) >= end)
817                 Host_Error ("%s is not a valid model", loadmodel->name);
818
819         loadmodel->num_surfaces = 1;
820         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
821         loadmodel->nummeshes = loadmodel->num_surfaces;
822         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->nummeshes * sizeof(surfmesh_t *) + loadmodel->nummeshes * sizeof(surfmesh_t));
823         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
824         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
825         loadmodel->meshlist = (surfmesh_t **)data;data += loadmodel->num_surfaces * sizeof(surfmesh_t *);
826         for (i = 0;i < loadmodel->num_surfaces;i++)
827         {
828                 loadmodel->surfacelist[i] = i;
829                 loadmodel->meshlist[i] = (surfmesh_t *)data;data += sizeof(surfmesh_t);
830         }
831
832         loadmodel->numskins = LittleLong(pinmodel->num_skins);
833         numxyz = LittleLong(pinmodel->num_xyz);
834         numst = LittleLong(pinmodel->num_st);
835         loadmodel->meshlist[0]->num_triangles = LittleLong(pinmodel->num_tris);
836         loadmodel->numframes = LittleLong(pinmodel->num_frames);
837         loadmodel->meshlist[0]->num_morphframes = loadmodel->numframes;
838         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, loadmodel->numframes * sizeof(animscene_t));
839
840         loadmodel->flags = 0; // there are no MD2 flags
841         loadmodel->synctype = ST_RAND;
842
843         // load the skins
844         inskin = (char *)(base + LittleLong(pinmodel->ofs_skins));
845         skinfiles = Mod_LoadSkinFiles();
846         if (skinfiles)
847         {
848                 loadmodel->num_textures = loadmodel->num_surfaces;
849                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
850                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
851                 Mod_FreeSkinFiles(skinfiles);
852         }
853         else if (loadmodel->numskins)
854         {
855                 // skins found (most likely not a player model)
856                 loadmodel->num_textures = loadmodel->num_surfaces;
857                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
858                 for (i = 0;i < loadmodel->numskins;i++, inskin += MD2_SKINNAME)
859                 {
860                         if (Mod_LoadSkinFrame(&tempskinframe, inskin, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, true, true))
861                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i * loadmodel->num_surfaces, &tempskinframe);
862                         else
863                         {
864                                 Con_Printf("%s is missing skin \"%s\"\n", loadmodel->name, inskin);
865                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i * loadmodel->num_surfaces, NULL);
866                         }
867                 }
868         }
869         else
870         {
871                 // no skins (most likely a player model)
872                 loadmodel->numskins = 1;
873                 loadmodel->num_textures = loadmodel->num_surfaces;
874                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
875                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures, NULL);
876         }
877
878         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
879         for (i = 0;i < loadmodel->numskins;i++)
880         {
881                 loadmodel->skinscenes[i].firstframe = i;
882                 loadmodel->skinscenes[i].framecount = 1;
883                 loadmodel->skinscenes[i].loop = true;
884                 loadmodel->skinscenes[i].framerate = 10;
885         }
886
887         // load the triangles and stvert data
888         inst = (unsigned short *)(base + LittleLong(pinmodel->ofs_st));
889         intri = (md2triangle_t *)(base + LittleLong(pinmodel->ofs_tris));
890         skinwidth = LittleLong(pinmodel->skinwidth);
891         skinheight = LittleLong(pinmodel->skinheight);
892
893         stverts = (float *)Mem_Alloc(tempmempool, numst * sizeof(float[2]));
894         s = 1.0f / skinwidth;
895         t = 1.0f / skinheight;
896         for (i = 0;i < numst;i++)
897         {
898                 j = (unsigned short) LittleShort(inst[i*2+0]);
899                 k = (unsigned short) LittleShort(inst[i*2+1]);
900                 if (j >= skinwidth || k >= skinheight)
901                 {
902                         Con_Printf("%s has an invalid skin coordinate (%i %i) on vert %i, changing to 0 0\n", loadmodel->name, j, k, i);
903                         j = 0;
904                         k = 0;
905                 }
906                 stverts[i*2+0] = j * s;
907                 stverts[i*2+1] = k * t;
908         }
909
910         md2verthash = (struct md2verthash_s **)Mem_Alloc(tempmempool, 256 * sizeof(hash));
911         md2verthashdata = (struct md2verthash_s *)Mem_Alloc(tempmempool, loadmodel->meshlist[0]->num_triangles * 3 * sizeof(*hash));
912         // swap the triangle list
913         num = 0;
914         loadmodel->meshlist[0]->data_element3i = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->meshlist[0]->num_triangles * sizeof(int[3]));
915         for (i = 0;i < loadmodel->meshlist[0]->num_triangles;i++)
916         {
917                 for (j = 0;j < 3;j++)
918                 {
919                         xyz = (unsigned short) LittleShort (intri[i].index_xyz[j]);
920                         st = (unsigned short) LittleShort (intri[i].index_st[j]);
921                         if (xyz >= numxyz)
922                         {
923                                 Con_Printf("%s has an invalid xyz index (%i) on triangle %i, resetting to 0\n", loadmodel->name, xyz, i);
924                                 xyz = 0;
925                         }
926                         if (st >= numst)
927                         {
928                                 Con_Printf("%s has an invalid st index (%i) on triangle %i, resetting to 0\n", loadmodel->name, st, i);
929                                 st = 0;
930                         }
931                         s = stverts[st*2+0];
932                         t = stverts[st*2+1];
933                         hashindex = (xyz * 17 + st) & 255;
934                         for (hash = md2verthash[hashindex];hash;hash = hash->next)
935                                 if (hash->xyz == xyz && hash->st[0] == s && hash->st[1] == t)
936                                         break;
937                         if (hash == NULL)
938                         {
939                                 hash = md2verthashdata + num++;
940                                 hash->xyz = xyz;
941                                 hash->st[0] = s;
942                                 hash->st[1] = t;
943                                 hash->next = md2verthash[hashindex];
944                                 md2verthash[hashindex] = hash;
945                         }
946                         loadmodel->meshlist[0]->data_element3i[i*3+j] = (hash - md2verthashdata);
947                 }
948         }
949
950         Mem_Free(stverts);
951
952         numverts = num;
953         loadmodel->meshlist[0]->num_vertices = numverts;
954         vertremap = (int *)Mem_Alloc(loadmodel->mempool, num * sizeof(int));
955         loadmodel->meshlist[0]->data_texcoordtexture2f = (float *)Mem_Alloc(loadmodel->mempool, num * sizeof(float[2]));
956         for (i = 0;i < num;i++)
957         {
958                 hash = md2verthashdata + i;
959                 vertremap[i] = hash->xyz;
960                 loadmodel->meshlist[0]->data_texcoordtexture2f[i*2+0] = hash->st[0];
961                 loadmodel->meshlist[0]->data_texcoordtexture2f[i*2+1] = hash->st[1];
962         }
963
964         Mem_Free(md2verthash);
965         Mem_Free(md2verthashdata);
966
967         // load the frames
968         datapointer = (base + LittleLong(pinmodel->ofs_frames));
969         loadmodel->meshlist[0]->data_morphvertex3f = (float *)Mem_Alloc(loadmodel->mempool, numverts * loadmodel->meshlist[0]->num_morphframes * sizeof(float[3]));
970         for (i = 0;i < loadmodel->meshlist[0]->num_morphframes;i++)
971         {
972                 pinframe = (md2frame_t *)datapointer;
973                 datapointer += sizeof(md2frame_t);
974                 for (j = 0;j < 3;j++)
975                 {
976                         scale[j] = LittleFloat(pinframe->scale[j]);
977                         translate[j] = LittleFloat(pinframe->translate[j]);
978                 }
979                 Mod_MD2_ConvertVerts(scale, translate, (trivertx_t *)datapointer, loadmodel->meshlist[0]->data_morphvertex3f + i * numverts * 3, numverts, vertremap);
980                 datapointer += numxyz * sizeof(trivertx_t);
981
982                 strcpy(loadmodel->animscenes[i].name, pinframe->name);
983                 loadmodel->animscenes[i].firstframe = i;
984                 loadmodel->animscenes[i].framecount = 1;
985                 loadmodel->animscenes[i].framerate = 10;
986                 loadmodel->animscenes[i].loop = true;
987         }
988
989         Mem_Free(vertremap);
990
991         loadmodel->meshlist[0]->data_neighbor3i = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->meshlist[0]->num_triangles * sizeof(int[3]));
992         Mod_BuildTriangleNeighbors(loadmodel->meshlist[0]->data_neighbor3i, loadmodel->meshlist[0]->data_element3i, loadmodel->meshlist[0]->num_triangles);
993         Mod_CalcAliasModelBBoxes();
994         Mod_Alias_Mesh_CompileFrameZero(loadmodel->meshlist[0]);
995
996         surface = loadmodel->data_surfaces;
997         surface->groupmesh = loadmodel->meshlist[0];
998         surface->texture = loadmodel->data_textures;
999         surface->num_firsttriangle = 0;
1000         surface->num_triangles = surface->groupmesh->num_triangles;
1001         surface->num_firstvertex = 0;
1002         surface->num_vertices = surface->groupmesh->num_vertices;
1003 }
1004
1005 void Mod_IDP3_Load(model_t *mod, void *buffer, void *bufferend)
1006 {
1007         int i, j, k, version;
1008         unsigned char *data;
1009         msurface_t *surface;
1010         surfmesh_t *mesh;
1011         md3modelheader_t *pinmodel;
1012         md3frameinfo_t *pinframe;
1013         md3mesh_t *pinmesh;
1014         md3tag_t *pintag;
1015         skinfile_t *skinfiles;
1016
1017         pinmodel = (md3modelheader_t *)buffer;
1018
1019         if (memcmp(pinmodel->identifier, "IDP3", 4))
1020                 Host_Error ("%s is not a MD3 (IDP3) file", loadmodel->name);
1021         version = LittleLong (pinmodel->version);
1022         if (version != MD3VERSION)
1023                 Host_Error ("%s has wrong version number (%i should be %i)",
1024                         loadmodel->name, version, MD3VERSION);
1025
1026         skinfiles = Mod_LoadSkinFiles();
1027         if (loadmodel->numskins < 1)
1028                 loadmodel->numskins = 1;
1029
1030         loadmodel->type = mod_alias;
1031         loadmodel->DrawSky = NULL;
1032         loadmodel->Draw = R_Q1BSP_Draw;
1033         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1034         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1035         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1036         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1037         loadmodel->flags = LittleLong(pinmodel->flags);
1038         loadmodel->synctype = ST_RAND;
1039
1040         // set up some global info about the model
1041         loadmodel->numframes = LittleLong(pinmodel->num_frames);
1042         loadmodel->num_surfaces = LittleLong(pinmodel->num_meshes);
1043
1044         // make skinscenes for the skins (no groups)
1045         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
1046         for (i = 0;i < loadmodel->numskins;i++)
1047         {
1048                 loadmodel->skinscenes[i].firstframe = i;
1049                 loadmodel->skinscenes[i].framecount = 1;
1050                 loadmodel->skinscenes[i].loop = true;
1051                 loadmodel->skinscenes[i].framerate = 10;
1052         }
1053
1054         // load frameinfo
1055         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, loadmodel->numframes * sizeof(animscene_t));
1056         for (i = 0, pinframe = (md3frameinfo_t *)((unsigned char *)pinmodel + LittleLong(pinmodel->lump_frameinfo));i < loadmodel->numframes;i++, pinframe++)
1057         {
1058                 strcpy(loadmodel->animscenes[i].name, pinframe->name);
1059                 loadmodel->animscenes[i].firstframe = i;
1060                 loadmodel->animscenes[i].framecount = 1;
1061                 loadmodel->animscenes[i].framerate = 10;
1062                 loadmodel->animscenes[i].loop = true;
1063         }
1064
1065         // load tags
1066         loadmodel->num_tagframes = loadmodel->numframes;
1067         loadmodel->num_tags = LittleLong(pinmodel->num_tags);
1068         loadmodel->data_tags = (aliastag_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_tagframes * loadmodel->num_tags * sizeof(aliastag_t));
1069         for (i = 0, pintag = (md3tag_t *)((unsigned char *)pinmodel + LittleLong(pinmodel->lump_tags));i < loadmodel->num_tagframes * loadmodel->num_tags;i++, pintag++)
1070         {
1071                 strcpy(loadmodel->data_tags[i].name, pintag->name);
1072                 loadmodel->data_tags[i].matrix = identitymatrix;
1073                 for (j = 0;j < 3;j++)
1074                 {
1075                         for (k = 0;k < 3;k++)
1076                                 loadmodel->data_tags[i].matrix.m[j][k] = LittleFloat(pintag->rotationmatrix[k * 3 + j]);
1077                         loadmodel->data_tags[i].matrix.m[j][3] = LittleFloat(pintag->origin[j]);
1078                 }
1079                 //Con_Printf("model \"%s\" frame #%i tag #%i \"%s\"\n", loadmodel->name, i / loadmodel->num_tags, i % loadmodel->num_tags, loadmodel->data_tags[i].name);
1080         }
1081
1082         // load meshes
1083         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
1084         loadmodel->nummeshes = loadmodel->num_surfaces;
1085         loadmodel->num_textures = loadmodel->num_surfaces;
1086         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->nummeshes * sizeof(surfmesh_t *) + loadmodel->nummeshes * sizeof(surfmesh_t) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
1087         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1088         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1089         loadmodel->meshlist = (surfmesh_t **)data;data += loadmodel->num_surfaces * sizeof(surfmesh_t *);
1090         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
1091         for (i = 0;i < loadmodel->num_surfaces;i++)
1092         {
1093                 loadmodel->surfacelist[i] = i;
1094                 loadmodel->meshlist[i] = (surfmesh_t *)data;data += sizeof(surfmesh_t);
1095         }
1096         for (i = 0, pinmesh = (md3mesh_t *)((unsigned char *)pinmodel + LittleLong(pinmodel->lump_meshes));i < loadmodel->num_surfaces;i++, pinmesh = (md3mesh_t *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_end)))
1097         {
1098                 if (memcmp(pinmesh->identifier, "IDP3", 4))
1099                         Host_Error("Mod_IDP3_Load: invalid mesh identifier (not IDP3)");
1100                 mesh = loadmodel->meshlist[i];
1101                 mesh->num_morphframes = LittleLong(pinmesh->num_frames);
1102                 mesh->num_vertices = LittleLong(pinmesh->num_vertices);
1103                 mesh->num_triangles = LittleLong(pinmesh->num_triangles);
1104                 mesh->data_element3i = (int *)Mem_Alloc(loadmodel->mempool, mesh->num_triangles * sizeof(int[3]));
1105                 mesh->data_neighbor3i = (int *)Mem_Alloc(loadmodel->mempool, mesh->num_triangles * sizeof(int[3]));
1106                 mesh->data_texcoordtexture2f = (float *)Mem_Alloc(loadmodel->mempool, mesh->num_vertices * sizeof(float[2]));
1107                 mesh->data_morphvertex3f = (float *)Mem_Alloc(loadmodel->mempool, mesh->num_vertices * mesh->num_morphframes * sizeof(float[3]));
1108                 for (j = 0;j < mesh->num_triangles * 3;j++)
1109                         mesh->data_element3i[j] = LittleLong(((int *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_elements)))[j]);
1110                 for (j = 0;j < mesh->num_vertices;j++)
1111                 {
1112                         mesh->data_texcoordtexture2f[j * 2 + 0] = LittleFloat(((float *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_texcoords)))[j * 2 + 0]);
1113                         mesh->data_texcoordtexture2f[j * 2 + 1] = LittleFloat(((float *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_texcoords)))[j * 2 + 1]);
1114                 }
1115                 for (j = 0;j < mesh->num_vertices * mesh->num_morphframes;j++)
1116                 {
1117                         mesh->data_morphvertex3f[j * 3 + 0] = LittleShort(((short *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_framevertices)))[j * 4 + 0]) * (1.0f / 64.0f);
1118                         mesh->data_morphvertex3f[j * 3 + 1] = LittleShort(((short *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_framevertices)))[j * 4 + 1]) * (1.0f / 64.0f);
1119                         mesh->data_morphvertex3f[j * 3 + 2] = LittleShort(((short *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_framevertices)))[j * 4 + 2]) * (1.0f / 64.0f);
1120                 }
1121
1122                 Mod_ValidateElements(mesh->data_element3i, mesh->num_triangles, mesh->num_vertices, __FILE__, __LINE__);
1123                 Mod_BuildTriangleNeighbors(mesh->data_neighbor3i, mesh->data_element3i, mesh->num_triangles);
1124                 Mod_Alias_Mesh_CompileFrameZero(mesh);
1125
1126                 if (LittleLong(pinmesh->num_shaders) >= 1)
1127                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + i, skinfiles, pinmesh->name, ((md3shader_t *)((unsigned char *) pinmesh + LittleLong(pinmesh->lump_shaders)))->name);
1128                 else
1129                         for (j = 0;j < loadmodel->numskins;j++)
1130                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i + j * loadmodel->num_surfaces, NULL);
1131
1132                 surface = loadmodel->data_surfaces + i;
1133                 surface->groupmesh = mesh;
1134                 surface->texture = loadmodel->data_textures + i;
1135                 surface->num_firsttriangle = 0;
1136                 surface->num_triangles = mesh->num_triangles;
1137                 surface->num_firstvertex = 0;
1138                 surface->num_vertices = mesh->num_vertices;
1139         }
1140         Mod_CalcAliasModelBBoxes();
1141         Mod_FreeSkinFiles(skinfiles);
1142 }
1143
1144 void Mod_ZYMOTICMODEL_Load(model_t *mod, void *buffer, void *bufferend)
1145 {
1146         zymtype1header_t *pinmodel, *pheader;
1147         unsigned char *pbase;
1148         int i, j, k, l, numposes, *bonecount, *vertbonecounts, count, *renderlist, *renderlistend, *outelements, *remapvertices;
1149         float modelradius, corner[2], *poses, *intexcoord2f, *outtexcoord2f;
1150         zymvertex_t *verts, *vertdata;
1151         zymscene_t *scene;
1152         zymbone_t *bone;
1153         char *shadername;
1154         skinfile_t *skinfiles;
1155         unsigned char *data;
1156         msurface_t *surface;
1157         surfmesh_t *mesh;
1158
1159         pinmodel = (zymtype1header_t *)buffer;
1160         pbase = (unsigned char *)buffer;
1161         if (memcmp(pinmodel->id, "ZYMOTICMODEL", 12))
1162                 Host_Error ("Mod_ZYMOTICMODEL_Load: %s is not a zymotic model");
1163         if (BigLong(pinmodel->type) != 1)
1164                 Host_Error ("Mod_ZYMOTICMODEL_Load: only type 1 (skeletal pose) models are currently supported (name = %s)", loadmodel->name);
1165
1166         loadmodel->type = mod_alias;
1167         loadmodel->flags = 0; // there are no flags on zym models
1168         loadmodel->synctype = ST_RAND;
1169
1170         // byteswap header
1171         pheader = pinmodel;
1172         pheader->type = BigLong(pinmodel->type);
1173         pheader->filesize = BigLong(pinmodel->filesize);
1174         pheader->mins[0] = BigFloat(pinmodel->mins[0]);
1175         pheader->mins[1] = BigFloat(pinmodel->mins[1]);
1176         pheader->mins[2] = BigFloat(pinmodel->mins[2]);
1177         pheader->maxs[0] = BigFloat(pinmodel->maxs[0]);
1178         pheader->maxs[1] = BigFloat(pinmodel->maxs[1]);
1179         pheader->maxs[2] = BigFloat(pinmodel->maxs[2]);
1180         pheader->radius = BigFloat(pinmodel->radius);
1181         pheader->numverts = BigLong(pinmodel->numverts);
1182         pheader->numtris = BigLong(pinmodel->numtris);
1183         pheader->numshaders = BigLong(pinmodel->numshaders);
1184         pheader->numbones = BigLong(pinmodel->numbones);
1185         pheader->numscenes = BigLong(pinmodel->numscenes);
1186         pheader->lump_scenes.start = BigLong(pinmodel->lump_scenes.start);
1187         pheader->lump_scenes.length = BigLong(pinmodel->lump_scenes.length);
1188         pheader->lump_poses.start = BigLong(pinmodel->lump_poses.start);
1189         pheader->lump_poses.length = BigLong(pinmodel->lump_poses.length);
1190         pheader->lump_bones.start = BigLong(pinmodel->lump_bones.start);
1191         pheader->lump_bones.length = BigLong(pinmodel->lump_bones.length);
1192         pheader->lump_vertbonecounts.start = BigLong(pinmodel->lump_vertbonecounts.start);
1193         pheader->lump_vertbonecounts.length = BigLong(pinmodel->lump_vertbonecounts.length);
1194         pheader->lump_verts.start = BigLong(pinmodel->lump_verts.start);
1195         pheader->lump_verts.length = BigLong(pinmodel->lump_verts.length);
1196         pheader->lump_texcoords.start = BigLong(pinmodel->lump_texcoords.start);
1197         pheader->lump_texcoords.length = BigLong(pinmodel->lump_texcoords.length);
1198         pheader->lump_render.start = BigLong(pinmodel->lump_render.start);
1199         pheader->lump_render.length = BigLong(pinmodel->lump_render.length);
1200         pheader->lump_shaders.start = BigLong(pinmodel->lump_shaders.start);
1201         pheader->lump_shaders.length = BigLong(pinmodel->lump_shaders.length);
1202         pheader->lump_trizone.start = BigLong(pinmodel->lump_trizone.start);
1203         pheader->lump_trizone.length = BigLong(pinmodel->lump_trizone.length);
1204
1205         if (pheader->numtris < 1 || pheader->numverts < 3 || pheader->numshaders < 1)
1206         {
1207                 Con_Printf("%s has no geometry\n");
1208                 return;
1209         }
1210         if (pheader->numscenes < 1 || pheader->lump_poses.length < (int)sizeof(float[3][4]))
1211         {
1212                 Con_Printf("%s has no animations\n");
1213                 return;
1214         }
1215
1216         loadmodel->DrawSky = NULL;
1217         loadmodel->Draw = R_Q1BSP_Draw;
1218         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1219         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1220         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1221         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1222
1223         loadmodel->numframes = pheader->numscenes;
1224         loadmodel->num_surfaces = pheader->numshaders;
1225
1226         skinfiles = Mod_LoadSkinFiles();
1227         if (loadmodel->numskins < 1)
1228                 loadmodel->numskins = 1;
1229
1230         // make skinscenes for the skins (no groups)
1231         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
1232         for (i = 0;i < loadmodel->numskins;i++)
1233         {
1234                 loadmodel->skinscenes[i].firstframe = i;
1235                 loadmodel->skinscenes[i].framecount = 1;
1236                 loadmodel->skinscenes[i].loop = true;
1237                 loadmodel->skinscenes[i].framerate = 10;
1238         }
1239
1240         // model bbox
1241         modelradius = pheader->radius;
1242         for (i = 0;i < 3;i++)
1243         {
1244                 loadmodel->normalmins[i] = pheader->mins[i];
1245                 loadmodel->normalmaxs[i] = pheader->maxs[i];
1246                 loadmodel->rotatedmins[i] = -modelradius;
1247                 loadmodel->rotatedmaxs[i] = modelradius;
1248         }
1249         corner[0] = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
1250         corner[1] = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
1251         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
1252         if (loadmodel->yawmaxs[0] > modelradius)
1253                 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelradius;
1254         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -loadmodel->yawmaxs[0];
1255         loadmodel->yawmins[2] = loadmodel->normalmins[2];
1256         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
1257         loadmodel->radius = modelradius;
1258         loadmodel->radius2 = modelradius * modelradius;
1259
1260         // go through the lumps, swapping things
1261
1262         //zymlump_t lump_scenes; // zymscene_t scene[numscenes]; // name and other information for each scene (see zymscene struct)
1263         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numframes);
1264         scene = (zymscene_t *) (pheader->lump_scenes.start + pbase);
1265         numposes = pheader->lump_poses.length / pheader->numbones / sizeof(float[3][4]);
1266         for (i = 0;i < pheader->numscenes;i++)
1267         {
1268                 memcpy(loadmodel->animscenes[i].name, scene->name, 32);
1269                 loadmodel->animscenes[i].firstframe = BigLong(scene->start);
1270                 loadmodel->animscenes[i].framecount = BigLong(scene->length);
1271                 loadmodel->animscenes[i].framerate = BigFloat(scene->framerate);
1272                 loadmodel->animscenes[i].loop = (BigLong(scene->flags) & ZYMSCENEFLAG_NOLOOP) == 0;
1273                 if ((unsigned int) loadmodel->animscenes[i].firstframe >= (unsigned int) numposes)
1274                         Host_Error("%s scene->firstframe (%i) >= numposes (%i)", loadmodel->name, loadmodel->animscenes[i].firstframe, numposes);
1275                 if ((unsigned int) loadmodel->animscenes[i].firstframe + (unsigned int) loadmodel->animscenes[i].framecount > (unsigned int) numposes)
1276                         Host_Error("%s scene->firstframe (%i) + framecount (%i) >= numposes (%i)", loadmodel->name, loadmodel->animscenes[i].firstframe, loadmodel->animscenes[i].framecount, numposes);
1277                 if (loadmodel->animscenes[i].framerate < 0)
1278                         Host_Error("%s scene->framerate (%f) < 0", loadmodel->name, loadmodel->animscenes[i].framerate);
1279                 scene++;
1280         }
1281
1282         //zymlump_t lump_poses; // float pose[numposes][numbones][3][4]; // animation data
1283         loadmodel->num_poses = pheader->lump_poses.length / sizeof(float[3][4]);
1284         loadmodel->data_poses = (float *)Mem_Alloc(loadmodel->mempool, pheader->lump_poses.length);
1285         poses = (float *) (pheader->lump_poses.start + pbase);
1286         for (i = 0;i < pheader->lump_poses.length / 4;i++)
1287                 loadmodel->data_poses[i] = BigFloat(poses[i]);
1288
1289         //zymlump_t lump_bones; // zymbone_t bone[numbones];
1290         loadmodel->num_bones = pheader->numbones;
1291         loadmodel->data_bones = (aliasbone_t *)Mem_Alloc(loadmodel->mempool, pheader->numbones * sizeof(aliasbone_t));
1292         bone = (zymbone_t *) (pheader->lump_bones.start + pbase);
1293         for (i = 0;i < pheader->numbones;i++)
1294         {
1295                 memcpy(loadmodel->data_bones[i].name, bone[i].name, sizeof(bone[i].name));
1296                 loadmodel->data_bones[i].flags = BigLong(bone[i].flags);
1297                 loadmodel->data_bones[i].parent = BigLong(bone[i].parent);
1298                 if (loadmodel->data_bones[i].parent >= i)
1299                         Host_Error("%s bone[%i].parent >= %i", loadmodel->name, i, i);
1300         }
1301
1302         //zymlump_t lump_vertbonecounts; // int vertbonecounts[numvertices]; // how many bones influence each vertex (separate mainly to make this compress better)
1303         vertbonecounts = (int *)Mem_Alloc(loadmodel->mempool, pheader->numverts * sizeof(int));
1304         bonecount = (int *) (pheader->lump_vertbonecounts.start + pbase);
1305         for (i = 0;i < pheader->numverts;i++)
1306         {
1307                 vertbonecounts[i] = BigLong(bonecount[i]);
1308                 if (vertbonecounts[i] < 1)
1309                         Host_Error("%s bonecount[%i] < 1", loadmodel->name, i);
1310         }
1311
1312         //zymlump_t lump_verts; // zymvertex_t vert[numvertices]; // see vertex struct
1313         verts = (zymvertex_t *)Mem_Alloc(loadmodel->mempool, pheader->lump_verts.length);
1314         vertdata = (zymvertex_t *) (pheader->lump_verts.start + pbase);
1315         for (i = 0;i < pheader->lump_verts.length / (int) sizeof(zymvertex_t);i++)
1316         {
1317                 verts[i].bonenum = BigLong(vertdata[i].bonenum);
1318                 verts[i].origin[0] = BigFloat(vertdata[i].origin[0]);
1319                 verts[i].origin[1] = BigFloat(vertdata[i].origin[1]);
1320                 verts[i].origin[2] = BigFloat(vertdata[i].origin[2]);
1321         }
1322
1323         //zymlump_t lump_texcoords; // float texcoords[numvertices][2];
1324         outtexcoord2f = (float *)Mem_Alloc(loadmodel->mempool, pheader->numverts * sizeof(float[2]));
1325         intexcoord2f = (float *) (pheader->lump_texcoords.start + pbase);
1326         for (i = 0;i < pheader->numverts;i++)
1327         {
1328                 outtexcoord2f[i*2+0] = BigFloat(intexcoord2f[i*2+0]);
1329                 // flip T coordinate for OpenGL
1330                 outtexcoord2f[i*2+1] = 1 - BigFloat(intexcoord2f[i*2+1]);
1331         }
1332
1333         //zymlump_t lump_trizone; // byte trizone[numtris]; // see trizone explanation
1334         //loadmodel->alias.zymdata_trizone = Mem_Alloc(loadmodel->mempool, pheader->numtris);
1335         //memcpy(loadmodel->alias.zymdata_trizone, (void *) (pheader->lump_trizone.start + pbase), pheader->numtris);
1336
1337         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
1338         loadmodel->nummeshes = loadmodel->num_surfaces;
1339         loadmodel->num_textures = loadmodel->num_surfaces;
1340         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->nummeshes * sizeof(surfmesh_t *) + loadmodel->nummeshes * sizeof(surfmesh_t) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
1341         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1342         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1343         loadmodel->meshlist = (surfmesh_t **)data;data += loadmodel->num_surfaces * sizeof(surfmesh_t *);
1344         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
1345         for (i = 0;i < loadmodel->num_surfaces;i++)
1346         {
1347                 loadmodel->surfacelist[i] = i;
1348                 loadmodel->meshlist[i] = (surfmesh_t *)data;data += sizeof(surfmesh_t);
1349         }
1350
1351         //zymlump_t lump_shaders; // char shadername[numshaders][32]; // shaders used on this model
1352         //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)
1353         // byteswap, validate, and swap winding order of tris
1354         count = pheader->numshaders * sizeof(int) + pheader->numtris * sizeof(int[3]);
1355         if (pheader->lump_render.length != count)
1356                 Host_Error("%s renderlist is wrong size (%i bytes, should be %i bytes)", loadmodel->name, pheader->lump_render.length, count);
1357         renderlist = (int *) (pheader->lump_render.start + pbase);
1358         renderlistend = (int *) ((unsigned char *) renderlist + pheader->lump_render.length);
1359         for (i = 0;i < loadmodel->num_surfaces;i++)
1360         {
1361                 if (renderlist >= renderlistend)
1362                         Host_Error("%s corrupt renderlist (wrong size)", loadmodel->name);
1363                 count = BigLong(*renderlist);renderlist++;
1364                 if (renderlist + count * 3 > renderlistend || (i == pheader->numshaders - 1 && renderlist + count * 3 != renderlistend))
1365                         Host_Error("%s corrupt renderlist (wrong size)", loadmodel->name);
1366                 mesh = loadmodel->meshlist[i];
1367                 mesh->num_triangles = count;
1368                 mesh->data_element3i = (int *)Mem_Alloc(loadmodel->mempool, mesh->num_triangles * sizeof(int[3]));
1369                 mesh->data_neighbor3i = (int *)Mem_Alloc(loadmodel->mempool, mesh->num_triangles * sizeof(int[3]));
1370                 outelements = mesh->data_element3i;
1371                 for (j = 0;j < mesh->num_triangles;j++)
1372                 {
1373                         outelements[2] = BigLong(renderlist[0]);
1374                         outelements[1] = BigLong(renderlist[1]);
1375                         outelements[0] = BigLong(renderlist[2]);
1376                         if ((unsigned int)outelements[0] >= (unsigned int)pheader->numverts
1377                          || (unsigned int)outelements[1] >= (unsigned int)pheader->numverts
1378                          || (unsigned int)outelements[2] >= (unsigned int)pheader->numverts)
1379                                 Host_Error("%s corrupt renderlist (out of bounds index)", loadmodel->name);
1380                         if (vertbonecounts[outelements[0]] == 0 || vertbonecounts[outelements[1]] == 0 || vertbonecounts[outelements[2]] == 0)
1381                                 Host_Error("%s corrupt renderlist (references vertex with no bone weights", loadmodel->name);
1382                         renderlist += 3;
1383                         outelements += 3;
1384                 }
1385                 remapvertices = (int *)Mem_Alloc(loadmodel->mempool, pheader->numverts * sizeof(int));
1386                 mesh->num_vertices = Mod_BuildVertexRemapTableFromElements(mesh->num_triangles * 3, mesh->data_element3i, pheader->numverts, remapvertices);
1387                 for (j = 0;j < mesh->num_triangles * 3;j++)
1388                         mesh->data_element3i[j] = remapvertices[mesh->data_element3i[j]];
1389                 mesh->data_texcoordtexture2f = (float *)Mem_Alloc(loadmodel->mempool, mesh->num_vertices * sizeof(float[2]));
1390                 for (j = 0;j < pheader->numverts;j++)
1391                 {
1392                         if (remapvertices[j] >= 0)
1393                         {
1394                                 mesh->data_texcoordtexture2f[remapvertices[j]*2+0] = outtexcoord2f[j*2+0];
1395                                 mesh->data_texcoordtexture2f[remapvertices[j]*2+1] = outtexcoord2f[j*2+1];
1396                         }
1397                 }
1398                 mesh->num_vertexboneweights = 0;
1399                 for (j = 0;j < pheader->numverts;j++)
1400                         if (remapvertices[j] >= 0)
1401                                 mesh->num_vertexboneweights += vertbonecounts[remapvertices[j]];
1402                 mesh->data_vertexboneweights = (surfmeshvertexboneweight_t *)Mem_Alloc(loadmodel->mempool, mesh->num_vertexboneweights * sizeof(surfmeshvertexboneweight_t));
1403                 mesh->num_vertexboneweights = 0;
1404                 // note this vertexboneweight ordering requires that the remapvertices array is sequential numbers (separated by -1 values for omitted vertices)
1405                 l = 0;
1406                 for (j = 0;j < pheader->numverts;j++)
1407                 {
1408                         if (remapvertices[j] < 0)
1409                         {
1410                                 l += vertbonecounts[j];
1411                                 continue;
1412                         }
1413                         for (k = 0;k < vertbonecounts[j];k++)
1414                         {
1415                                 // this format really should have had a per vertexweight weight value...
1416                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].vertexindex = remapvertices[j];
1417                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].boneindex = verts[l].bonenum;
1418                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin[3] = 1.0f / vertbonecounts[j];
1419                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin[0] = verts[l].origin[0] * mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin[3];
1420                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin[1] = verts[l].origin[1] * mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin[3];
1421                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin[2] = verts[l].origin[2] * mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin[3];
1422                                 mesh->num_vertexboneweights++;
1423                                 l++;
1424                         }
1425                 }
1426                 shadername = (char *) (pheader->lump_shaders.start + pbase) + i * 32;
1427                 // since zym models do not have named sections, reuse their shader
1428                 // name as the section name
1429                 if (shadername[0])
1430                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + i, skinfiles, shadername, shadername);
1431                 else
1432                         for (j = 0;j < loadmodel->numskins;j++)
1433                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i + j * loadmodel->num_surfaces, NULL);
1434
1435                 Mod_ValidateElements(mesh->data_element3i, mesh->num_triangles, mesh->num_vertices, __FILE__, __LINE__);
1436                 Mod_BuildTriangleNeighbors(mesh->data_neighbor3i, mesh->data_element3i, mesh->num_triangles);
1437                 Mod_Alias_Mesh_CompileFrameZero(mesh);
1438
1439                 surface = loadmodel->data_surfaces + i;
1440                 surface->groupmesh = mesh;
1441                 surface->texture = loadmodel->data_textures + i;
1442                 surface->num_firsttriangle = 0;
1443                 surface->num_triangles = mesh->num_triangles;
1444                 surface->num_firstvertex = 0;
1445                 surface->num_vertices = mesh->num_vertices;
1446         }
1447
1448         Mem_Free(vertbonecounts);
1449         Mem_Free(verts);
1450         Mem_Free(outtexcoord2f);
1451 }
1452
1453 void Mod_DARKPLACESMODEL_Load(model_t *mod, void *buffer, void *bufferend)
1454 {
1455         dpmheader_t *pheader;
1456         dpmframe_t *frame;
1457         dpmbone_t *bone;
1458         dpmmesh_t *dpmmesh;
1459         unsigned char *pbase;
1460         int i, j, k;
1461         skinfile_t *skinfiles;
1462         unsigned char *data;
1463
1464         pheader = (dpmheader_t *)buffer;
1465         pbase = (unsigned char *)buffer;
1466         if (memcmp(pheader->id, "DARKPLACESMODEL\0", 16))
1467                 Host_Error ("Mod_DARKPLACESMODEL_Load: %s is not a darkplaces model");
1468         if (BigLong(pheader->type) != 2)
1469                 Host_Error ("Mod_DARKPLACESMODEL_Load: only type 2 (hierarchical skeletal pose) models are currently supported (name = %s)", loadmodel->name);
1470
1471         loadmodel->type = mod_alias;
1472         loadmodel->flags = 0; // there are no flags on zym models
1473         loadmodel->synctype = ST_RAND;
1474
1475         // byteswap header
1476         pheader->type = BigLong(pheader->type);
1477         pheader->filesize = BigLong(pheader->filesize);
1478         pheader->mins[0] = BigFloat(pheader->mins[0]);
1479         pheader->mins[1] = BigFloat(pheader->mins[1]);
1480         pheader->mins[2] = BigFloat(pheader->mins[2]);
1481         pheader->maxs[0] = BigFloat(pheader->maxs[0]);
1482         pheader->maxs[1] = BigFloat(pheader->maxs[1]);
1483         pheader->maxs[2] = BigFloat(pheader->maxs[2]);
1484         pheader->yawradius = BigFloat(pheader->yawradius);
1485         pheader->allradius = BigFloat(pheader->allradius);
1486         pheader->num_bones = BigLong(pheader->num_bones);
1487         pheader->num_meshs = BigLong(pheader->num_meshs);
1488         pheader->num_frames = BigLong(pheader->num_frames);
1489         pheader->ofs_bones = BigLong(pheader->ofs_bones);
1490         pheader->ofs_meshs = BigLong(pheader->ofs_meshs);
1491         pheader->ofs_frames = BigLong(pheader->ofs_frames);
1492
1493         if (pheader->num_bones < 1 || pheader->num_meshs < 1)
1494         {
1495                 Con_Printf("%s has no geometry\n");
1496                 return;
1497         }
1498         if (pheader->num_frames < 1)
1499         {
1500                 Con_Printf("%s has no frames\n");
1501                 return;
1502         }
1503
1504         loadmodel->DrawSky = NULL;
1505         loadmodel->Draw = R_Q1BSP_Draw;
1506         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1507         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1508         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1509         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1510
1511         // model bbox
1512         for (i = 0;i < 3;i++)
1513         {
1514                 loadmodel->normalmins[i] = pheader->mins[i];
1515                 loadmodel->normalmaxs[i] = pheader->maxs[i];
1516                 loadmodel->yawmins[i] = i != 2 ? -pheader->yawradius : pheader->mins[i];
1517                 loadmodel->yawmaxs[i] = i != 2 ? pheader->yawradius : pheader->maxs[i];
1518                 loadmodel->rotatedmins[i] = -pheader->allradius;
1519                 loadmodel->rotatedmaxs[i] = pheader->allradius;
1520         }
1521         loadmodel->radius = pheader->allradius;
1522         loadmodel->radius2 = pheader->allradius * pheader->allradius;
1523
1524         // load external .skin files if present
1525         skinfiles = Mod_LoadSkinFiles();
1526         if (loadmodel->numskins < 1)
1527                 loadmodel->numskins = 1;
1528
1529         loadmodel->numframes = pheader->num_frames;
1530         loadmodel->num_bones = pheader->num_bones;
1531         loadmodel->num_poses = loadmodel->num_bones * loadmodel->numframes;
1532         loadmodel->num_textures = loadmodel->nummeshes = loadmodel->nummodelsurfaces = loadmodel->num_surfaces = pheader->num_meshs;
1533
1534         // do most allocations as one merged chunk
1535         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->nummeshes * sizeof(surfmesh_t *) + loadmodel->nummeshes * sizeof(surfmesh_t) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + loadmodel->numskins * sizeof(animscene_t) + loadmodel->num_bones * sizeof(aliasbone_t) + loadmodel->num_poses * sizeof(float[12]) + loadmodel->numframes * sizeof(animscene_t));
1536         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1537         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1538         loadmodel->meshlist = (surfmesh_t **)data;data += loadmodel->num_surfaces * sizeof(surfmesh_t *);
1539         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
1540         loadmodel->skinscenes = (animscene_t *)data;data += loadmodel->numskins * sizeof(animscene_t);
1541         loadmodel->data_bones = (aliasbone_t *)data;data += loadmodel->num_bones * sizeof(aliasbone_t);
1542         loadmodel->data_poses = (float *)data;data += loadmodel->num_poses * sizeof(float[12]);
1543         loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
1544         for (i = 0;i < loadmodel->numskins;i++)
1545         {
1546                 loadmodel->skinscenes[i].firstframe = i;
1547                 loadmodel->skinscenes[i].framecount = 1;
1548                 loadmodel->skinscenes[i].loop = true;
1549                 loadmodel->skinscenes[i].framerate = 10;
1550         }
1551         for (i = 0;i < loadmodel->num_surfaces;i++)
1552         {
1553                 loadmodel->surfacelist[i] = i;
1554                 loadmodel->meshlist[i] = (surfmesh_t *)data;data += sizeof(surfmesh_t);
1555         }
1556
1557         // load the bone info
1558         bone = (dpmbone_t *) (pbase + pheader->ofs_bones);
1559         for (i = 0;i < loadmodel->num_bones;i++)
1560         {
1561                 memcpy(loadmodel->data_bones[i].name, bone[i].name, sizeof(bone[i].name));
1562                 loadmodel->data_bones[i].flags = BigLong(bone[i].flags);
1563                 loadmodel->data_bones[i].parent = BigLong(bone[i].parent);
1564                 if (loadmodel->data_bones[i].parent >= i)
1565                         Host_Error("%s bone[%i].parent >= %i", loadmodel->name, i, i);
1566         }
1567
1568         // load the frames
1569         frame = (dpmframe_t *) (pbase + pheader->ofs_frames);
1570         for (i = 0;i < loadmodel->numframes;i++)
1571         {
1572                 const float *poses;
1573                 memcpy(loadmodel->animscenes[i].name, frame->name, sizeof(frame->name));
1574                 loadmodel->animscenes[i].firstframe = i;
1575                 loadmodel->animscenes[i].framecount = 1;
1576                 loadmodel->animscenes[i].loop = true;
1577                 loadmodel->animscenes[i].framerate = 10;
1578                 // load the bone poses for this frame
1579                 poses = (float *) (pbase + BigLong(frame->ofs_bonepositions));
1580                 for (j = 0;j < loadmodel->num_bones*12;j++)
1581                         loadmodel->data_poses[i * loadmodel->num_bones*12 + j] = BigFloat(poses[j]);
1582                 // stuff not processed here: mins, maxs, yawradius, allradius
1583                 frame++;
1584         }
1585
1586         // load the meshes now
1587         dpmmesh = (dpmmesh_t *) (pbase + pheader->ofs_meshs);
1588         for (i = 0;i < loadmodel->num_surfaces;i++)
1589         {
1590                 const int *inelements;
1591                 int *outelements;
1592                 const float *intexcoord;
1593                 surfmesh_t *mesh;
1594                 msurface_t *surface;
1595
1596                 mesh = loadmodel->meshlist[i];
1597                 mesh->num_triangles = BigLong(dpmmesh->num_tris);
1598                 mesh->num_vertices = BigLong(dpmmesh->num_verts);
1599
1600                 // to find out how many weights exist we two a two-stage load...
1601                 mesh->num_vertexboneweights = 0;
1602                 data = (unsigned char *) (pbase + BigLong(dpmmesh->ofs_verts));
1603                 for (j = 0;j < mesh->num_vertices;j++)
1604                 {
1605                         int numweights = BigLong(((dpmvertex_t *)data)->numbones);
1606                         mesh->num_vertexboneweights += numweights;
1607                         data += sizeof(dpmvertex_t);
1608                         data += numweights * sizeof(dpmbonevert_t);
1609                 }
1610
1611                 // allocate things now that we know how many
1612                 mesh->data_vertexboneweights = (surfmeshvertexboneweight_t *)Mem_Alloc(loadmodel->mempool, mesh->num_vertexboneweights * sizeof(surfmeshvertexboneweight_t));
1613                 mesh->data_element3i = (int *)Mem_Alloc(loadmodel->mempool, mesh->num_triangles * sizeof(int[3]));
1614                 mesh->data_neighbor3i = (int *)Mem_Alloc(loadmodel->mempool, mesh->num_triangles * sizeof(int[3]));
1615                 mesh->data_texcoordtexture2f = (float *)Mem_Alloc(loadmodel->mempool, mesh->num_vertices * sizeof(float[2]));
1616
1617                 inelements = (int *) (pbase + BigLong(dpmmesh->ofs_indices));
1618                 outelements = mesh->data_element3i;
1619                 for (j = 0;j < mesh->num_triangles;j++)
1620                 {
1621                         // swap element order to flip triangles, because Quake uses clockwise (rare) and dpm uses counterclockwise (standard)
1622                         outelements[0] = BigLong(inelements[2]);
1623                         outelements[1] = BigLong(inelements[1]);
1624                         outelements[2] = BigLong(inelements[0]);
1625                         inelements += 3;
1626                         outelements += 3;
1627                 }
1628
1629                 intexcoord = (float *) (pbase + BigLong(dpmmesh->ofs_texcoords));
1630                 for (j = 0;j < mesh->num_vertices*2;j++)
1631                         mesh->data_texcoordtexture2f[j] = BigFloat(intexcoord[j]);
1632
1633                 // now load them for real
1634                 mesh->num_vertexboneweights = 0;
1635                 data = (unsigned char *) (pbase + BigLong(dpmmesh->ofs_verts));
1636                 for (j = 0;j < mesh->num_vertices;j++)
1637                 {
1638                         int numweights = BigLong(((dpmvertex_t *)data)->numbones);
1639                         data += sizeof(dpmvertex_t);
1640                         for (k = 0;k < numweights;k++)
1641                         {
1642                                 const dpmbonevert_t *vert = (dpmbonevert_t *) data;
1643                                 // stuff not processed here: normal
1644                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].vertexindex = j;
1645                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].boneindex = BigLong(vert->bonenum);
1646                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin[0] = BigFloat(vert->origin[0]);
1647                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin[1] = BigFloat(vert->origin[1]);
1648                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin[2] = BigFloat(vert->origin[2]);
1649                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin[3] = BigFloat(vert->influence);
1650                                 mesh->num_vertexboneweights++;
1651                                 data += sizeof(dpmbonevert_t);
1652                         }
1653                 }
1654
1655                 // since dpm models do not have named sections, reuse their shader name as the section name
1656                 if (dpmmesh->shadername[0])
1657                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + i, skinfiles, dpmmesh->shadername, dpmmesh->shadername);
1658                 else
1659                         for (j = 0;j < loadmodel->numskins;j++)
1660                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i + j * loadmodel->num_surfaces, NULL);
1661
1662                 Mod_ValidateElements(mesh->data_element3i, mesh->num_triangles, mesh->num_vertices, __FILE__, __LINE__);
1663                 Mod_BuildTriangleNeighbors(mesh->data_neighbor3i, mesh->data_element3i, mesh->num_triangles);
1664                 Mod_Alias_Mesh_CompileFrameZero(mesh);
1665
1666                 surface = loadmodel->data_surfaces + i;
1667                 surface->groupmesh = mesh;
1668                 surface->texture = loadmodel->data_textures + i;
1669                 surface->num_firsttriangle = 0;
1670                 surface->num_triangles = mesh->num_triangles;
1671                 surface->num_firstvertex = 0;
1672                 surface->num_vertices = mesh->num_vertices;
1673
1674                 dpmmesh++;
1675         }
1676 }
1677
1678 static void Mod_PSKMODEL_AnimKeyToMatrix(float *origin, float *quat, matrix4x4_t *m)
1679 {
1680         float x = quat[0], y = quat[1], z = quat[2], w = quat[3];
1681         m->m[0][0]=1-2*(y*y+z*z);m->m[0][1]=  2*(x*y-z*w);m->m[0][2]=  2*(x*z+y*w);m->m[0][3]=origin[0];
1682         m->m[1][0]=  2*(x*y+z*w);m->m[1][1]=1-2*(x*x+z*z);m->m[1][2]=  2*(y*z-x*w);m->m[1][3]=origin[1];
1683         m->m[2][0]=  2*(x*z-y*w);m->m[2][1]=  2*(y*z+x*w);m->m[2][2]=1-2*(x*x+y*y);m->m[2][3]=origin[2];
1684         m->m[3][0]=  0          ;m->m[3][1]=  0          ;m->m[3][2]=  0          ;m->m[3][3]=1;
1685 }
1686
1687 // no idea why PSK/PSA files contain weird quaternions but they do...
1688 #define PSKQUATNEGATIONS
1689 void Mod_PSKMODEL_Load(model_t *mod, void *buffer, void *bufferend)
1690 {
1691         int i, j, index, version, recordsize, numrecords;
1692         int numpnts, numvtxw, numfaces, nummatts, numbones, numrawweights, numanimbones, numanims, numanimkeys;
1693         fs_offset_t filesize;
1694         pskpnts_t *pnts;
1695         pskvtxw_t *vtxw;
1696         pskface_t *faces;
1697         pskmatt_t *matts;
1698         pskboneinfo_t *bones;
1699         pskrawweights_t *rawweights;
1700         pskboneinfo_t *animbones;
1701         pskaniminfo_t *anims;
1702         pskanimkeys_t *animkeys;
1703         void *animfilebuffer, *animbuffer, *animbufferend;
1704         pskchunk_t *pchunk;
1705         surfmesh_t *mesh;
1706         skinfile_t *skinfiles;
1707         char animname[MAX_QPATH];
1708
1709         pchunk = (pskchunk_t *)buffer;
1710         if (strcmp(pchunk->id, "ACTRHEAD"))
1711                 Host_Error ("Mod_PSKMODEL_Load: %s is not an Unreal Engine ActorX (.psk + .psa) model");
1712
1713         loadmodel->type = mod_alias;
1714         loadmodel->DrawSky = NULL;
1715         loadmodel->Draw = R_Q1BSP_Draw;
1716         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1717         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1718         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1719         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1720         loadmodel->flags = 0; // there are no flags on zym models
1721         loadmodel->synctype = ST_RAND;
1722
1723         // load external .skin files if present
1724         skinfiles = Mod_LoadSkinFiles();
1725         if (loadmodel->numskins < 1)
1726                 loadmodel->numskins = 1;
1727         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, loadmodel->numskins * sizeof(animscene_t));
1728         for (i = 0;i < loadmodel->numskins;i++)
1729         {
1730                 loadmodel->skinscenes[i].firstframe = i;
1731                 loadmodel->skinscenes[i].framecount = 1;
1732                 loadmodel->skinscenes[i].loop = true;
1733                 loadmodel->skinscenes[i].framerate = 10;
1734         }
1735
1736         FS_StripExtension(loadmodel->name, animname, sizeof(animname));
1737         strlcat(animname, ".psa", sizeof(animname));
1738         animbuffer = animfilebuffer = FS_LoadFile(animname, loadmodel->mempool, false, &filesize);
1739         animbufferend = (void *)((unsigned char*)animbuffer + (int)filesize);
1740         if (animbuffer == NULL)
1741                 Host_Error("%s: can't find .psa file (%s)", loadmodel->name, animname);
1742
1743         numpnts = 0;
1744         pnts = NULL;
1745         numvtxw = 0;
1746         vtxw = NULL;
1747         numfaces = 0;
1748         faces = NULL;
1749         nummatts = 0;
1750         matts = NULL;
1751         numbones = 0;
1752         bones = NULL;
1753         numrawweights = 0;
1754         rawweights = NULL;
1755         numanims = 0;
1756         anims = NULL;
1757         numanimkeys = 0;
1758         animkeys = NULL;
1759
1760         while (buffer < bufferend)
1761         {
1762                 pchunk = (pskchunk_t *)buffer;
1763                 buffer = (void *)((unsigned char *)buffer + sizeof(pskchunk_t));
1764                 version = LittleLong(pchunk->version);
1765                 recordsize = LittleLong(pchunk->recordsize);
1766                 numrecords = LittleLong(pchunk->numrecords);
1767                 if (developer.integer)
1768                         Con_Printf("%s: %s %x: %i * %i = %i\n", loadmodel->name, pchunk->id, version, recordsize, numrecords, recordsize * numrecords);
1769                 if (version != 0x1e83b9 && version != 0x1e9179 && version != 0x2e)
1770                         Con_Printf ("%s: chunk %s has unknown version %x (0x1e83b9, 0x1e9179 and 0x2e are currently supported), trying to load anyway!\n", loadmodel->name, pchunk->id, version);
1771                 if (!strcmp(pchunk->id, "ACTRHEAD"))
1772                 {
1773                         // nothing to do
1774                 }
1775                 else if (!strcmp(pchunk->id, "PNTS0000"))
1776                 {
1777                         pskpnts_t *p;
1778                         if (recordsize != sizeof(*p))
1779                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
1780                         // byteswap in place and keep the pointer
1781                         numpnts = numrecords;
1782                         pnts = (pskpnts_t *)buffer;
1783                         for (index = 0, p = (pskpnts_t *)buffer;index < numrecords;index++, p++)
1784                         {
1785                                 p->origin[0] = LittleFloat(p->origin[0]);
1786                                 p->origin[1] = LittleFloat(p->origin[1]);
1787                                 p->origin[2] = LittleFloat(p->origin[2]);
1788                         }
1789                         buffer = p;
1790                 }
1791                 else if (!strcmp(pchunk->id, "VTXW0000"))
1792                 {
1793                         pskvtxw_t *p;
1794                         if (recordsize != sizeof(*p))
1795                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
1796                         // byteswap in place and keep the pointer
1797                         numvtxw = numrecords;
1798                         vtxw = (pskvtxw_t *)buffer;
1799                         for (index = 0, p = (pskvtxw_t *)buffer;index < numrecords;index++, p++)
1800                         {
1801                                 p->pntsindex = LittleShort(p->pntsindex);
1802                                 p->texcoord[0] = LittleFloat(p->texcoord[0]);
1803                                 p->texcoord[1] = LittleFloat(p->texcoord[1]);
1804                                 if (p->pntsindex >= numpnts)
1805                                 {
1806                                         Con_Printf("%s: vtxw->pntsindex %i >= numpnts %i\n", loadmodel->name, p->pntsindex, numpnts);
1807                                         p->pntsindex = 0;
1808                                 }
1809                         }
1810                         buffer = p;
1811                 }
1812                 else if (!strcmp(pchunk->id, "FACE0000"))
1813                 {
1814                         pskface_t *p;
1815                         if (recordsize != sizeof(*p))
1816                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
1817                         // byteswap in place and keep the pointer
1818                         numfaces = numrecords;
1819                         faces = (pskface_t *)buffer;
1820                         for (index = 0, p = (pskface_t *)buffer;index < numrecords;index++, p++)
1821                         {
1822                                 p->vtxwindex[0] = LittleShort(p->vtxwindex[0]);
1823                                 p->vtxwindex[1] = LittleShort(p->vtxwindex[1]);
1824                                 p->vtxwindex[2] = LittleShort(p->vtxwindex[2]);
1825                                 p->group = LittleLong(p->group);
1826                                 if (p->vtxwindex[0] >= numvtxw)
1827                                 {
1828                                         Con_Printf("%s: face->vtxwindex[0] %i >= numvtxw %i\n", loadmodel->name, p->vtxwindex[0], numvtxw);
1829                                         p->vtxwindex[0] = 0;
1830                                 }
1831                                 if (p->vtxwindex[1] >= numvtxw)
1832                                 {
1833                                         Con_Printf("%s: face->vtxwindex[1] %i >= numvtxw %i\n", loadmodel->name, p->vtxwindex[1], numvtxw);
1834                                         p->vtxwindex[1] = 0;
1835                                 }
1836                                 if (p->vtxwindex[2] >= numvtxw)
1837                                 {
1838                                         Con_Printf("%s: face->vtxwindex[2] %i >= numvtxw %i\n", loadmodel->name, p->vtxwindex[2], numvtxw);
1839                                         p->vtxwindex[2] = 0;
1840                                 }
1841                         }
1842                         buffer = p;
1843                 }
1844                 else if (!strcmp(pchunk->id, "MATT0000"))
1845                 {
1846                         pskmatt_t *p;
1847                         if (recordsize != sizeof(*p))
1848                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
1849                         // byteswap in place and keep the pointer
1850                         nummatts = numrecords;
1851                         matts = (pskmatt_t *)buffer;
1852                         for (index = 0, p = (pskmatt_t *)buffer;index < numrecords;index++, p++)
1853                         {
1854                         }
1855                         buffer = p;
1856                 }
1857                 else if (!strcmp(pchunk->id, "REFSKELT"))
1858                 {
1859                         pskboneinfo_t *p;
1860                         if (recordsize != sizeof(*p))
1861                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
1862                         // byteswap in place and keep the pointer
1863                         numbones = numrecords;
1864                         bones = (pskboneinfo_t *)buffer;
1865                         for (index = 0, p = (pskboneinfo_t *)buffer;index < numrecords;index++, p++)
1866                         {
1867                                 p->numchildren = LittleLong(p->numchildren);
1868                                 p->parent = LittleLong(p->parent);
1869                                 p->basepose.quat[0] = LittleFloat(p->basepose.quat[0]);
1870                                 p->basepose.quat[1] = LittleFloat(p->basepose.quat[1]);
1871                                 p->basepose.quat[2] = LittleFloat(p->basepose.quat[2]);
1872                                 p->basepose.quat[3] = LittleFloat(p->basepose.quat[3]);
1873                                 p->basepose.origin[0] = LittleFloat(p->basepose.origin[0]);
1874                                 p->basepose.origin[1] = LittleFloat(p->basepose.origin[1]);
1875                                 p->basepose.origin[2] = LittleFloat(p->basepose.origin[2]);
1876                                 p->basepose.unknown = LittleFloat(p->basepose.unknown);
1877                                 p->basepose.size[0] = LittleFloat(p->basepose.size[0]);
1878                                 p->basepose.size[1] = LittleFloat(p->basepose.size[1]);
1879                                 p->basepose.size[2] = LittleFloat(p->basepose.size[2]);
1880 #ifdef PSKQUATNEGATIONS
1881                                 if (index)
1882                                 {
1883                                         p->basepose.quat[0] *= -1;
1884                                         p->basepose.quat[1] *= -1;
1885                                         p->basepose.quat[2] *= -1;
1886                                 }
1887                                 else
1888                                 {
1889                                         p->basepose.quat[0] *=  1;
1890                                         p->basepose.quat[1] *= -1;
1891                                         p->basepose.quat[2] *=  1;
1892                                 }
1893 #endif
1894                                 if (p->parent < 0 || p->parent >= numbones)
1895                                 {
1896                                         Con_Printf("%s: bone->parent %i >= numbones %i\n", loadmodel->name, p->parent, numbones);
1897                                         p->parent = 0;
1898                                 }
1899                         }
1900                         buffer = p;
1901                 }
1902                 else if (!strcmp(pchunk->id, "RAWWEIGHTS"))
1903                 {
1904                         pskrawweights_t *p;
1905                         if (recordsize != sizeof(*p))
1906                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
1907                         // byteswap in place and keep the pointer
1908                         numrawweights = numrecords;
1909                         rawweights = (pskrawweights_t *)buffer;
1910                         for (index = 0, p = (pskrawweights_t *)buffer;index < numrecords;index++, p++)
1911                         {
1912                                 p->weight = LittleFloat(p->weight);
1913                                 p->pntsindex = LittleLong(p->pntsindex);
1914                                 p->boneindex = LittleLong(p->boneindex);
1915                                 if (p->pntsindex < 0 || p->pntsindex >= numpnts)
1916                                 {
1917                                         Con_Printf("%s: weight->pntsindex %i >= numpnts %i\n", loadmodel->name, p->pntsindex, numpnts);
1918                                         p->pntsindex = 0;
1919                                 }
1920                                 if (p->boneindex < 0 || p->boneindex >= numbones)
1921                                 {
1922                                         Con_Printf("%s: weight->boneindex %i >= numbones %i\n", loadmodel->name, p->boneindex, numbones);
1923                                         p->boneindex = 0;
1924                                 }
1925                         }
1926                         buffer = p;
1927                 }
1928         }
1929
1930         while (animbuffer < animbufferend)
1931         {
1932                 pchunk = (pskchunk_t *)animbuffer;
1933                 animbuffer = (void *)((unsigned char *)animbuffer + sizeof(pskchunk_t));
1934                 version = LittleLong(pchunk->version);
1935                 recordsize = LittleLong(pchunk->recordsize);
1936                 numrecords = LittleLong(pchunk->numrecords);
1937                 if (developer.integer)
1938                         Con_Printf("%s: %s %x: %i * %i = %i\n", animname, pchunk->id, version, recordsize, numrecords, recordsize * numrecords);
1939                 if (version != 0x1e83b9 && version != 0x1e9179 && version != 0x2e)
1940                         Con_Printf ("%s: chunk %s has unknown version %x (0x1e83b9, 0x1e9179 and 0x2e are currently supported), trying to load anyway!\n", animname, pchunk->id, version);
1941                 if (!strcmp(pchunk->id, "ANIMHEAD"))
1942                 {
1943                         // nothing to do
1944                 }
1945                 else if (!strcmp(pchunk->id, "BONENAMES"))
1946                 {
1947                         pskboneinfo_t *p;
1948                         if (recordsize != sizeof(*p))
1949                                 Host_Error("%s: %s has unsupported recordsize", animname, pchunk->id);
1950                         // byteswap in place and keep the pointer
1951                         numanimbones = numrecords;
1952                         animbones = (pskboneinfo_t *)animbuffer;
1953                         // NOTE: supposedly psa does not need to match the psk model, the
1954                         // bones missing from the psa would simply use their base
1955                         // positions from the psk, but this is hard for me to implement
1956                         // and people can easily make animations that match.
1957                         if (numanimbones != numbones)
1958                                 Host_Error("%s: this loader only supports animations with the same bones as the mesh");
1959                         for (index = 0, p = (pskboneinfo_t *)animbuffer;index < numrecords;index++, p++)
1960                         {
1961                                 p->numchildren = LittleLong(p->numchildren);
1962                                 p->parent = LittleLong(p->parent);
1963                                 p->basepose.quat[0] = LittleFloat(p->basepose.quat[0]);
1964                                 p->basepose.quat[1] = LittleFloat(p->basepose.quat[1]);
1965                                 p->basepose.quat[2] = LittleFloat(p->basepose.quat[2]);
1966                                 p->basepose.quat[3] = LittleFloat(p->basepose.quat[3]);
1967                                 p->basepose.origin[0] = LittleFloat(p->basepose.origin[0]);
1968                                 p->basepose.origin[1] = LittleFloat(p->basepose.origin[1]);
1969                                 p->basepose.origin[2] = LittleFloat(p->basepose.origin[2]);
1970                                 p->basepose.unknown = LittleFloat(p->basepose.unknown);
1971                                 p->basepose.size[0] = LittleFloat(p->basepose.size[0]);
1972                                 p->basepose.size[1] = LittleFloat(p->basepose.size[1]);
1973                                 p->basepose.size[2] = LittleFloat(p->basepose.size[2]);
1974 #ifdef PSKQUATNEGATIONS
1975                                 if (index)
1976                                 {
1977                                         p->basepose.quat[0] *= -1;
1978                                         p->basepose.quat[1] *= -1;
1979                                         p->basepose.quat[2] *= -1;
1980                                 }
1981                                 else
1982                                 {
1983                                         p->basepose.quat[0] *=  1;
1984                                         p->basepose.quat[1] *= -1;
1985                                         p->basepose.quat[2] *=  1;
1986                                 }
1987 #endif
1988                                 if (p->parent < 0 || p->parent >= numanimbones)
1989                                 {
1990                                         Con_Printf("%s: bone->parent %i >= numanimbones %i\n", animname, p->parent, numanimbones);
1991                                         p->parent = 0;
1992                                 }
1993                                 // check that bones are the same as in the base
1994                                 if (strcmp(p->name, bones[index].name) || p->parent != bones[index].parent)
1995                                         Host_Error("%s: this loader only supports animations with the same bones as the mesh", animname);
1996                         }
1997                         animbuffer = p;
1998                 }
1999                 else if (!strcmp(pchunk->id, "ANIMINFO"))
2000                 {
2001                         pskaniminfo_t *p;
2002                         if (recordsize != sizeof(*p))
2003                                 Host_Error("%s: %s has unsupported recordsize", animname, pchunk->id);
2004                         // byteswap in place and keep the pointer
2005                         numanims = numrecords;
2006                         anims = (pskaniminfo_t *)animbuffer;
2007                         for (index = 0, p = (pskaniminfo_t *)animbuffer;index < numrecords;index++, p++)
2008                         {
2009                                 p->numbones = LittleLong(p->numbones);
2010                                 p->playtime = LittleFloat(p->playtime);
2011                                 p->fps = LittleFloat(p->fps);
2012                                 p->firstframe = LittleLong(p->firstframe);
2013                                 p->numframes = LittleLong(p->numframes);
2014                                 if (p->numbones != numbones)
2015                                 {
2016                                         Con_Printf("%s: animinfo->numbones != numbones, trying to load anyway!\n", animname);
2017                                 }
2018                         }
2019                         animbuffer = p;
2020                 }
2021                 else if (!strcmp(pchunk->id, "ANIMKEYS"))
2022                 {
2023                         pskanimkeys_t *p;
2024                         if (recordsize != sizeof(*p))
2025                                 Host_Error("%s: %s has unsupported recordsize", animname, pchunk->id);
2026                         numanimkeys = numrecords;
2027                         animkeys = (pskanimkeys_t *)animbuffer;
2028                         for (index = 0, p = (pskanimkeys_t *)animbuffer;index < numrecords;index++, p++)
2029                         {
2030                                 p->origin[0] = LittleFloat(p->origin[0]);
2031                                 p->origin[1] = LittleFloat(p->origin[1]);
2032                                 p->origin[2] = LittleFloat(p->origin[2]);
2033                                 p->quat[0] = LittleFloat(p->quat[0]);
2034                                 p->quat[1] = LittleFloat(p->quat[1]);
2035                                 p->quat[2] = LittleFloat(p->quat[2]);
2036                                 p->quat[3] = LittleFloat(p->quat[3]);
2037                                 p->frametime = LittleFloat(p->frametime);
2038 #ifdef PSKQUATNEGATIONS
2039                                 if (index % numbones)
2040                                 {
2041                                         p->quat[0] *= -1;
2042                                         p->quat[1] *= -1;
2043                                         p->quat[2] *= -1;
2044                                 }
2045                                 else
2046                                 {
2047                                         p->quat[0] *=  1;
2048                                         p->quat[1] *= -1;
2049                                         p->quat[2] *=  1;
2050                                 }
2051 #endif
2052                         }
2053                         animbuffer = p;
2054                         // TODO: allocate bonepose stuff
2055                 }
2056                 else
2057                         Con_Printf("%s: unknown chunk ID \"%s\"\n", animname, pchunk->id);
2058         }
2059
2060         if (!numpnts || !pnts || !numvtxw || !vtxw || !numfaces || !faces || !nummatts || !matts || !numbones || !bones || !numrawweights || !rawweights || !numanims || !anims || !numanimkeys || !animkeys)
2061                 Host_Error("%s: missing required chunks", loadmodel->name);
2062
2063         // FIXME: model bbox
2064         // model bbox
2065         for (i = 0;i < 3;i++)
2066         {
2067                 loadmodel->normalmins[i] = -128;
2068                 loadmodel->normalmaxs[i] = 128;
2069                 loadmodel->yawmins[i] = -128;
2070                 loadmodel->yawmaxs[i] = 128;
2071                 loadmodel->rotatedmins[i] = -128;
2072                 loadmodel->rotatedmaxs[i] = 128;
2073         }
2074         loadmodel->radius = 128;
2075         loadmodel->radius2 = loadmodel->radius * loadmodel->radius;
2076
2077         loadmodel->numframes = 0;
2078         for (index = 0;index < numanims;index++)
2079                 loadmodel->numframes += anims[index].numframes;
2080
2081         loadmodel->num_bones = numbones;
2082         loadmodel->num_poses = loadmodel->num_bones * loadmodel->numframes;
2083         loadmodel->num_textures = loadmodel->nummeshes = loadmodel->nummodelsurfaces = loadmodel->num_surfaces = nummatts;
2084
2085         if (numanimkeys != loadmodel->num_bones * loadmodel->numframes)
2086                 Host_Error("%s: %s has incorrect number of animation keys", animname, pchunk->id);
2087
2088         loadmodel->data_poses = (float *)Mem_Alloc(loadmodel->mempool, loadmodel->num_poses * sizeof(float[12]));
2089         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, loadmodel->numframes * sizeof(animscene_t));
2090         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
2091         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t));
2092         loadmodel->surfacelist = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(int));
2093         loadmodel->data_bones = (aliasbone_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_bones * sizeof(aliasbone_t));
2094
2095         loadmodel->meshlist = (surfmesh_t **)Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t *));
2096         mesh = loadmodel->meshlist[0] = (surfmesh_t *)Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t));
2097         mesh->num_vertices = numvtxw;
2098         mesh->num_triangles = numfaces;
2099         mesh->data_element3i = (int *)Mem_Alloc(loadmodel->mempool, mesh->num_triangles * sizeof(int[3]));
2100         mesh->data_neighbor3i = (int *)Mem_Alloc(loadmodel->mempool, mesh->num_triangles * sizeof(int[3]));
2101         mesh->data_texcoordtexture2f = (float *)Mem_Alloc(loadmodel->mempool, mesh->num_vertices * sizeof(float[2]));
2102
2103         // create surfaces
2104         for (index = 0, i = 0;index < nummatts;index++)
2105         {
2106                 // since psk models do not have named sections, reuse their shader name as the section name
2107                 if (matts[index].name[0])
2108                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + index, skinfiles, matts[index].name, matts[index].name);
2109                 else
2110                         for (j = 0;j < loadmodel->numskins;j++)
2111                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + index + j * loadmodel->num_surfaces, NULL);
2112                 loadmodel->surfacelist[index] = index;
2113                 loadmodel->data_surfaces[index].groupmesh = loadmodel->meshlist[0];
2114                 loadmodel->data_surfaces[index].texture = loadmodel->data_textures + index;
2115                 loadmodel->data_surfaces[index].num_firstvertex = 0;
2116                 loadmodel->data_surfaces[index].num_vertices = loadmodel->meshlist[0]->num_vertices;
2117         }
2118
2119         // copy over the texcoords
2120         for (index = 0;index < numvtxw;index++)
2121         {
2122                 mesh->data_texcoordtexture2f[index*2+0] = vtxw[index].texcoord[0];
2123                 mesh->data_texcoordtexture2f[index*2+1] = vtxw[index].texcoord[1];
2124         }
2125
2126         // loading the faces is complicated because we need to sort them into surfaces by mattindex
2127         for (index = 0;index < numfaces;index++)
2128                 loadmodel->data_surfaces[faces[index].mattindex].num_triangles++;
2129         for (index = 0, i = 0;index < nummatts;index++)
2130         {
2131                 loadmodel->data_surfaces[index].num_firsttriangle = i;
2132                 i += loadmodel->data_surfaces[index].num_triangles;
2133                 loadmodel->data_surfaces[index].num_triangles = 0;
2134         }
2135         for (index = 0;index < numfaces;index++)
2136         {
2137                 i = (loadmodel->data_surfaces[faces[index].mattindex].num_firsttriangle + loadmodel->data_surfaces[faces[index].mattindex].num_triangles++)*3;
2138                 mesh->data_element3i[i+0] = faces[index].vtxwindex[0];
2139                 mesh->data_element3i[i+1] = faces[index].vtxwindex[1];
2140                 mesh->data_element3i[i+2] = faces[index].vtxwindex[2];
2141         }
2142
2143         // copy over the bones
2144         for (index = 0;index < numbones;index++)
2145         {
2146                 strlcpy(loadmodel->data_bones[index].name, bones[index].name, sizeof(loadmodel->data_bones[index].name));
2147                 loadmodel->data_bones[index].parent = (index || bones[index].parent > 0) ? bones[index].parent : -1;
2148                 if (loadmodel->data_bones[index].parent >= index)
2149                         Host_Error("%s bone[%i].parent >= %i", loadmodel->name, index, index);
2150         }
2151
2152         // build bone-relative vertex weights from the psk point weights
2153         mesh->num_vertexboneweights = 0;
2154         for (index = 0;index < numvtxw;index++)
2155                 for (j = 0;j < numrawweights;j++)
2156                         if (rawweights[j].pntsindex == vtxw[index].pntsindex)
2157                                 mesh->num_vertexboneweights++;
2158         mesh->data_vertexboneweights = (surfmeshvertexboneweight_t *)Mem_Alloc(loadmodel->mempool, mesh->num_vertexboneweights * sizeof(surfmeshvertexboneweight_t));
2159         mesh->num_vertexboneweights = 0;
2160         for (index = 0;index < numvtxw;index++)
2161         {
2162                 for (j = 0;j < numrawweights;j++)
2163                 {
2164                         if (rawweights[j].pntsindex == vtxw[index].pntsindex)
2165                         {
2166                                 matrix4x4_t matrix, inversematrix;
2167                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].vertexindex = index;
2168                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].boneindex = rawweights[j].boneindex;
2169                                 mesh->data_vertexboneweights[mesh->num_vertexboneweights].weight = rawweights[j].weight;
2170                                 matrix = identitymatrix;
2171                                 for (i = rawweights[j].boneindex;i >= 0;i = loadmodel->data_bones[i].parent)
2172                                 {
2173                                         matrix4x4_t childmatrix, tempmatrix;
2174                                         Mod_PSKMODEL_AnimKeyToMatrix(bones[i].basepose.origin, bones[i].basepose.quat, &tempmatrix);
2175                                         childmatrix = matrix;
2176                                         Matrix4x4_Concat(&matrix, &tempmatrix, &childmatrix);
2177                                 }
2178                                 Matrix4x4_Invert_Simple(&inversematrix, &matrix);
2179                                 Matrix4x4_Transform(&inversematrix, pnts[rawweights[j].pntsindex].origin, mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin);
2180                                 VectorScale(mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin, mesh->data_vertexboneweights[mesh->num_vertexboneweights].weight, mesh->data_vertexboneweights[mesh->num_vertexboneweights].origin);
2181                                 mesh->num_vertexboneweights++;
2182                         }
2183                 }
2184         }
2185
2186         // set up the animscenes based on the anims
2187         for (index = 0, i = 0;index < numanims;index++)
2188         {
2189                 for (j = 0;j < anims[index].numframes;j++, i++)
2190                 {
2191                         dpsnprintf(loadmodel->animscenes[i].name, sizeof(loadmodel->animscenes[i].name), "%s_%d", anims[index].name, j);
2192                         loadmodel->animscenes[i].firstframe = i;
2193                         loadmodel->animscenes[i].framecount = 1;
2194                         loadmodel->animscenes[i].loop = true;
2195                         loadmodel->animscenes[i].framerate = 10;
2196                 }
2197         }
2198
2199         // load the poses from the animkeys
2200         for (index = 0;index < numanimkeys;index++)
2201         {
2202                 matrix4x4_t matrix;
2203                 Mod_PSKMODEL_AnimKeyToMatrix(animkeys[index].origin, animkeys[index].quat, &matrix);
2204                 loadmodel->data_poses[index*12+0] = matrix.m[0][0];
2205                 loadmodel->data_poses[index*12+1] = matrix.m[0][1];
2206                 loadmodel->data_poses[index*12+2] = matrix.m[0][2];
2207                 loadmodel->data_poses[index*12+3] = matrix.m[0][3];
2208                 loadmodel->data_poses[index*12+4] = matrix.m[1][0];
2209                 loadmodel->data_poses[index*12+5] = matrix.m[1][1];
2210                 loadmodel->data_poses[index*12+6] = matrix.m[1][2];
2211                 loadmodel->data_poses[index*12+7] = matrix.m[1][3];
2212                 loadmodel->data_poses[index*12+8] = matrix.m[2][0];
2213                 loadmodel->data_poses[index*12+9] = matrix.m[2][1];
2214                 loadmodel->data_poses[index*12+10] = matrix.m[2][2];
2215                 loadmodel->data_poses[index*12+11] = matrix.m[2][3];
2216         }
2217
2218         // compile extra data we want
2219         Mod_ValidateElements(mesh->data_element3i, mesh->num_triangles, mesh->num_vertices, __FILE__, __LINE__);
2220         Mod_BuildTriangleNeighbors(mesh->data_neighbor3i, mesh->data_element3i, mesh->num_triangles);
2221         Mod_Alias_Mesh_CompileFrameZero(mesh);
2222
2223         Mem_Free(animfilebuffer);
2224 }
2225