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