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