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