]> git.xonotic.org Git - xonotic/netradiant.git/blob - libs/picomodel/pm_ms3d.c
Merge commit 'ffb487e45c26dccd20285849979be1cb261c52f6' into master-merge
[xonotic/netradiant.git] / libs / picomodel / pm_ms3d.c
1 /* -----------------------------------------------------------------------------
2
3    PicoModel Library
4
5    Copyright (c) 2002, Randy Reddig & seaw0lf
6    All rights reserved.
7
8    Redistribution and use in source and binary forms, with or without modification,
9    are permitted provided that the following conditions are met:
10
11    Redistributions of source code must retain the above copyright notice, this list
12    of conditions and the following disclaimer.
13
14    Redistributions in binary form must reproduce the above copyright notice, this
15    list of conditions and the following disclaimer in the documentation and/or
16    other materials provided with the distribution.
17
18    Neither the names of the copyright holders nor the names of its contributors may
19    be used to endorse or promote products derived from this software without
20    specific prior written permission.
21
22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
23    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
24    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
26    ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
27    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
29    ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
33    ----------------------------------------------------------------------------- */
34
35 /* dependencies */
36 #include "picointernal.h"
37 #include "globaldefs.h"
38
39 /* disable warnings */
40 #if GDEF_COMPILER_MSVC
41 #pragma warning( disable:4100 )         /* unref param */
42 #endif
43
44 /* remarks:
45  * - loader seems stable
46  * todo:
47  * - fix uv coordinate problem
48  * - check for buffer overflows ('bufptr' accesses)
49  */
50 /* uncomment when debugging this module */
51  #define DEBUG_PM_MS3D
52  #define DEBUG_PM_MS3D_EX
53
54 /* ms3d limits */
55 const int MS3D_MAX_VERTS      = 8192;
56 const int MS3D_MAX_TRIS       = 16384;
57 const int MS3D_MAX_GROUPS     = 128;
58 const int MS3D_MAX_MATERIALS  = 128;
59 const int MS3D_MAX_JOINTS     = 128;
60 const int MS3D_MAX_KEYFRAMES  = 216;
61
62 /* ms3d flags */
63 const int MS3D_SELECTED       = 1;
64 const int MS3D_HIDDEN         = 2;
65 const int MS3D_SELECTED2      = 4;
66 const int MS3D_DIRTY          = 8;
67
68 /* this freaky loader needs byte alignment */
69 #pragma pack(push, 1)
70
71 /* ms3d header */
72 typedef struct SMsHeader
73 {
74         char magic[10];
75         int version;
76 }
77 TMsHeader;
78
79 /* ms3d vertex */
80 typedef struct SMsVertex
81 {
82         unsigned char flags;                /* sel, sel2, or hidden */
83         float xyz[3];
84         char boneID;                        /* -1 means 'no bone' */
85         unsigned char refCount;
86 }
87 TMsVertex;
88
89 /* ms3d triangle */
90 typedef struct SMsTriangle
91 {
92         unsigned short flags;               /* sel, sel2, or hidden */
93         unsigned short vertexIndices[3];
94         float vertexNormals[3][3];
95         float s[3];
96         float t[3];
97         unsigned char smoothingGroup;       /* 1 - 32 */
98         unsigned char groupIndex;
99 }
100 TMsTriangle;
101
102 /* ms3d material */
103 typedef struct SMsMaterial
104 {
105         char name[32];
106         float ambient[4];
107         float diffuse[4];
108         float specular[4];
109         float emissive[4];
110         float shininess;                    /* range 0..128 */
111         float transparency;                 /* range 0..1 */
112         unsigned char mode;
113         char texture [128];                 /* texture.bmp */
114         char alphamap[128];                 /* alpha.bmp */
115 }
116 TMsMaterial;
117
118 // ms3d group (static part)
119 // followed by a variable size block (see below)
120 typedef struct SMsGroup
121 {
122         unsigned char flags;                // sel, hidden
123         char name[32];
124         unsigned short numTriangles;
125 /*
126     unsigned short      triangleIndices[ numTriangles ];
127     char                        materialIndex;          // -1 means 'no material'
128  */
129 }
130 TMsGroup;
131
132 // ms3d joint
133 typedef struct SMsJoint
134 {
135         unsigned char flags;
136         char name[32];
137         char parentName[32];
138         float rotation[3];
139         float translation[3];
140         unsigned short numRotationKeyframes;
141         unsigned short numTranslationKeyframes;
142 }
143 TMsJoint;
144
145 // ms3d keyframe
146 typedef struct SMsKeyframe
147 {
148         float time;
149         float parameter[3];
150 }
151 TMsKeyframe;
152
153 /* restore previous data alignment */
154 #pragma pack(pop)
155
156 /* _ms3d_canload:
157  *      validates a milkshape3d model file.
158  */
159 static int _ms3d_canload( PM_PARAMS_CANLOAD ){
160         const TMsHeader *hdr;
161
162
163         /* sanity check */
164         if ( (size_t) bufSize < sizeof( TMsHeader ) ) {
165                 return PICO_PMV_ERROR_SIZE;
166         }
167
168         /* get ms3d header */
169         hdr = (const TMsHeader *)buffer;
170
171         /* check ms3d magic */
172         if ( strncmp( hdr->magic,"MS3D000000",10 ) != 0 ) {
173                 return PICO_PMV_ERROR_IDENT;
174         }
175
176         /* check ms3d version */
177         if ( _pico_little_long( hdr->version ) < 3 ||
178                  _pico_little_long( hdr->version ) > 4 ) {
179                 _pico_printf( PICO_ERROR,"MS3D file ignored. Only MS3D 1.3 and 1.4 is supported." );
180                 return PICO_PMV_ERROR_VERSION;
181         }
182         /* file seems to be a valid ms3d */
183         return PICO_PMV_OK;
184 }
185
186 static unsigned char *GetWord( unsigned char *bufptr, int *out ){
187         if ( bufptr == NULL ) {
188                 return NULL;
189         }
190         *out = _pico_little_short( *(unsigned short *)bufptr );
191         return( bufptr + 2 );
192 }
193
194 /* _ms3d_load:
195  *      loads a milkshape3d model file.
196  */
197 static picoModel_t *_ms3d_load( PM_PARAMS_LOAD ){
198         picoModel_t    *model;
199         unsigned char  *bufptr, *bufptr0;
200         int shaderRefs[ MS3D_MAX_GROUPS ];
201         int numGroups;
202         int numMaterials;
203 //      unsigned char  *ptrToGroups;
204         int numVerts;
205         unsigned char  *ptrToVerts;
206         int numTris;
207         unsigned char  *ptrToTris;
208         int i,k,m;
209
210         /* create new pico model */
211         model = PicoNewModel();
212         if ( model == NULL ) {
213                 return NULL;
214         }
215
216         /* do model setup */
217         PicoSetModelFrameNum( model, frameNum );
218         PicoSetModelName( model, fileName );
219         PicoSetModelFileName( model, fileName );
220
221         bufptr0 = bufptr = (picoByte_t*) _pico_alloc( bufSize );
222         memcpy( bufptr, buffer, bufSize );
223         /* skip header */
224         bufptr += sizeof( TMsHeader );
225
226         /* get number of vertices */
227         bufptr = GetWord( bufptr,&numVerts );
228         ptrToVerts = bufptr;
229
230 #ifdef DEBUG_PM_MS3D
231         printf( "NumVertices: %d\n",numVerts );
232 #endif
233         /* swap verts */
234         for ( i = 0; i < numVerts; i++ )
235         {
236                 TMsVertex *vertex;
237                 vertex = (TMsVertex *)bufptr;
238                 bufptr += sizeof( TMsVertex );
239
240                 vertex->xyz[ 0 ] = _pico_little_float( vertex->xyz[ 0 ] );
241                 vertex->xyz[ 1 ] = _pico_little_float( vertex->xyz[ 1 ] );
242                 vertex->xyz[ 2 ] = _pico_little_float( vertex->xyz[ 2 ] );
243
244 #ifdef DEBUG_PM_MS3D_EX_
245                 printf( "Vertex: x: %f y: %f z: %f\n",
246                                 msvd[i]->vertex[0],
247                                 msvd[i]->vertex[1],
248                                 msvd[i]->vertex[2] );
249 #endif
250         }
251         /* get number of triangles */
252         bufptr = GetWord( bufptr,&numTris );
253         ptrToTris = bufptr;
254
255 #ifdef DEBUG_PM_MS3D
256         printf( "NumTriangles: %d\n",numTris );
257 #endif
258         /* swap tris */
259         for ( i = 0; i < numTris; i++ )
260         {
261                 TMsTriangle *triangle;
262                 triangle = (TMsTriangle *)bufptr;
263                 bufptr += sizeof( TMsTriangle );
264
265                 triangle->flags = _pico_little_short( triangle->flags );
266
267                 /* run through all tri verts */
268                 for ( k = 0; k < 3; k++ )
269                 {
270                         /* swap tex coords */
271                         triangle->s[ k ] = _pico_little_float( triangle->s[ k ] );
272                         triangle->t[ k ] = _pico_little_float( triangle->t[ k ] );
273
274                         /* swap fields */
275                         triangle->vertexIndices[ k ]      = _pico_little_short( triangle->vertexIndices[ k ] );
276                         triangle->vertexNormals[ 0 ][ k ] = _pico_little_float( triangle->vertexNormals[ 0 ][ k ] );
277                         triangle->vertexNormals[ 1 ][ k ] = _pico_little_float( triangle->vertexNormals[ 1 ][ k ] );
278                         triangle->vertexNormals[ 2 ][ k ] = _pico_little_float( triangle->vertexNormals[ 2 ][ k ] );
279
280                         /* check for out of range indices */
281                         if ( triangle->vertexIndices[ k ] >= numVerts ) {
282                                 _pico_printf( PICO_ERROR,"Vertex %d index %d out of range (%d, max %d)",i,k,triangle->vertexIndices[k],numVerts - 1 );
283                                 PicoFreeModel( model );
284                                 _pico_free( bufptr0 );
285                                 return NULL; /* yuck */
286                         }
287                 }
288         }
289         /* get number of groups */
290         bufptr = GetWord( bufptr,&numGroups );
291 //      ptrToGroups = bufptr;
292
293 #ifdef DEBUG_PM_MS3D
294         printf( "NumGroups: %d\n",numGroups );
295 #endif
296         /* run through all groups in model */
297         for ( i = 0; i < numGroups && i < MS3D_MAX_GROUPS; i++ )
298         {
299                 picoSurface_t *surface;
300                 TMsGroup      *group;
301
302                 group = (TMsGroup *)bufptr;
303                 bufptr += sizeof( TMsGroup );
304
305                 /* we ignore hidden groups */
306                 if ( group->flags & MS3D_HIDDEN ) {
307                         bufptr += ( group->numTriangles * 2 ) + 1;
308                         continue;
309                 }
310                 /* forced null term of group name */
311                 group->name[ 31 ] = '\0';
312
313                 /* create new pico surface */
314                 surface = PicoNewSurface( model );
315                 if ( surface == NULL ) {
316                         PicoFreeModel( model );
317                         _pico_free( bufptr0 );
318                         return NULL;
319                 }
320                 /* do surface setup */
321                 PicoSetSurfaceType( surface,PICO_TRIANGLES );
322                 PicoSetSurfaceName( surface,group->name );
323
324                 /* process triangle indices */
325                 for ( k = 0; k < group->numTriangles; k++ )
326                 {
327                         TMsTriangle *triangle;
328                         unsigned int triangleIndex;
329
330                         /* get triangle index */
331                         bufptr = GetWord( bufptr,(int *)&triangleIndex );
332
333                         /* get ptr to triangle data */
334                         triangle = (TMsTriangle *)( ptrToTris + ( sizeof( TMsTriangle ) * triangleIndex ) );
335
336                         /* run through triangle vertices */
337                         for ( m = 0; m < 3; m++ )
338                         {
339                                 TMsVertex   *vertex;
340                                 unsigned int vertexIndex;
341                                 picoVec2_t texCoord;
342
343                                 /* get ptr to vertex data */
344                                 vertexIndex = triangle->vertexIndices[ m ];
345                                 vertex = (TMsVertex *)( ptrToVerts + ( sizeof( TMsVertex ) * vertexIndex ) );
346
347                                 /* store vertex origin */
348                                 PicoSetSurfaceXYZ( surface,vertexIndex,vertex->xyz );
349
350                                 /* store vertex color */
351                                 PicoSetSurfaceColor( surface, 0, vertexIndex, picoColor_white );
352
353                                 /* store vertex normal */
354                                 PicoSetSurfaceNormal( surface,vertexIndex,triangle->vertexNormals[ m ] );
355
356                                 /* store current face vertex index */
357                                 PicoSetSurfaceIndex( surface,( k * 3 + ( 2 - m ) ),(picoIndex_t)vertexIndex );
358
359                                 /* get texture vertex coord */
360                                 texCoord[ 0 ] = triangle->s[ m ];
361                                 texCoord[ 1 ] = -triangle->t[ m ];  /* flip t */
362
363                                 /* store texture vertex coord */
364                                 PicoSetSurfaceST( surface,0,vertexIndex,texCoord );
365                         }
366                 }
367                 /* store material */
368                 shaderRefs[ i ] = *bufptr++;
369
370 #ifdef DEBUG_PM_MS3D
371                 printf( "Group %d: '%s' (%d tris)\n",i,group->name,group->numTriangles );
372 #endif
373         }
374         /* get number of materials */
375         bufptr = GetWord( bufptr,&numMaterials );
376
377 #ifdef DEBUG_PM_MS3D
378         printf( "NumMaterials: %d\n",numMaterials );
379 #endif
380         /* run through all materials in model */
381         for ( i = 0; i < numMaterials; i++ )
382         {
383                 picoShader_t *shader;
384                 picoColor_t ambient,diffuse,specular;
385                 TMsMaterial  *material;
386                 int k;
387
388                 material = (TMsMaterial *)bufptr;
389                 bufptr += sizeof( TMsMaterial );
390
391                 /* null term strings */
392                 material->name    [  31 ] = '\0';
393                 material->texture [ 127 ] = '\0';
394                 material->alphamap[ 127 ] = '\0';
395
396                 /* ltrim strings */
397                 _pico_strltrim( material->name );
398                 _pico_strltrim( material->texture );
399                 _pico_strltrim( material->alphamap );
400
401                 /* rtrim strings */
402                 _pico_strrtrim( material->name );
403                 _pico_strrtrim( material->texture );
404                 _pico_strrtrim( material->alphamap );
405
406                 /* create new pico shader */
407                 shader = PicoNewShader( model );
408                 if ( shader == NULL ) {
409                         PicoFreeModel( model );
410                         _pico_free( bufptr0 );
411                         return NULL;
412                 }
413                 /* scale shader colors */
414                 for ( k = 0; k < 4; k++ )
415                 {
416                         ambient [ k ] = (picoByte_t) ( material->ambient[ k ] * 255 );
417                         diffuse [ k ] = (picoByte_t) ( material->diffuse[ k ] * 255 );
418                         specular[ k ] = (picoByte_t) ( material->specular[ k ] * 255 );
419                 }
420                 /* set shader colors */
421                 PicoSetShaderAmbientColor( shader,ambient );
422                 PicoSetShaderDiffuseColor( shader,diffuse );
423                 PicoSetShaderSpecularColor( shader,specular );
424
425                 /* set shader transparency */
426                 PicoSetShaderTransparency( shader,material->transparency );
427
428                 /* set shader shininess (0..127) */
429                 PicoSetShaderShininess( shader,material->shininess );
430
431                 /* set shader name */
432                 PicoSetShaderName( shader,material->name );
433
434                 /* set shader texture map name */
435                 PicoSetShaderMapName( shader,material->texture );
436
437 #ifdef DEBUG_PM_MS3D
438                 printf( "Material %d: '%s' ('%s','%s')\n",i,material->name,material->texture,material->alphamap );
439 #endif
440         }
441         /* assign shaders to surfaces */
442         for ( i = 0; i < numGroups && i < MS3D_MAX_GROUPS; i++ )
443         {
444                 picoSurface_t *surface;
445                 picoShader_t  *shader;
446
447                 /* sanity check */
448                 if ( shaderRefs[ i ] >= MS3D_MAX_MATERIALS ||
449                          shaderRefs[ i ] < 0 ) {
450                         continue;
451                 }
452
453                 /* get surface */
454                 surface = PicoGetModelSurface( model,i );
455                 if ( surface == NULL ) {
456                         continue;
457                 }
458
459                 /* get shader */
460                 shader = PicoGetModelShader( model,shaderRefs[ i ] );
461                 if ( shader == NULL ) {
462                         continue;
463                 }
464
465                 /* assign shader */
466                 PicoSetSurfaceShader( surface,shader );
467
468 #ifdef DEBUG_PM_MS3D
469                 printf( "Mapped: %d ('%s') to %d (%s)\n",
470                                 shaderRefs[i],shader->name,i,surface->name );
471 #endif
472         }
473         /* return allocated pico model */
474         _pico_free( bufptr0 );
475         return model;
476 //      return NULL;
477 }
478
479 /* pico file format module definition */
480 const picoModule_t picoModuleMS3D =
481 {
482         "0.4-a",                    /* module version string */
483         "Milkshape 3D",             /* module display name */
484         "seaw0lf",                  /* author's name */
485         "2002 seaw0lf",             /* module copyright */
486         {
487                 "ms3d",NULL,NULL,NULL   /* default extensions to use */
488         },
489         _ms3d_canload,              /* validation routine */
490         _ms3d_load,                 /* load routine */
491         NULL,                       /* save validation routine */
492         NULL                        /* save routine */
493 };