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