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