]> icculus.org git repositories - taylor/freespace2.git/blob - src/model/modelread.cpp
GCC 3.4 fixes.
[taylor/freespace2.git] / src / model / modelread.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
4  * All source code herein is the property of Volition, Inc. You may not sell 
5  * or otherwise commercially exploit the source or things you created based on
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/Model/ModelRead.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * file which reads and deciphers POF information
16  *
17  * $Log$
18  * Revision 1.12  2004/09/20 01:31:44  theoddone33
19  * GCC 3.4 fixes.
20  *
21  * Revision 1.11  2004/07/04 11:39:06  taylor
22  * fix missing debrief text, crash on exit, path separator's, warning fixes, no GR_SOFT
23  *
24  * Revision 1.10  2004/06/11 21:39:44  taylor
25  * x86 compile fixes for OSX patch
26  *
27  * Revision 1.9  2004/06/10 23:55:39  tigital
28  * byte-swapping changes for bigendian systems
29  *
30  * Revision 1.8  2003/06/11 18:30:33  taylor
31  * plug memory leaks
32  *
33  * Revision 1.7  2003/01/30 19:43:57  relnev
34  * added a missing "not" in the model warning
35  *
36  * Revision 1.6  2002/06/17 06:33:09  relnev
37  * ryan's struct patch for gcc 2.95
38  *
39  * Revision 1.5  2002/06/09 04:41:23  relnev
40  * added copyright header
41  *
42  * Revision 1.4  2002/06/09 03:16:04  relnev
43  * added _splitpath.
44  *
45  * removed unneeded asm, old sdl 2d setup.
46  *
47  * fixed crash caused by opengl_get_region.
48  *
49  * Revision 1.3  2002/06/01 07:12:33  relnev
50  * a few NDEBUG updates.
51  *
52  * removed a few warnings.
53  *
54  * Revision 1.2  2002/05/07 03:16:47  theoddone33
55  * The Great Newline Fix
56  *
57  * Revision 1.1.1.1  2002/05/03 03:28:10  root
58  * Initial import.
59  *
60  * 
61  * 36    7/22/99 2:26p Mattk
62  * DA: don't show engine wash error if no subsystems.  (ie, Pofview...)
63  * 
64  * 35    7/19/99 12:02p Andsager
65  * Allow AWACS on any ship subsystem. Fix sexp_set_subsystem_strength to
66  * only blow up subsystem if its strength is > 0
67  * 
68  * 34    7/07/99 5:00p Andsager
69  * Fixed bug in stepped rotation
70  * 
71  * 33    7/06/99 4:42p Anoop
72  * Add MiniCap hack for engine wash
73  * 
74  * 32    7/06/99 3:52p Andsager
75  * That wacky model_subsystem name vs. subobj_name thing bites us in the
76  * ass again.
77  * 
78  * 31    7/06/99 3:15p Anoop
79  * Better debug info for engine wash error.
80  * 
81  * 30    7/06/99 11:37a Andsager
82  * Fix warning message.
83  * 
84  * 29    7/06/99 10:45a Andsager
85  * Modify engine wash to work on any ship that is not small.  Add AWACS
86  * ask for help.
87  * 
88  * 28    7/01/99 4:23p Dave
89  * Full support for multiple linked ambient engine sounds. Added "big
90  * damage" flag.
91  * 
92  * 27    6/08/99 2:33p Dave
93  * Fixed release build warning. Put in hud config stuff.
94  * 
95  * 26    6/01/99 8:35p Dave
96  * Finished lockarm weapons. Added proper supercap weapons/damage. Added
97  * awacs-set-radius sexpression.
98  * 
99  * 25    5/28/99 1:51p Andsager
100  * Allow models to rotate in both direction on an axis, specifying a
101  * negative rotation time in submodel properties.
102  * 
103  * 24    5/27/99 3:48p Andsager
104  * Add assert to model_read code to not allow overwrite of memory
105  * 
106  * 23    5/27/99 12:11p Andsager
107  * Allow more than 1 subsystem to have live debris on any ship
108  * 
109  * 22    5/27/99 10:57a Mattk
110  * Put in a warning about too many firing points per turret.
111  * 
112  * 21    5/24/99 5:45p Dave
113  * Added detail levels to the nebula, with a decent speedup. Split nebula
114  * lightning into its own section.
115  * 
116  * 20    5/19/99 11:09a Andsager
117  * Turn on engine wash.  Check every 1/4 sec.
118  * 
119  * 19    5/11/99 10:16p Andsager
120  * First pass on engine wash effect.  Rotation (control input), damage,
121  * shake.  
122  * 
123  * 18    4/09/99 11:38a Andsager
124  * Change POF format for Freespace2
125  * 
126  * 17    3/23/99 5:17p Dave
127  * Changed model file format somewhat to account for LOD's on insignias
128  * 
129  * 16    3/20/99 3:46p Dave
130  * Added support for model-based background nebulae. Added 3 new
131  * sexpressions.
132  * 
133  * 15    3/19/99 6:15p Dave
134  * Put in checks for insignia bitmaps for having too many faces or
135  * vertices
136  * 
137  * 14    2/21/99 6:01p Dave
138  * Fixed standalone WSS packets. 
139  * 
140  * 13    2/19/99 11:42a Dave
141  * Put in model rendering autocentering.
142  * 
143  * 12    2/10/99 3:52p Enricco
144  * Fix stupid assert
145  * 
146  * 11    1/14/99 6:06p Dave
147  * 100% full squad logo support for single player and multiplayer.
148  * 
149  * 10    1/11/99 12:42p Andsager
150  * Add live debris - debris which is created from a destroyed subsystem,
151  * when the ship is still alive
152  * 
153  * 9     1/08/99 2:08p Dave
154  * Fixed software rendering for pofview. Super early support for AWACS and
155  * beam weapons.
156  * 
157  * 8     1/06/99 2:24p Dave
158  * Stubs and release build fixes.
159  * 
160  * 7     12/23/98 2:53p Andsager
161  * Added stepped rotation support
162  * 
163  * 6     12/04/98 3:34p Andsager
164  * Handle norotating submodels
165  * 
166  * 5     12/03/98 3:14p Andsager
167  * Check in code that checks rotating submodel actually has ship subsystem
168  * 
169  * 4     11/19/98 11:07p Andsager
170  * Check in of physics and collision detection of rotating submodels
171  * 
172  * 3     10/23/98 3:03p Andsager
173  * Initial support for changing rotation rate.
174  * 
175  * 2     10/07/98 10:53a Dave
176  * Initial checkin.
177  * 
178  * 1     10/07/98 10:50a Dave
179  * 
180  * 177   8/28/98 3:29p Dave
181  * EMP effect done. AI effects may need some tweaking as required.
182  * 
183  * 176   5/19/98 8:31p Andsager
184  * Added split planes (for big ship explosions)
185  * 
186  * 175   5/07/98 5:39p Andsager
187  * Changes to model to hold cross section info
188  * 
189  * 174   4/30/98 4:53p John
190  * Restructured and cleaned up cfile code.  Added capability to read off
191  * of CD-ROM drive and out of multiple pack files.
192  * 
193  * 173   4/22/98 9:43p John
194  * Added code to allow checking of invisible faces, flagged by any texture
195  * name with invisible in it.
196  * 
197  * 172   4/14/98 11:11p John
198  * Made ships with < 50% hull left show electrical damage arcs.
199  * 
200  * 171   4/01/98 5:34p John
201  * Made only the used POFs page in for a level.   Reduced some interp
202  * arrays.    Made custom detail level work differently.
203  * 
204  * 170   4/01/98 9:14a Mike
205  * Fixed free bug
206  * 
207  * 169   3/31/98 5:18p John
208  * Removed demo/save/restore.  Made NDEBUG defined compile.  Removed a
209  * bunch of debug stuff out of player file.  Made model code be able to
210  * unload models and malloc out only however many models are needed.
211  *  
212  * 
213  * 168   3/17/98 2:46p Allender
214  * Copy subsystem name when copying model subsystems
215  * 
216  * 167   3/02/98 5:42p John
217  * Removed WinAVI stuff from Freespace.  Made all HUD gauges wriggle from
218  * afterburner.  Made gr_set_clip work good with negative x &y.  Made
219  * model_caching be on by default.  Made each cached model have it's own
220  * bitmap id.  Made asteroids not rotate when model_caching is on.  
221  * 
222  * 166   2/24/98 5:04p Allender
223  * allow different ship classes to use the same model.  Lot's of subsystem
224  * stuff to deal with
225  * 
226  * 165   2/16/98 3:46p John
227  * Made mass be proportional to area in newer pofs
228  * 
229  * 164   2/13/98 5:19p John
230  * First rev of new model caching system.  Needs to be ripped out and
231  * moved into ship stuff.
232  * 
233  * 163   1/29/98 5:52p John
234  * new version of electrical arcing code
235  * 
236  * 162   1/29/98 8:39a Andsager
237  * Changed mass and moment of intertia based area vs. volume
238  * 
239  * 161   1/28/98 2:15p Mike
240  * Convert volume to surface area at runtime.  Write note to John to
241  * cleanup if he modifies bspgen.
242  * 
243  * 160   1/27/98 11:02a John
244  * Added first rev of sparks.   Made all code that calls model_render call
245  * clear_instance first.   Made debris pieces not render by default when
246  * clear_instance is called.
247  * 
248  * 159   1/19/98 6:15p John
249  * Fixed all my Optimized Build compiler warnings
250  * 
251  * 158   1/09/98 11:25a John
252  * Took the thruster animation stuff out of the model.
253  * 
254  * 157   12/31/97 4:47p John
255  * Made all the eye points fit inside core radius
256  * 
257  * 156   12/31/97 2:35p John
258  * Added code for core_radius
259  * 
260  * 155   12/17/97 2:41p John
261  * made target bounding box be on hull only.
262  * 
263  * 154   12/17/97 9:54a John
264  * added code for precalculated weapon flash lighting.
265  * 
266  * 153   11/29/97 2:05p John
267  * made g3_draw_bitmap and g3_draw_rotated bitmap take w&h, not w/2 & h/2,
268  * like they used to incorrectly assume.   Added code to model to read in
269  * thruster radius's.
270  * 
271  * 152   11/25/97 11:41a John
272  * added code to read in pof v20.05, which adds radius to thrusters.
273  * 
274  * 151   10/28/97 12:34a Mike
275  * Set useful values of mass and inertia matrix if values not otherwise
276  * set.  Generate Warnings for unexpected ones.
277  * 
278  * 150   10/22/97 5:54p Lawrance
279  * get rid of leading '$' when storing parent_name for paths
280  * 
281  * 149   10/20/97 5:57p Lawrance
282  * have index to polymodel->paths[] within the model_subsystem struct.
283  * 
284  * 148   9/15/97 5:45p John
285  * took out chunk stuff.
286  * made pofview display thrusters as blue polies.
287  * 
288  * 147   9/09/97 3:39p Sandeep
289  * warning level 4 bugs
290  * 
291  * 146   9/04/97 5:09p Andsager
292  * implement physics using moment of inertia and mass (from BSPgen).
293  * Added to phys_info struct.  Updated ship_info, polymodel structs.
294  * Updated weapon ($Mass and $Force) and ship ($Mass -> $Density) tables
295  * 
296  * 145   9/03/97 5:57p Lawrance
297  * take out warning
298  * 
299  * 144   9/03/97 4:32p John
300  * changed bmpman to only accept ani and pcx's.  made passing .pcx or .ani
301  * to bm_load functions not needed.   Made bmpman keep track of palettes
302  * for bitmaps not mapped into game palettes.
303  * 
304  * 143   8/19/97 11:49p Lawrance
305  * using atan2_safe() in place of atan2()
306  * 
307  * 142   8/19/97 8:44a John
308  * Initial hooks for thruster stuff.
309  * 
310  * 141   8/15/97 4:10p John
311  * new code to use the new octrees style bsp trees
312  * 
313  * 140   8/14/97 5:46p John
314  * added code to read in mass,center of mass, and moment of interia from
315  * the pof.  Also added code to display green center of mass dot when Show
316  * debug points is on in pofview.
317  * 
318  * 139   7/10/97 8:34a John
319  * Added code to read TGA files.
320  * 
321  * 138   6/26/97 3:18p Mike
322  * Recognize "turret", etc. in a subsystem field anywhere in name.
323  * Generate warning for bogus subsystem names.
324  * 
325  * 137   6/25/97 5:11p John
326  * added foundation for model octants.
327  * 
328  * 136   6/25/97 10:28a John
329  * Made debris chunks radius be set correctly to the submodel size, not
330  * hardcoded to 10.0f.
331  * 
332  * 135   6/06/97 11:55a Mike
333  * Fix firing direction for zero piece turrets.
334  * 
335  * 134   5/31/97 2:36p Mike
336  * Comment out mprintfs pertaining to debris.
337  * 
338  * 133   5/30/97 4:41p Hoffoss
339  * Made some additions required for Fred.
340  * 
341  * 132   5/30/97 3:42p Mike
342  * Shield mesh and hit system.
343  * 
344  * 131   5/30/97 10:40a Hoffoss
345  * Added a function for Fred to get docking point names.
346  * 
347  * 130   5/29/97 4:34p Allender
348  * removed Int3 from model_find_dock_index.
349  * 
350  * 129   4/30/97 10:41a Allender
351  * don't dump out token 'none' when dumping out subsystem information
352  * 
353  * 128   4/17/97 6:06p John
354  * New code/data for v19 of BSPGEN with smoothing and zbuffer
355  * optimizations.
356  * 
357  * 127   4/09/97 3:31p Lawrance
358  * if any points of bounding box don't project, return project fail code
359  * in model_find_2d_bound_min()
360  * 
361  * 126   4/07/97 10:37a John
362  * Took out limits on number of children a submodel can have.    (So now
363  * capital ships can have tons of children on them).
364  * 
365  * 125   4/03/97 3:18p Allender
366  * 
367  * 124   4/03/97 1:29p Allender
368  * subsystem enhancement.  Initial work on making subsystem status
369  * meaningful
370  * 
371  * 123   3/28/97 2:49p John
372  * added code to fix targetting of debris chunks to draw bounding boxes
373  * right.
374  * 
375  * 122   3/28/97 1:19p John
376  * Made TestCode not show damaged submodels.
377  * 
378  * 121   3/28/97 11:17a John
379  * added code for linking lower detail submodels to the highest one; added
380  * code to pofview to view these.
381  * 
382  * 120   3/17/97 11:24a John
383  * 
384  * 119   3/15/97 5:06p John
385  * added bounding boxes for each subobject and code to display them.
386  * 
387  * 118   3/13/97 10:32a John
388  * Added code for tiled 256x256 textures in certain models.
389  * 
390  * 117   3/06/97 5:36p Mike
391  * Change vec_normalize_safe() back to vec_normalize().
392  * Spruce up docking a bit.
393  * 
394  * 116   3/06/97 1:06p Allender
395  * more docking stuff.  docking points now specified by strings in mission
396  * file.  Changes to builtin missions and code to reflect this change.
397  * 
398  * 115   3/06/97 10:56a Mike
399  * Write error checking version of vm_vec_normalize().
400  * Fix resultant problems.
401  * 
402  * 114   3/06/97 10:05a Lawrance
403  * added missing cfclose's
404  * 
405  * 113   3/05/97 5:27p John
406  * more work with turret stuff
407  * 
408  * 112   3/05/97 12:49p John
409  * added Viewer_obj.  Took out the interp_??? variables for turning
410  * outline,etc on and put them in flags you pass to model_render.
411  * Cleaned up model_interp code to fit new coding styles.
412  * 
413  * 111   3/05/97 12:42p Adam
414  * john: fixed bug while model transversel code that assumed the root
415  * subobject was 0.   
416  * 
417  * 110   3/05/97 11:09a Allender
418  * DOH!  MAX_SLOTS just way too low.  Upped to 25 and Asserts put in to
419  * check bounds.
420  * 
421  * 109   3/04/97 5:08p John
422  * Started adding debug code to make it so you can view from a turret's
423  * view.
424  * 
425  * 108   3/04/97 3:36p John
426  * took out old debug "h' key.   Made zbuffer flag bit bit field so you
427  * can turn on/off each value.   Fixed a bug with turret rotation where
428  * different handedness turrets wouldn't work.   Fixed a bug with two
429  * large ships within each other's radius not rendering correctly.
430  * 
431  * 107   3/04/97 12:52p Allender
432  * docking styff.  Added dock type to docking structure in model code.
433  * Renamed structure member in ai_goals.  Temporary checkin.  (i.e.
434  * rearming will use rearm dock points)
435  * 
436  * 106   3/03/97 5:47p John
437  * fixed some rotating object discrepencies.   Took out the gun firing
438  * point average beause it was inconsitent and wsn't as correct as using
439  * the pivot point.
440  * 
441  * 105   3/03/97 4:20p Hoffoss
442  * Fixed bug in bug I just fixed. :)
443  * 
444  * 104   3/03/97 4:00p Hoffoss
445  * fixed bug that caused docking bays without a name to be garbage when
446  * loaded.
447  * 
448  * 103   3/03/97 8:58a Lawrance
449  * replaced a fprintf() with a cfputs()
450  * 
451  * 102   3/01/97 2:12p Lawrance
452  * made to work with new cfile changes
453  * 
454  * 101   2/28/97 10:57a John
455  * Made so you can blow off any subsystems, not just radars.
456  * 
457  * 
458  * 100   2/27/97 3:45p John
459  * Added a tree dialog to pofview that shows a model's tree.
460  * 
461  * 99    2/27/97 12:07p John
462  * Added code to suppord debris chunks after a ship is exploded..
463  * 
464  * 98    2/26/97 5:28p John
465  * Fixed a bunch of chunked model bugs.  Basically they almost work better
466  * than non-chunked objects!
467  * 
468  * 97    2/24/97 1:13p Allender
469  * support for multiple eye positions.  Still some kinks to be worked out
470  * though....
471  * 
472  * 96    2/20/97 4:06p Allender
473  * allow for multiple spline paths to lead to a docking bay
474  * 
475  * 95    2/20/97 3:25p Allender
476  * change to docking bay structure -- added a name (for use in Fred
477  * mainly), and index into spline paths to reach this docking point
478  * 
479  * 94    2/19/97 4:03p Allender
480  * dump a 0.0 instead of a 0 when dumping out missing subsystem
481  * information
482  * 
483  * 93    2/19/97 2:52p Allender
484  * added crewspot name to subsystems (used only with turrets).  Will be
485  * used by fred for ai class stuff for turrets
486  * 
487  * 92    2/17/97 4:30p John
488  * Added code to automatically rotate any subsystems with the $rotate
489  * value set (except for turrets)
490  * 
491  * 91    2/17/97 12:03p John
492  * Added code to set the angles of a subobject.
493  * 
494  * 90    2/14/97 4:02p John
495  * changed a vector being passed as value to reference.
496  * 
497  * 89    2/14/97 3:16p Mike
498  * Start on AI path garbage collection
499  * 
500  * 88    2/14/97 1:06p John
501  * upped bspgen version number.
502  * 
503  * 87    2/13/97 10:17a John
504  * INCORPORATED THE FOLLOWING CHANGES:
505  * ???    2/13/97 9:49a John
506  * added code for geometric centers of objects.
507  *  ???   2/12/97 6:30p John
508  *  upped model version number.
509  *  
510  * 
511  * 86    2/13/97 9:49a John
512  * ROLLEDBACK TO ALLENDER'S 85 
513  * 
514  * 85    2/12/97 5:34p Allender
515  * added a ton of debug code to help recify the subsystems in ships.tbl
516  * with subsystems in the models.   Fixed a bug with subsystems not being
517  * given the correct type.
518  * 
519  * 84    2/11/97 4:10p Allender
520  * major change of subsystem stuff.  obj_subsystem renamed to
521  * model_subsystem.  Dyamically allocate space in ship_info for
522  * subsystems.
523  * 
524  * 83    2/10/97 4:20p Allender
525  * added distance to closest geometry to spline points
526  * 
527  * 82    2/10/97 10:58a John
528  * Added back in sparks for where laser bolts hit.
529  * Added code to red damaged objects and replace then.
530  * 
531  * 81    2/07/97 1:24p Allender
532  * added turret lists for spline points
533  * 
534  * 80    2/06/97 2:56p John
535  * Added a "blown-off" field to the instance of a model.  Also took out
536  * the model_set_angles functions and replaced with the more general
537  * model_set_instance functions.
538  * 
539  * 79    2/04/97 7:37p John
540  * Finally!!! Turret stuff working!
541  * 
542  * 78    1/31/97 12:51p John
543  * Added turret_fov and turret_fov_cos
544  * 
545  * 77    1/31/97 12:43p John
546  * Turrets working nicely, finally!
547  * 
548  * 76    1/31/97 11:36a John
549  * 
550  * 75    1/29/97 4:46p John
551  * Code to read $crewpoint flag on turrets and store it in obj_subsystem
552  * info.
553  * 
554  * 74    1/29/97 3:14p John
555  * Added field to ships.tbl to control how fast turret rotates.
556  * 
557  * 73    1/28/97 11:23a John
558  * added functions to get/set model angles.
559  * 
560  * 72    1/28/97 10:07a John
561  * More turret stuff, still not working, though.
562  * 
563  * 71    1/27/97 2:46p John
564  * more turret stuff
565  * 
566  * 70    1/27/97 11:35a Allender
567  * upped compatible object version
568  * 
569  * 69    1/24/97 5:25p John
570  * More turret stuff.   Not working yet, though.
571  * 
572  * 68    1/24/97 4:55p John
573  * Started adding code for turning turrets.
574  * Had to change POF format to 18.0
575  * 
576  * 67    1/20/97 2:16p Allender
577  * new shield structures being used
578  * 
579  * 66    1/15/97 5:19p Allender
580  * new POF version.  old version obsolete.  Added shield and eye stuff.
581  * New format for gun/missile/docking points
582  * 
583  * 65    1/10/97 5:15p Mike
584  * Moved ship-specific parameters from obj_subsystem to ship_subsys.
585  * 
586  * Added turret code to AI system.
587  * 
588  * 64    1/10/97 2:25p John
589  * Added code to support detail level distances.
590  * 
591  * 63    1/02/97 11:45a Allender
592  * changed turret code to have > 1 firing point as well as fixing the
593  * problems of turrets being multiple subobjects.  Turret norms should be
594  * getting stuffed correctly now.
595  * 
596  * 62    12/31/96 4:14p Mike
597  * Turret firing.
598  * Correct bug in HUDtarget.cpp, showing wrong target.
599  * 
600  * 61    12/27/96 4:09p Mike
601  * Integrate John's new model code.
602  * 
603  * 60    12/26/96 1:42p John
604  * Changed function ordering to put model_init at top.
605  * 
606  * 59    12/23/96 3:56p John
607  * Changed POF code to support pof 15.0.
608  * 
609  * 58    12/23/96 11:00a John
610  * Restructured POF stuff to support LOD in one pof.
611  * 
612  * 57    12/20/96 11:55a Allender
613  * removed debug code
614  * 
615  * 56    12/20/96 11:40a Allender
616  * modifed subsystem stuff to do correct hit percentages and other cool
617  * stuff
618  * 
619  * 55    12/18/96 4:04p Allender
620  * added "unknown" subsystem type for subsystems which aren't recognized.
621  * 
622  * 54    12/17/96 11:37a Mike
623  * Big ship AI.
624  * 
625  * 53    12/17/96 8:59a Mike
626  * Path-extraction-from-mdoel test code.
627  * 
628  * 52    12/13/96 5:27p John
629  * fixed my sloppy code that didn't free model data.
630  * 
631  * 51    12/13/96 3:54p Mike
632  * Major improvement to model_draw_paths -- connect the dots!  Uses
633  * sophisticated connect-to-next algorithm.
634  * 
635  * 50    12/13/96 2:59p John
636  * Added some code to test spline paths.
637  * 
638  * 49    12/13/96 2:41p John
639  * Added code to read in spline paths on models.
640  * 
641  * 48    12/13/96 10:29a Adam
642  * from allender:  fixed up linked list walking when checking for turrets
643  * in subsystems
644  * 
645  * 47    12/12/96 3:38p Allender
646  * fix up docking special object names.  Added $thruster stuff to model
647  * and code
648  * 
649  * 46    12/12/96 2:35p Mike
650  * Subsystem support
651  * 
652  * 45    12/12/96 12:29p Lawrance
653  * added function to find the 2d bound for a subobject
654  * 
655  * 44    12/11/96 5:35p John
656  * Added variables for viewer eye.
657  * 
658  * 43    12/11/96 5:15p John
659  * Made the dist for detail level be calculated before the object is
660  * instanced.
661  * 
662  * 42    12/11/96 4:50p John
663  * Added detail levels to the non-chunky ships.
664  * 
665  * 41    12/11/96 4:33p Mike
666  * Temporary version so other people can build.
667  * 
668  * 40    12/11/96 4:24p Mike
669  * Fix broken code...oops! clumsy in editor!
670  * 
671  * 39    12/11/96 4:17p Adam
672  * 
673  * 38    12/11/96 12:57p Mike
674  * Support for "Big Ship" AI behavior.
675  * More turret stuff.
676  * 
677  * 37    12/11/96 12:43p Allender
678  * $gun and $missile don't get appended to models gun/missile list if the
679  * gun/missile belongs to a turret.  Turrets are special instances of
680  * these
681  * 
682  * 36    12/11/96 11:57a Allender
683  * added objnum reference to obj_subsystems so that $gun and $missile
684  * special polygons can refernce a particular subsystem if needed (i.e. to
685  * get the norms, etc).
686  * 
687  * 35    12/11/96 10:33a Allender
688  * added stuff for FOV for turrets
689  * 
690  * 34    12/10/96 3:27p Allender
691  * 
692  * 33    12/09/96 5:05p Allender
693  * made subsystem lists and model_special lists as seperate entities.
694  * 
695  * 32    12/09/96 1:16p Allender
696  * made seperate lists for guns/missiles/subsystems, etc
697  * 
698  * 31    12/09/96 11:01a Allender
699  * added special polygon information to models.  Linked list contains
700  * gun/missile/docking/subsystem/etc information.
701  *
702  * $NoKeywords: $
703  */
704
705 #include <string.h>
706 #include <ctype.h>
707
708 #define MODEL_LIB
709
710 #include "cfile.h"
711 #include "model.h"
712 #include "bmpman.h"
713 #include "floating.h"
714 #include "3d.h"
715 #include "ship.h"
716 #include "modelsinc.h"
717 #include "key.h"
718 #include "2d.h"
719 #include "3dinternal.h"
720 #include "linklist.h"
721 #include "timer.h"
722 #include "freespace.h"          // For flFrameTime
723 #include "fvi.h"
724
725
726 #define MAX_SUBMODEL_COLLISION_ROT_ANGLE (PI / 6.0f)    // max 30 degrees per frame
727
728 // info for special polygon lists
729
730 polymodel *Polygon_models[MAX_POLYGON_MODELS];
731
732 static int model_initted = 0;
733
734 #ifndef NDEBUG
735 CFILE *ss_fp;                   // file pointer used to dump subsystem information
736 char  model_filename[_MAX_PATH];                // temp used to store filename
737 char    debug_name[_MAX_PATH];
738 int ss_warning_shown;           // have we shown the warning dialog concerning the subsystems?
739 char    Global_filename[256];
740 int Model_ram = 0;                      // How much RAM the models use total
741 #endif
742
743
744
745 // Anything less than this is considered incompatible.
746 #define PM_COMPATIBLE_VERSION 1900
747
748 // Anything greater than or equal to PM_COMPATIBLE_VERSION and 
749 // whose major version is less than or equal to this is considered
750 // compatible.  
751 #define PM_OBJFILE_MAJOR_VERSION 21
752
753 static int Model_signature = 0;
754
755 // Free up a model, getting rid of all its memory
756 // Can't be called from outside of model code because more
757 // than one person might be using this model so we can't free 
758 // it.
759 static void model_unload(int modelnum)
760 {
761         int i,j;
762
763         if ( (modelnum < 0) || (modelnum>MAX_POLYGON_MODELS))   {
764                 return;
765         }
766
767         polymodel *pm = Polygon_models[modelnum];
768
769         if ( !pm )      {
770                 return;
771         }
772
773 #ifndef NDEBUG
774         Model_ram -= pm->ram_used;
775 #endif
776         
777         if (pm->paths)  {
778                 for (i=0; i<pm->n_paths; i++ )  {
779                         for (j=0; j<pm->paths[i].nverts; j++ )  {
780                                 if ( pm->paths[i].verts[j].turret_ids ) {
781                                         free(pm->paths[i].verts[j].turret_ids);
782                                 }
783                         }
784                         if (pm->paths[i].verts) {
785                                 free(pm->paths[i].verts);
786                         }
787                 }
788                 free(pm->paths);
789         }
790
791         if ( pm->shield.verts ) {
792                 free( pm->shield.verts );
793         }
794
795         if ( pm->shield.tris )  {
796                 free(pm->shield.tris);
797         }
798
799         if ( pm->missile_banks )        {
800                 free(pm->missile_banks);
801         }
802
803         if ( pm->docking_bays ) {
804                 for (i=0; i<pm->n_docks; i++ )  {
805                         if ( pm->docking_bays[i].splines )      {
806                                 free( pm->docking_bays[i].splines );
807                         }
808                 }
809                 free(pm->docking_bays);
810         }
811
812         // this is from ship.cpp but we don't get the polymodel there so free here
813         if ( pm->ship_bay != NULL ) {
814                 free(pm->ship_bay);
815                 pm->ship_bay = NULL;
816         }
817
818         if ( pm->thrusters )    {
819                 free(pm->thrusters);
820         }
821
822 #ifndef NDEBUG
823         if ( pm->debug_info )   {
824                 free(pm->debug_info);
825         }
826 #endif
827
828         model_octant_free( pm );
829
830         if (pm->submodel)       {
831                 for (i=0; i<pm->n_models; i++ ) {
832                         if ( pm->submodel[i].bsp_data ) {
833                                 free(pm->submodel[i].bsp_data);
834                         }
835                 }
836                 free(pm->submodel);
837         }
838
839         if ( pm->xc ) {
840                 free(pm->xc);
841         }
842
843         if ( pm->lights )       {
844                 free(pm->lights);
845         }
846
847         if ( pm->gun_banks )    {
848                 free(pm->gun_banks);
849         }
850
851         pm->id = 0;
852         memset( pm, 0, sizeof(polymodel));
853         free( pm );
854
855         Polygon_models[modelnum] = NULL;        
856 }
857
858 void model_free_all()
859 {
860         int i;
861
862         if ( !model_initted)    {
863                 model_init();
864                 return;
865         }
866
867         mprintf(( "Freeing all existing models...\n" ));
868
869         for (i=0;i<MAX_POLYGON_MODELS;i++) {
870                 model_unload(i);                
871         }
872
873 }
874
875 void model_init()
876 {
877         int i;
878
879         if ( model_initted )            {
880                 Int3();         // Model_init shouldn't be called twice!
881                 return;
882         }
883
884 #ifndef NDEBUG
885         Model_ram = 0;
886 #endif
887
888         for (i=0;i<MAX_POLYGON_MODELS;i++) {
889                 Polygon_models[i] = NULL;
890         }
891
892         // Init the model caching system
893         model_cache_init();
894
895         atexit( model_free_all );
896         model_initted = 1;
897 }
898
899 // routine to parse out values from a user property field of an object
900 void get_user_prop_value(char *buf, char *value)
901 {
902         char *p, *p1, c;
903
904         p = buf;
905         while ( isspace(*p) || (*p == '=') )            // skip white space and equal sign
906                 p++;
907         p1 = p;
908         while ( !iscntrl(*p1) )
909                 p1++;
910         c = *p1;
911         *p1 = '\0';
912         strcpy(value, p);
913         *p1 = c;
914 }
915
916 // funciton to copy model data from one subsystem set to another subsystem set.  This function
917 // is called when two ships use the same model data, but since the model only gets read in one time,
918 // the subsystem data is only present in one location.  The ship code will call this routine to fix
919 // this situation by copying stuff from the source subsystem set to the dest subsystem set.
920 void model_copy_subsystems( int n_subsystems, model_subsystem *d_sp, model_subsystem *s_sp )
921 {
922         int i, j;
923         model_subsystem *source, *dest;
924
925         for (i = 0; i < n_subsystems; i++ ) {
926                 source = &s_sp[i];
927                 for ( j = 0; j < n_subsystems; j++ ) {
928                         dest = &d_sp[j];
929                         if ( !stricmp( source->subobj_name, dest->subobj_name) ) {
930                                 dest->flags = source->flags;
931                                 dest->subobj_num = source->subobj_num;
932                                 dest->model_num = source->model_num;
933                                 dest->pnt = source->pnt;
934                                 dest->radius = source->radius;
935                                 dest->type = source->type;
936                                 dest->turn_rate = source->turn_rate;
937                                 dest->turret_gun_sobj = source->turret_gun_sobj;
938
939                                 strcpy( dest->name, source->name );
940
941                                 if ( dest->type == SUBSYSTEM_TURRET ) {
942                                         int nfp;
943
944                                         dest->turret_fov = source->turret_fov;
945                                         dest->turret_num_firing_points = source->turret_num_firing_points;
946                                         dest->turret_norm = source->turret_norm;
947                                         dest->turret_matrix = source->turret_matrix;
948
949                                         for (nfp = 0; nfp < dest->turret_num_firing_points; nfp++ )
950                                                 dest->turret_firing_point[nfp] = source->turret_firing_point[nfp];
951
952                                         if ( dest->flags & MSS_FLAG_CREWPOINT )
953                                                 strcpy(dest->crewspot, source->crewspot);
954                                 }
955                                 break;
956                         }
957                 }
958                 if ( j == n_subsystems )
959                         Int3();                                                 // get allender -- something is amiss with models
960
961         }
962 }
963
964 // routine to get/set subsystem information
965 static void set_subsystem_info( model_subsystem *subsystemp, char *props, char *dname )
966 {
967         char *p;
968         char buf[32];
969         char    lcdname[256];
970
971         if ( (p = strstr(props, "$name")) != NULL)
972                 get_user_prop_value(p+5, subsystemp->name);
973         else
974                 strcpy( subsystemp->name, dname );
975
976         strcpy(lcdname, dname);
977         strlwr(lcdname);
978
979         // check the name for it's specific type
980         if ( strstr(lcdname, "engine") ) {
981                 subsystemp->type = SUBSYSTEM_ENGINE;
982         } else if ( strstr(lcdname, "radar") ) {
983                 subsystemp->type = SUBSYSTEM_RADAR;
984         } else if ( strstr(lcdname, "turret") ) {
985                 float angle;
986
987                 subsystemp->type = SUBSYSTEM_TURRET;
988                 if ( (p = strstr(props, "$fov")) != NULL )
989                         get_user_prop_value(p+4, buf);                  // get the value of the fov
990                 else
991                         strcpy(buf,"180");
992                 angle = ANG_TO_RAD(atoi(buf))/2.0f;
993                 subsystemp->turret_fov = (float)cos(angle);
994                 subsystemp->turret_num_firing_points = 0;
995
996                 if ( (p = strstr(props, "$crewspot")) != NULL) {
997                         subsystemp->flags |= MSS_FLAG_CREWPOINT;
998                         get_user_prop_value(p+9, subsystemp->crewspot);
999                 }
1000
1001         } else if ( strstr(lcdname, "navigation") ) {
1002                 subsystemp->type = SUBSYSTEM_NAVIGATION;
1003         } else if ( strstr(lcdname, "communication") )  {
1004                 subsystemp->type = SUBSYSTEM_COMMUNICATION;
1005         } else if ( strstr(lcdname, "weapons") ) {
1006                 subsystemp->type = SUBSYSTEM_WEAPONS;
1007         } else if ( strstr(lcdname, "sensors") ) {
1008                 subsystemp->type = SUBSYSTEM_SENSORS;
1009         } else if ( strstr(lcdname, "solar") ) {
1010                 subsystemp->type = SUBSYSTEM_SOLAR;
1011         } else if ( strstr(lcdname, "gas") ) {
1012                 subsystemp->type = SUBSYSTEM_GAS_COLLECT;
1013         } else if ( strstr(lcdname, "activator") ) {
1014                 subsystemp->type = SUBSYSTEM_ACTIVATION;
1015         }  else { // If unrecognized type, set to unknown so artist can continue working...
1016                 subsystemp->type = SUBSYSTEM_UNKNOWN;
1017                 mprintf(("Warning: Ignoring unrecognized subsystem %s, believed to be in ship %s\n", dname, Global_filename));
1018         }
1019
1020         // Rotating subsystem
1021         if ( (p = strstr(props, "$rotate")) != NULL)    {
1022                 subsystemp->flags |= MSS_FLAG_ROTATES;
1023
1024                 // get time for (a) complete rotation (b) step (c) activation
1025                 float turn_time;
1026                 get_user_prop_value(p+7, buf);
1027                 turn_time = (float)atof(buf);
1028
1029                 // CASE OF STEPPED ROTATION
1030                 if ( (p = strstr(props, "$stepped")) != NULL) {
1031
1032                         subsystemp->stepped_rotation = new(stepped_rotation);
1033                         subsystemp->flags |= MSS_FLAG_STEPPED_ROTATE;
1034
1035                         // get number of steps
1036                         if ( (p = strstr(props, "$steps")) != NULL) {
1037                                 get_user_prop_value(p+6, buf);
1038                            subsystemp->stepped_rotation->num_steps = atoi(buf);
1039                          } else {
1040                             subsystemp->stepped_rotation->num_steps = 8;
1041                          }
1042
1043                         // get pause time
1044                         if ( (p = strstr(props, "$t_paused")) != NULL) {
1045                                 get_user_prop_value(p+9, buf);
1046                            subsystemp->stepped_rotation->t_pause = (float)atof(buf);
1047                          } else {
1048                             subsystemp->stepped_rotation->t_pause = 2.0f;
1049                          }
1050
1051                         // get transition time - time to go between steps
1052                         if ( (p = strstr(props, "$t_transit")) != NULL) {
1053                                 get_user_prop_value(p+10, buf);
1054                             subsystemp->stepped_rotation->t_transit = (float)atof(buf);
1055                         } else {
1056                             subsystemp->stepped_rotation->t_transit = 2.0f;
1057                         }
1058
1059                         // get fraction of time spent in accel
1060                         if ( (p = strstr(props, "$fraction_accel")) != NULL) {
1061                                 get_user_prop_value(p+15, buf);
1062                             subsystemp->stepped_rotation->fraction = (float)atof(buf);
1063                            Assert(subsystemp->stepped_rotation->fraction > 0 && subsystemp->stepped_rotation->fraction < 0.5);
1064                         } else {
1065                             subsystemp->stepped_rotation->fraction = 0.3f;
1066                         }
1067
1068                         int num_steps = subsystemp->stepped_rotation->num_steps;
1069                         float t_trans = subsystemp->stepped_rotation->t_transit;
1070                         float fraction = subsystemp->stepped_rotation->fraction;
1071
1072                         subsystemp->stepped_rotation->max_turn_accel = PI2 / (fraction*(1.0f - fraction) * num_steps * t_trans*t_trans);
1073                         subsystemp->stepped_rotation->max_turn_rate =  PI2 / ((1.0f - fraction) * num_steps *t_trans);
1074
1075                 }
1076
1077                 // CASE OF AI ROTATION
1078                 else if ( (p = strstr(props, "$ai")) != NULL) {
1079                         get_user_prop_value(p+8, buf);
1080                         subsystemp->flags |= MSS_FLAG_AI_ROTATE;
1081
1082                         // get parameters - ie, speed / dist / other ??
1083                         // time to activate
1084                         // condition
1085                 }
1086
1087                 // CASE OF NORMAL CONTINUOUS ROTATION
1088                 else {
1089                         if ( fabs(turn_time) < 1 ) {                            
1090                                 // Warning(LOCATION, "%s has subsystem %s with rotation time less than 1 sec", dname, Global_filename );
1091                                 subsystemp->flags &= ~MSS_FLAG_ROTATES;
1092                                 subsystemp->turn_rate = 0.0f;
1093                         } else {
1094                                 subsystemp->turn_rate = PI2 / turn_time;
1095                         }
1096                 }
1097         }
1098
1099 }
1100
1101 // used in collision code to check if submode rotates too far
1102 float get_submodel_delta_angle(submodel_instance_info *sii)
1103 {
1104         vector diff;
1105         vm_vec_sub(&diff, (vector*)&sii->angs, (vector*)&sii->prev_angs);
1106
1107         // find the angle
1108         float delta_angle = vm_vec_mag(&diff);
1109
1110         // make sure we get the short way around
1111         if (delta_angle > PI) {
1112                 delta_angle = (PI2 - delta_angle);
1113         }
1114
1115         return delta_angle;
1116 }
1117
1118 void do_new_subsystem( int n_subsystems, model_subsystem *slist, int subobj_num, float rad, vector *pnt, char *props, char *subobj_name, int model_num )
1119 {
1120         int i;
1121         model_subsystem *subsystemp;
1122
1123
1124         if ( slist==NULL ) return;                      // For TestCode, POFView, etc don't bother
1125         
1126         // try to find the name of the subsystem passed here on the list of subsystems currently on the
1127         // ship.  Assign the values only when the right subsystem is found
1128
1129         for (i = 0; i < n_subsystems; i++ ) {
1130                 subsystemp = &slist[i];
1131                 if ( !stricmp(subobj_name, subsystemp->subobj_name) ) {
1132                         subsystemp->flags = 0;
1133                         subsystemp->subobj_num = subobj_num;
1134                         subsystemp->turret_gun_sobj = -1;
1135                         subsystemp->model_num = model_num;
1136                         subsystemp->pnt = *pnt;                         // use the offset to get the center point of the subsystem
1137                         subsystemp->radius = rad;
1138                         set_subsystem_info( subsystemp, props, subobj_name);
1139                         strcpy(subsystemp->subobj_name, subobj_name);                                           // copy the object name
1140                         return;
1141                 }
1142         }
1143 #ifndef NDEBUG
1144         if ( !ss_warning_shown) {
1145                 char bname[_MAX_FNAME];
1146
1147                 _splitpath(model_filename, NULL, NULL, bname, NULL);
1148                 Warning(LOCATION, "A subsystem was found in model %s that does not have a record in ships.tbl.\nA list of subsystems for this ship will be dumped to:\n\ndata\\tables\\%s.subsystems for inclusion\n into ships.tbl.", model_filename, bname);
1149
1150                 ss_warning_shown = 1;
1151         } else
1152 #endif
1153         nprintf(("warning", "Subsystem %s in ships.tbl not found in model!\n", subobj_name));
1154 #ifndef NDEBUG
1155         if ( ss_fp )    {
1156                 char tmp_buffer[128];
1157                 sprintf(tmp_buffer, "$Subsystem:\t\t\t%s,1,0.0\n", subobj_name);
1158                 cfputs(tmp_buffer, ss_fp);
1159         }
1160 #endif
1161
1162 }
1163
1164 void print_family_tree( polymodel *obj, int modelnum, char * ident, int islast )        
1165 {
1166         char temp[50];
1167
1168         if ( modelnum < 0 ) return;
1169         if (obj==NULL) return;
1170
1171         if (strlen(ident)==0 )  {
1172                 mprintf(( " %s", obj->submodel[modelnum].name ));
1173                 sprintf( temp, " " );
1174         } else if ( islast )    {
1175                 mprintf(( "%sÀÄ%s", ident, obj->submodel[modelnum].name ));
1176                 sprintf( temp, "%s  ", ident );
1177         } else {
1178                 mprintf(( "%sÃÄ%s", ident, obj->submodel[modelnum].name ));
1179                 sprintf( temp, "%s³ ", ident );
1180         }
1181
1182         mprintf(( "\n" ));
1183
1184         int child = obj->submodel[modelnum].first_child;
1185         while( child > -1 )     {
1186                 if ( obj->submodel[child].next_sibling < 0 )
1187                         print_family_tree( obj, child, temp,1 );
1188                 else
1189                         print_family_tree( obj, child, temp,0 );
1190                 child = obj->submodel[child].next_sibling;
1191         }
1192 }
1193
1194 void dump_object_tree(polymodel *obj)
1195 {
1196         print_family_tree( obj, 0, "", 0 );
1197         key_getch();
1198 }
1199
1200 void create_family_tree(polymodel *obj)
1201 {
1202         int i;
1203         for (i=0; i<obj->n_models; i++ )        {
1204                 obj->submodel[i].num_children = 0;
1205                 obj->submodel[i].first_child = -1;
1206                 obj->submodel[i].next_sibling = -1;
1207         }
1208
1209         for (i=0; i<obj->n_models; i++ )        {
1210                 int pn;
1211                 pn = obj->submodel[i].parent;
1212                 if ( pn > -1 )  {
1213                         obj->submodel[pn].num_children++;
1214                         int tmp = obj->submodel[pn].first_child;
1215                         obj->submodel[pn].first_child = i;
1216                         obj->submodel[i].next_sibling = tmp;
1217                 }
1218         }
1219 }
1220
1221 void model_calc_bound_box( vector *box, vector *big_mn, vector *big_mx)
1222 {
1223         box[0].xyz.x = big_mn->xyz.x; box[0].xyz.y = big_mn->xyz.y; box[0].xyz.z = big_mn->xyz.z;
1224         box[1].xyz.x = big_mx->xyz.x; box[1].xyz.y = big_mn->xyz.y; box[1].xyz.z = big_mn->xyz.z;
1225         box[2].xyz.x = big_mx->xyz.x; box[2].xyz.y = big_mx->xyz.y; box[2].xyz.z = big_mn->xyz.z;
1226         box[3].xyz.x = big_mn->xyz.x; box[3].xyz.y = big_mx->xyz.y; box[3].xyz.z = big_mn->xyz.z;
1227
1228
1229         box[4].xyz.x = big_mn->xyz.x; box[4].xyz.y = big_mn->xyz.y; box[4].xyz.z = big_mx->xyz.z;
1230         box[5].xyz.x = big_mx->xyz.x; box[5].xyz.y = big_mn->xyz.y; box[5].xyz.z = big_mx->xyz.z;
1231         box[6].xyz.x = big_mx->xyz.x; box[6].xyz.y = big_mx->xyz.y; box[6].xyz.z = big_mx->xyz.z;
1232         box[7].xyz.x = big_mn->xyz.x; box[7].xyz.y = big_mx->xyz.y; box[7].xyz.z = big_mx->xyz.z;
1233 }
1234
1235
1236 //      Debug thing so we don't repeatedly show warning messages.
1237 #ifndef NDEBUG
1238 int Bogus_warning_flag_1903 = 0;
1239 #endif
1240
1241 //reads a binary file containing a 3d model
1242 int read_model_file(polymodel * pm, char *filename, int n_subsystems, model_subsystem *subsystems)
1243 {
1244         CFILE *fp;
1245         int version;
1246         int id, len, next_chunk;
1247         int i,j;
1248
1249 #ifndef NDEBUG
1250         strcpy(Global_filename, filename);
1251 #endif
1252
1253         fp = cfopen(filename,"rb");
1254         if (!fp){
1255                 Error( LOCATION, "Can't open file <%s>",filename);
1256                 return 0;
1257         }               
1258
1259         // code to get a filename to write out subsystem information for each model that
1260         // is read.  This info is essentially debug stuff that is used to help get models
1261         // into the game quicker
1262 #if 0
1263         {
1264                 char bname[_MAX_FNAME];
1265
1266                 _splitpath(filename, NULL, NULL, bname, NULL);
1267                 sprintf(debug_name, "%s.subsystems", bname);
1268                 ss_fp = cfopen(debug_name, "wb", CFILE_NORMAL, CF_TYPE_TABLES );
1269                 if ( !ss_fp )   {
1270                         mprintf(( "Can't open debug file for writing subsystems for %s\n", filename));
1271                 } else {
1272                         strcpy(model_filename, filename);
1273                         ss_warning_shown = 0;
1274                 }
1275         }
1276 #endif
1277
1278         id = cfread_int(fp);
1279
1280         if (id != ID_PSPO)
1281                 Error( LOCATION, "Bad ID in model file <%s>",filename);
1282
1283         // Version is major*100+minor
1284         // So, major = version / 100;
1285         //     minor = version % 100;
1286         version = cfread_int(fp);
1287
1288         //Warning( LOCATION, "POF Version = %d", version );
1289         
1290         if (version < PM_COMPATIBLE_VERSION || (version/100) > PM_OBJFILE_MAJOR_VERSION)        {
1291                 Warning(LOCATION,"Bad version (%d) in model file <%s>",version,filename);
1292                 return 0;
1293         }
1294
1295         pm->version = version;
1296         Assert( strlen(filename) < FILENAME_LEN );
1297         strncpy(pm->filename, filename, FILENAME_LEN);
1298
1299         memset( &pm->view_positions, 0, sizeof(pm->view_positions) );
1300
1301         // reset insignia counts
1302         pm->num_ins = 0;
1303
1304         id = cfread_int(fp);
1305         len = cfread_int(fp);
1306         next_chunk = cftell(fp) + len;
1307
1308         while (!cfeof(fp)) {
1309
1310 //              mprintf(("Processing chunk <%c%c%c%c>, len = %d\n",id,id>>8,id>>16,id>>24,len));
1311 //              key_getch();
1312
1313                 switch (id) {
1314
1315                         case ID_OHDR: {         //Object header
1316                                 //vector v;
1317
1318                                 //mprintf(0,"Got chunk OHDR, len=%d\n",len);
1319
1320 #if defined( FREESPACE1_FORMAT )
1321                                 pm->n_models = cfread_int(fp);
1322 //                              mprintf(( "Num models = %d\n", pm->n_models ));
1323                                 pm->rad = cfread_float(fp);
1324                                 pm->flags = cfread_int(fp);     // 1=Allow tiling
1325 #elif defined( FREESPACE2_FORMAT )
1326                                 pm->rad = cfread_float(fp);
1327                                 pm->flags = cfread_int(fp);     // 1=Allow tiling
1328                                 pm->n_models = cfread_int(fp);
1329 //                              mprintf(( "Num models = %d\n", pm->n_models ));
1330 #endif
1331                                 
1332                                 pm->submodel = (bsp_info *)malloc( sizeof(bsp_info)*pm->n_models );
1333                                 Assert(pm->submodel != NULL );
1334                                 memset( pm->submodel, 0, sizeof(bsp_info)*pm->n_models );
1335
1336                                 //Assert(pm->n_models <= MAX_SUBMODELS);
1337
1338                                 cfread_vector(&pm->mins,fp);
1339                                 cfread_vector(&pm->maxs,fp);
1340                                 model_calc_bound_box(pm->bounding_box,&pm->mins,&pm->maxs);
1341                                 
1342                                 pm->n_detail_levels = cfread_int(fp);
1343                         //      mprintf(( "There are %d detail levels\n", pm->n_detail_levels ));
1344                                 for (i=0; i<pm->n_detail_levels;i++ )   {
1345                                         pm->detail[i] = cfread_int(fp);
1346                                         pm->detail_depth[i] = 0.0f;
1347                         ///             mprintf(( "Detail level %d is model %d.\n", i, pm->detail[i] ));
1348                                 }
1349
1350                                 pm->num_debris_objects = cfread_int(fp);
1351                                 Assert( pm->num_debris_objects <= MAX_DEBRIS_OBJECTS );
1352                                 // mprintf(( "There are %d debris objects\n", pm->num_debris_objects ));
1353                                 for (i=0; i<pm->num_debris_objects;i++ )        {
1354                                         pm->debris_objects[i] = cfread_int(fp);
1355                                         // mprintf(( "Debris object %d is model %d.\n", i, pm->debris_objects[i] ));
1356                                 }
1357
1358                                 if ( pm->version >= 1903 )      {
1359         
1360                                         if ( pm->version >= 2009 )      {
1361                                                                                                                                         
1362                                                 pm->mass = cfread_float(fp);
1363                                                 cfread_vector( &pm->center_of_mass, fp );
1364                                                 cfread_vector( &pm->moment_of_inertia.v.rvec, fp );
1365                                                 cfread_vector( &pm->moment_of_inertia.v.uvec, fp );
1366                                                 cfread_vector( &pm->moment_of_inertia.v.fvec, fp );
1367                                         } else {
1368                                                 // old code where mass wasn't based on area, so do the calculation manually
1369
1370                                                 float vol_mass = cfread_float(fp);
1371                                                 //      Attn: John Slagel:  The following is better done in bspgen.
1372                                                 // Convert volume (cubic) to surface area (quadratic) and scale so 100 -> 100
1373                                                 float area_mass = (float) pow(vol_mass, 0.6667f) * 4.65f;
1374
1375                                                 pm->mass = area_mass;
1376                                                 float mass_ratio = vol_mass / area_mass; 
1377                                                         
1378                                                 cfread_vector( &pm->center_of_mass, fp );
1379                                                 cfread_vector( &pm->moment_of_inertia.v.rvec, fp );
1380                                                 cfread_vector( &pm->moment_of_inertia.v.uvec, fp );
1381                                                 cfread_vector( &pm->moment_of_inertia.v.fvec, fp );
1382
1383                                                 // John remove this with change to bspgen
1384                                                 vm_vec_scale( &pm->moment_of_inertia.v.rvec, mass_ratio );
1385                                                 vm_vec_scale( &pm->moment_of_inertia.v.uvec, mass_ratio );
1386                                                 vm_vec_scale( &pm->moment_of_inertia.v.fvec, mass_ratio );
1387                                         }       
1388                                 } else {
1389 #ifndef NDEBUG
1390                                         if (stricmp("fighter04.pof", filename)) {
1391                                                 if (Bogus_warning_flag_1903 == 0) {
1392                                                         Warning(LOCATION, "Ship %s is old.  Cannot compute mass.\nSetting to 50.0f.  Talk to John.", filename);
1393                                                         Bogus_warning_flag_1903 = 1;
1394                                                 }
1395                                         }
1396 #endif
1397                                         pm->mass = 50.0f;
1398                                         vm_vec_zero( &pm->center_of_mass );
1399                                         vm_set_identity( &pm->moment_of_inertia );
1400                                         vm_vec_scale(&pm->moment_of_inertia.v.rvec, 0.001f);
1401                                         vm_vec_scale(&pm->moment_of_inertia.v.uvec, 0.001f);
1402                                         vm_vec_scale(&pm->moment_of_inertia.v.fvec, 0.001f);
1403                                 }
1404
1405                                 // read in cross section info
1406                                 pm->xc = NULL;
1407                                 if ( pm->version >= 2014 ) {
1408                                         pm->num_xc = cfread_int(fp);
1409                                         if (pm->num_xc > 0) {
1410                                                 pm->xc = (cross_section*) malloc(pm->num_xc*sizeof(cross_section));
1411                                                 for (int i=0; i<pm->num_xc; i++) {
1412                                                         pm->xc[i].z = cfread_float(fp);
1413                                                         pm->xc[i].radius = cfread_float(fp);
1414                                                 }
1415                                         }
1416                                 } else {
1417                                         pm->num_xc = 0;
1418                                 }
1419
1420                                 if ( pm->version >= 2007 )      {
1421                                         pm->num_lights = cfread_int(fp);
1422                                         //mprintf(( "Found %d lights!\n", pm->num_lights ));
1423
1424                                         pm->lights = (bsp_light *)malloc( sizeof(bsp_light)*pm->num_lights );
1425                                         for (i=0; i<pm->num_lights; i++ )       {                       
1426                                                 cfread_vector(&pm->lights[i].pos,fp);
1427                                                 pm->lights[i].type = cfread_int(fp);
1428                                                 pm->lights[i].value = 0.0f;
1429                                         }                                                               
1430                                 } else {
1431                                         pm->num_lights = 0;
1432                                         pm->lights = NULL;
1433                                 }
1434
1435                                 break;
1436                         }
1437                         
1438                         case ID_SOBJ: {         //Subobject header
1439                                 int n;
1440                                 char *p, props[MAX_PROP_LEN];
1441 //                              float d;
1442
1443                                 //mprintf(0,"Got chunk SOBJ, len=%d\n",len);
1444
1445                                 n = cfread_int(fp);
1446
1447                                 Assert(n < pm->n_models );
1448
1449 #if defined( FREESPACE2_FORMAT )        
1450                                 pm->submodel[n].rad = cfread_float(fp);         //radius
1451 #endif
1452
1453                                 pm->submodel[n].parent = cfread_int(fp);
1454
1455 //                              cfread_vector(&pm->submodel[n].norm,fp);
1456 //                              d = cfread_float(fp);                           
1457 //                              cfread_vector(&pm->submodel[n].pnt,fp);
1458                                 cfread_vector(&pm->submodel[n].offset,fp);
1459
1460 //                      mprintf(( "Subobj %d, offs = %.1f, %.1f, %.1f\n", n, pm->submodel[n].offset.xyz.x, pm->submodel[n].offset.xyz.y, pm->submodel[n].offset.xyz.z ));
1461         
1462 #if defined ( FREESPACE1_FORMAT )
1463                                 pm->submodel[n].rad = cfread_float(fp);         //radius
1464 #endif
1465
1466 //                              pm->submodel[n].tree_offset = cfread_int(fp);   //offset
1467 //                              pm->submodel[n].data_offset = cfread_int(fp);   //offset
1468
1469                                 cfread_vector(&pm->submodel[n].geometric_center,fp);
1470
1471                                 cfread_vector(&pm->submodel[n].min,fp);
1472                                 cfread_vector(&pm->submodel[n].max,fp);
1473
1474                                 model_calc_bound_box(pm->submodel[n].bounding_box,&pm->submodel[n].min,&pm->submodel[n].max);
1475
1476                                 pm->submodel[n].name[0] = '\0';
1477
1478                                 cfread_string_len( pm->submodel[n].name, MAX_NAME_LEN, fp);             // get the name
1479                                 cfread_string_len(props, MAX_PROP_LEN, fp);                     // and the user properites
1480
1481                                 pm->submodel[n].movement_type = cfread_int(fp);
1482                                 pm->submodel[n].movement_axis = cfread_int(fp);
1483
1484                                 // change turret movement type to MOVEMENT_TYPE_ROT_SPECIAL
1485                                 if (pm->submodel[n].movement_type == MOVEMENT_TYPE_ROT) {
1486                                         if ( strstr(pm->submodel[n].name, "turret") || strstr(pm->submodel[n].name, "gun") || strstr(pm->submodel[n].name, "cannon")) {
1487                                                 pm->submodel[n].movement_type = MOVEMENT_TYPE_ROT_SPECIAL;
1488                                         } else if (strstr(pm->submodel[n].name, "thruster")) {
1489                                                 // Int3();
1490                                                 pm->submodel[n].movement_type = MOVEMENT_TYPE_NONE;
1491                                                 pm->submodel[n].movement_axis = MOVEMENT_AXIS_NONE;
1492                                         }
1493                                 }
1494
1495                                 if ( pm->submodel[n].name[0] == '\0' ) {
1496                                         strcpy(pm->submodel[n].name, "unknown object name");
1497                                 }
1498
1499                                 bool rotating_submodel_has_subsystem = !(pm->submodel[n].movement_type == MOVEMENT_TYPE_ROT);
1500                                 if ( ( p = strstr(props, "$special"))!= NULL ) {
1501                                         char type[32];
1502
1503                                         get_user_prop_value(p+9, type);
1504                                         if ( !stricmp(type, "subsystem") ) {    // if we have a subsystem, put it into the list!
1505                                                 do_new_subsystem( n_subsystems, subsystems, n, pm->submodel[n].rad, &pm->submodel[n].offset, props, pm->submodel[n].name, pm->id );
1506                                                 rotating_submodel_has_subsystem = true;
1507                                         } else if ( !stricmp(type, "no_rotate") ) {
1508                                                 // mark those submodels which should not rotate - ie, those with no subsystem
1509                                                 pm->submodel[n].movement_type = MOVEMENT_TYPE_NONE;
1510                                                 pm->submodel[n].movement_axis = MOVEMENT_AXIS_NONE;
1511                                         } else {
1512                                                 // if submodel rotates (via bspgen), then there is either a subsys or special=no_rotate
1513                                                 Assert( pm->submodel[n].movement_type != MOVEMENT_TYPE_ROT );
1514                                         }
1515                                 }
1516
1517                                 if ( !rotating_submodel_has_subsystem ) {
1518                                         nprintf(("Model", "Model %s: Rotating Submodel without subsystem: %s\n", pm->filename, pm->submodel[n].name));
1519
1520                                         // mark those submodels which should not rotate - ie, those with no subsystem
1521                                         pm->submodel[n].movement_type = MOVEMENT_TYPE_NONE;
1522                                         pm->submodel[n].movement_axis = MOVEMENT_AXIS_NONE;
1523                                 }
1524
1525
1526                                 pm->submodel[n].angs.p = 0.0f;
1527                                 pm->submodel[n].angs.b = 0.0f;
1528                                 pm->submodel[n].angs.h = 0.0f;
1529
1530                                 {
1531                                         int nchunks = cfread_int( fp );         // Throw away nchunks
1532                                         if ( nchunks > 0 )      {
1533                                                 Error( LOCATION, "Model '%s' is chunked.  See John or Adam!\n", pm->filename );
1534                                         }
1535                                 }
1536                                 pm->submodel[n].bsp_data_size = cfread_int(fp);
1537                                 if ( pm->submodel[n].bsp_data_size > 0 )        {
1538                                         pm->submodel[n].bsp_data = (ubyte *)malloc(pm->submodel[n].bsp_data_size);
1539                                         cfread(pm->submodel[n].bsp_data,1,pm->submodel[n].bsp_data_size,fp);
1540 #if (SDL_BYTEORDER == SDL_BIG_ENDIAN)           //tigital
1541                                         swap_bsp_data( pm, pm->submodel[n].bsp_data );
1542 #endif
1543                                 } else {
1544                                         pm->submodel[n].bsp_data = NULL;
1545                                 }
1546
1547                                 if ( strstr( pm->submodel[n].name, "thruster") )        
1548                                         pm->submodel[n].is_thruster=1;
1549                                 else
1550                                         pm->submodel[n].is_thruster=0;
1551
1552                                 if ( strstr( pm->submodel[n].name, "-destroyed") )      
1553                                         pm->submodel[n].is_damaged=1;
1554                                 else
1555                                         pm->submodel[n].is_damaged=0;
1556                                         
1557                                 //mprintf(( "Submodel %d, name '%s', parent = %d\n", n, pm->submodel[n].name, pm->submodel[n].parent ));
1558                                 //key_getch();
1559
1560                 //mprintf(( "Submodel %d, tree offset %d\n", n, pm->submodel[n].tree_offset ));
1561                 //mprintf(( "Submodel %d, data offset %d\n", n, pm->submodel[n].data_offset ));
1562                 //key_getch();
1563
1564
1565                                 break;
1566
1567                         }
1568
1569                         case ID_SHLD:
1570                                 {
1571                                         int nverts, ntris;                                      
1572
1573                                         nverts = cfread_int( fp );              // get the number of vertices in the list
1574                                         pm->shield.nverts = nverts;
1575                                         pm->shield.verts = (shield_vertex *)malloc(nverts * sizeof(shield_vertex) );
1576                                         Assert( pm->shield.verts );
1577                                         for ( i = 0; i < nverts; i++ )                                                  // read in the vertex list
1578                                                 cfread_vector( &(pm->shield.verts[i].pos), fp );
1579
1580                                         ntris = cfread_int( fp );               // get the number of triangles that compose the shield
1581                                         pm->shield.ntris = ntris;
1582                                         pm->shield.tris = (shield_tri *)malloc(ntris * sizeof(shield_tri) );
1583                                         Assert( pm->shield.tris );
1584                                         for ( i = 0; i < ntris; i++ ) {
1585                                                 cfread_vector( &(pm->shield.tris[i].norm), fp );
1586                                                 for ( j = 0; j < 3; j++ ) {
1587                                                         pm->shield.tris[i].verts[j] = cfread_int( fp );         // read in the indices into the shield_vertex list
1588                                                         /*
1589 #ifndef NDEBUG
1590                                                         if (pm->shield.tris[i].verts[j] >= nverts)
1591                                                                 if (!warning_displayed) {
1592                                                                         warning_displayed = 1;
1593                                                                         Warning(LOCATION, "Ship %s has a bogus shield mesh.\nOnly %i vertices, index %i found.\n", filename, nverts, pm->shield.tris[i].verts[j]);
1594                                                                 }
1595 #endif
1596                                                                 */
1597                                                 }
1598                                                 for ( j = 0; j < 3; j++ )
1599                                                         pm->shield.tris[i].neighbors[j] = cfread_int( fp );     // read in the neighbor indices -- indexes into tri list
1600                                         }
1601                                         break;
1602
1603
1604                                         
1605                                 }
1606                                 break;
1607
1608                         case ID_GPNT:
1609                                 pm->n_guns = cfread_int(fp);
1610                                 pm->gun_banks = (w_bank *)malloc(sizeof(w_bank) * pm->n_guns);
1611                                 Assert( pm->gun_banks != NULL );
1612
1613                                 for (i = 0; i < pm->n_guns; i++ ) {
1614                                         w_bank *bank = &pm->gun_banks[i];
1615
1616                                         bank->num_slots = cfread_int(fp);
1617                                         Assert ( bank->num_slots < MAX_SLOTS );
1618                                         for (j = 0; j < bank->num_slots; j++) {
1619                                                 cfread_vector( &(bank->pnt[j]), fp );
1620                                                 cfread_vector( &(bank->norm[j]), fp );
1621                                         }
1622                                 }
1623                                 break;
1624                         
1625                         case ID_MPNT:
1626                                 pm->n_missiles = cfread_int(fp);
1627                                 pm->missile_banks = (w_bank *)malloc(sizeof(w_bank) * pm->n_missiles);
1628                                 Assert( pm->missile_banks != NULL );
1629
1630                                 for (i = 0; i < pm->n_missiles; i++ ) {
1631                                         w_bank *bank = &pm->missile_banks[i];
1632
1633                                         bank->num_slots = cfread_int(fp);
1634                                         Assert ( bank->num_slots < MAX_SLOTS );
1635                                         for (j = 0; j < bank->num_slots; j++) {
1636                                                 cfread_vector( &(bank->pnt[j]), fp );
1637                                                 cfread_vector( &(bank->norm[j]), fp );
1638                                         }
1639                                 }
1640                                 break;
1641
1642                         case ID_DOCK: {
1643                                 char props[MAX_PROP_LEN];
1644
1645                                 pm->n_docks = cfread_int(fp);
1646                                 pm->docking_bays = (dock_bay *)malloc(sizeof(dock_bay) * pm->n_docks);
1647                                 Assert( pm->docking_bays != NULL );
1648
1649                                 for (i = 0; i < pm->n_docks; i++ ) {
1650                                         char *p;
1651                                         dock_bay *bay = &pm->docking_bays[i];
1652
1653                                         cfread_string_len( props, MAX_PROP_LEN, fp );
1654                                         if ( (p = strstr(props, "$name"))!= NULL )
1655                                                 get_user_prop_value(p+5, bay->name);
1656                                         else
1657                                                 sprintf(bay->name, "<unnamed bay %c>", 'A' + i);
1658                                         bay->num_spline_paths = cfread_int( fp );
1659                                         if ( bay->num_spline_paths > 0 ) {
1660                                                 bay->splines = (int *)malloc(sizeof(int) * bay->num_spline_paths);
1661                                                 for ( j = 0; j < bay->num_spline_paths; j++ )
1662                                                         bay->splines[j] = cfread_int(fp);
1663                                         } else {
1664                                                 bay->splines = NULL;
1665                                         }
1666
1667                                         // determine what this docking bay can be used for
1668                                         if ( !strnicmp(bay->name, "cargo", 5) )
1669                                                 bay->type_flags = DOCK_TYPE_CARGO;
1670                                         else
1671                                                 bay->type_flags = (DOCK_TYPE_REARM | DOCK_TYPE_GENERIC);
1672
1673                                         bay->num_slots = cfread_int(fp);
1674                                         Assert( bay->num_slots == 2 );                                  // Get Allender if Asserted!
1675                                         for (j = 0; j < bay->num_slots; j++) {
1676                                                 cfread_vector( &(bay->pnt[j]), fp );
1677                                                 cfread_vector( &(bay->norm[j]), fp );
1678                                         }
1679                                 }
1680                                 break;
1681                         }
1682
1683                         case ID_FUEL:
1684                                 char props[MAX_PROP_LEN];
1685                                 pm->n_thrusters = cfread_int(fp);
1686                                 pm->thrusters = (thruster_bank *)malloc(sizeof(thruster_bank) * pm->n_thrusters);
1687                                 Assert( pm->thrusters != NULL );
1688
1689                                 for (i = 0; i < pm->n_thrusters; i++ ) {
1690                                         thruster_bank *bank = &pm->thrusters[i];
1691
1692                                         bank->num_slots = cfread_int(fp);
1693
1694                                         if (pm->version < 2117) {
1695                                                 bank->wash_info_index = -1;
1696                                         } else {
1697                                                 cfread_string_len( props, MAX_PROP_LEN, fp );
1698                                                 // look for $engine_subsystem=xxx
1699                                                 int length = strlen(props);
1700                                                 if (length > 0) {
1701                                                         int base_length = strlen("$engine_subsystem=");
1702                                                         Assert( strstr( (const char *)&props, "$engine_subsystem=") != NULL );
1703                                                         Assert( length > base_length );
1704                                                         char *engine_subsys_name = props + base_length;
1705                                                         if (engine_subsys_name[0] == '$') {
1706                                                                 engine_subsys_name++;
1707                                                         }
1708
1709                                                         nprintf(("wash", "Ship %s with engine wash associated with subsys %s\n", filename, engine_subsys_name));
1710
1711                                                         // set wash_info_index to invalid
1712                                                         int table_error = 1;
1713                                                         bank->wash_info_index = -1;
1714                                                         for (int k=0; k<n_subsystems; k++) {
1715                                                                 if ( 0 == stricmp(subsystems[k].subobj_name, engine_subsys_name) ) {
1716                                                                         bank->wash_info_index = subsystems[k].engine_wash_index;
1717                                                                         if (bank->wash_info_index >= 0) {
1718                                                                                 table_error = 0;
1719                                                                         }
1720                                                                         break;
1721                                                                 }
1722                                                         }
1723
1724                                                         if ( (bank->wash_info_index == -1) && (n_subsystems > 0) ) {
1725                                                                 if (table_error) {
1726                                                                         Warning(LOCATION, "No engine wash table entry in ships.tbl for ship model %s", filename);
1727                                                                 } else {
1728                                                                         Warning(LOCATION, "Inconsistent model: Engine wash engine subsystem does not match any ship subsytem names for ship model %s", filename);
1729                                                                 }
1730                                                         }
1731                                                 } else {
1732                                                         bank->wash_info_index = -1;
1733                                                 }
1734                                         }
1735
1736                                         for (j = 0; j < bank->num_slots; j++) {
1737
1738                                                 cfread_vector( &(bank->pnt[j]), fp );
1739                                                 cfread_vector( &(bank->norm[j]), fp );
1740                                                 if ( pm->version > 2004 )       {
1741                                                         bank->radius[j] = cfread_float( fp );
1742                                                         //mprintf(( "Rad = %.2f\n", rad ));
1743                                                 } else {
1744                                                         bank->radius[j] = 1.0f;
1745                                                 }
1746                                         }
1747                                         //mprintf(( "Num slots = %d\n", bank->num_slots ));
1748
1749                                 }
1750                                 break;
1751
1752                         case ID_TGUN:
1753                         case ID_TMIS: {
1754                                 int n_banks, n_slots, parent;
1755                                 model_subsystem *subsystemp;
1756                                 int i, j, snum=-1;
1757         
1758                                 n_banks = cfread_int(fp);                               // number of turret points
1759                                 for ( i = 0; i < n_banks; i++ ) {
1760                                         int physical_parent;                    // who are we attached to?
1761                                         parent = cfread_int( fp );                      // get the turret parent of the object
1762
1763                                         physical_parent = cfread_int(fp);       // The parent subobj that this is physically attached to
1764
1765                                         if ( subsystems ) {
1766                                                 for ( snum = 0; snum < n_subsystems; snum++ ) {
1767                                                         subsystemp = &subsystems[snum];
1768
1769                                                         if ( parent == subsystemp->subobj_num ) {
1770                                                                 cfread_vector( &subsystemp->turret_norm, fp );
1771                                                                 vm_vector_2_matrix(&subsystemp->turret_matrix,&subsystemp->turret_norm,NULL,NULL);
1772
1773                                                                 n_slots = cfread_int( fp );
1774                                                                 subsystemp->turret_gun_sobj = physical_parent;
1775                                                                 Assert(n_slots < MAX_TFP);              // only MAX_TFP firing points per model_subsystem
1776                                                                 for (j = 0; j < n_slots; j++ )  {
1777                                                                         cfread_vector( &subsystemp->turret_firing_point[j], fp );
1778                                                                 }
1779                                                                 Assert( n_slots > 0 );
1780
1781                                                                 subsystemp->turret_num_firing_points = n_slots;
1782
1783                                                                 break;
1784                                                         }
1785                                                 }
1786                                         }
1787
1788 //turret_gun_sobj
1789
1790                                         if ( (n_subsystems == 0) || (snum == n_subsystems) ) {
1791                                                 vector bogus;
1792
1793                                                 nprintf(("Warning", "Turret object not found for turret firing point in model %s\n", model_filename));
1794                                                 cfread_vector( &bogus, fp );
1795                                                 n_slots = cfread_int( fp );
1796                                                 for (j = 0; j < n_slots; j++ )
1797                                                         cfread_vector( &bogus, fp );
1798                                         }
1799                                 }
1800                                 break;
1801                         }
1802
1803                         case ID_SPCL: {
1804                                 char name[MAX_NAME_LEN], props[MAX_PROP_LEN], *p;
1805                                 int n_specials;
1806                                 float radius;
1807                                 vector pnt;
1808
1809                                 n_specials = cfread_int(fp);            // get the number of special subobjects we have
1810                                 for (i = 0; i < n_specials; i++) {
1811
1812                                         // get the next free object of the subobject list.  Flag error if no more room
1813
1814                                         cfread_string_len(name, MAX_NAME_LEN, fp);                      // get the name of this special polygon
1815
1816                                         cfread_string_len(props, MAX_PROP_LEN, fp);             // will definately have properties as well!
1817                                         cfread_vector( &pnt, fp );
1818                                         radius = cfread_float( fp );
1819
1820                                         // check if $Split
1821                                         p = strstr(name, "$split");
1822                                         if (p != NULL) {
1823                                                 pm->split_plane[pm->num_split_plane] = pnt.xyz.z;
1824                                                 pm->num_split_plane++;
1825                                                 Assert(pm->num_split_plane <= MAX_SPLIT_PLANE);
1826                                         } else if ( ( p = strstr(props, "$special"))!= NULL ) {
1827                                                 char type[32];
1828
1829                                                 get_user_prop_value(p+9, type);
1830                                                 if ( !stricmp(type, "subsystem") )                                              // if we have a subsystem, put it into the list!
1831                                                         do_new_subsystem( n_subsystems, subsystems, -1, radius, &pnt, props, &name[1], pm->id );                // skip the first '$' character of the name
1832                                         } else if ( strstr(name, "$enginelarge") || strstr(name, "$enginehuge") ){
1833                                                 do_new_subsystem( n_subsystems, subsystems, -1, radius, &pnt, props, &name[1], pm->id );                // skip the first '$' character of the name
1834                                         } else {
1835                                                 nprintf(("Warning", "Unknown special object type %s while reading model %s\n", name, pm->filename));
1836                                         }                                       
1837                                 }
1838                                 break;
1839                         }
1840                         
1841                         case ID_TXTR: {         //Texture filename list
1842                                 int i,n;
1843 //                              char name_buf[128];
1844
1845                                 //mprintf(0,"Got chunk TXTR, len=%d\n",len);
1846
1847                                 n = cfread_int(fp);
1848                                 pm->n_textures = n;
1849                                 // Dont overwrite memory!!
1850                                 Assert(n <= MAX_MODEL_TEXTURES);
1851                                 //mprintf(0,"  num textures = %d\n",n);
1852                                 for (i=0; i<n; i++ )    {
1853                                         char tmp_name[256];
1854                                         cfread_string_len(tmp_name,127,fp);
1855
1856                                         if ( strstr(tmp_name, "thruster") || strstr(tmp_name, "invisible") )    {
1857                                                 // Don't load textures for thruster animations or invisible textures
1858                                                 pm->textures[i] = -1;
1859                                         } else {
1860                                                 pm->textures[i] = bm_load( tmp_name );
1861                                                 if (pm->textures[i]<0)  {
1862                                                         Error( LOCATION, "Couldn't open texture '%s'\nreferenced by model '%s'\n", tmp_name, pm->filename );
1863                                                 }
1864                                         }
1865                                         pm->original_textures[i] = pm->textures[i];
1866                                         //mprintf(0,"<%s>\n",name_buf);
1867                                 }
1868
1869                                 break;
1870                         }
1871                         
1872 /*                      case ID_IDTA:           //Interpreter data
1873                                 //mprintf(0,"Got chunk IDTA, len=%d\n",len);
1874
1875                                 pm->model_data = (ubyte *)malloc(len);
1876                                 pm->model_data_size = len;
1877                                 Assert(pm->model_data != NULL );
1878                         
1879                                 cfread(pm->model_data,1,len,fp);
1880                         
1881                                 break;
1882 */
1883
1884                         case ID_INFO:           // don't need to do anything with info stuff
1885
1886                                 #ifndef NDEBUG
1887                                         pm->debug_info_size = len;
1888                                         pm->debug_info = (char *)malloc(pm->debug_info_size+1);
1889                                         Assert(pm->debug_info!=NULL);
1890                                         memset(pm->debug_info,0,len+1);
1891                                         cfread( pm->debug_info, 1, len, fp );
1892                                 #endif
1893                                 break;
1894
1895                         case ID_GRID:
1896                                 break;
1897
1898                         case ID_PATH:
1899                                 pm->n_paths = cfread_int( fp );
1900                                 pm->paths = (model_path *)malloc(sizeof(model_path)*pm->n_paths);
1901                                 Assert( pm->paths != NULL );
1902                                         
1903                                 for (i=0; i<pm->n_paths; i++ )  {
1904                                         cfread_string_len(pm->paths[i].name , MAX_NAME_LEN-1, fp);
1905                                         if ( pm->version >= 2002 ) {
1906                                                 // store the sub_model name number of the parent
1907                                                 cfread_string_len(pm->paths[i].parent_name , MAX_NAME_LEN-1, fp);
1908                                                 // get rid of leading '$' char in name
1909                                                 if ( pm->paths[i].parent_name[0] == '$' ) {
1910                                                         char tmpbuf[MAX_NAME_LEN];
1911                                                         strcpy(tmpbuf, pm->paths[i].parent_name+1);
1912                                                         strcpy(pm->paths[i].parent_name, tmpbuf);
1913                                                 }
1914                                                 // store the sub_model index (ie index into pm->submodel) of the parent
1915                                                 pm->paths[i].parent_submodel = -1;
1916                                                 for ( j = 0; j < pm->n_models; j++ ) {
1917                                                         if ( !stricmp( pm->submodel[j].name, pm->paths[i].parent_name) ) {
1918                                                                 pm->paths[i].parent_submodel = j;
1919                                                         }
1920                                                 }
1921                                         } else {
1922                                                 pm->paths[i].parent_name[0] = 0;
1923                                                 pm->paths[i].parent_submodel = -1;
1924                                         }
1925                                         pm->paths[i].nverts = cfread_int( fp );
1926                                         pm->paths[i].verts = (mp_vert *)malloc( sizeof(mp_vert) * pm->paths[i].nverts );
1927                                         pm->paths[i].goal = pm->paths[i].nverts - 1;
1928                                         pm->paths[i].type = MP_TYPE_UNUSED;
1929                                         pm->paths[i].value = 0;
1930                                         Assert(pm->paths[i].verts!=NULL);
1931                                         for (j=0; j<pm->paths[i].nverts; j++ )  {
1932                                                 cfread_vector(&pm->paths[i].verts[j].pos,fp );
1933                                                 pm->paths[i].verts[j].radius = cfread_float( fp );
1934                                                 
1935                                                 {                                       // version 1802 added turret stuff
1936                                                         int nturrets, k;
1937
1938                                                         nturrets = cfread_int( fp );
1939                                                         pm->paths[i].verts[j].nturrets = nturrets;
1940                                                         pm->paths[i].verts[j].turret_ids = (int *)malloc( sizeof(int) * nturrets );
1941                                                         for ( k = 0; k < nturrets; k++ )
1942                                                                 pm->paths[i].verts[j].turret_ids[k] = cfread_int( fp );
1943                                                 } 
1944                                                 
1945                                         }
1946                                 }
1947                                 break;
1948
1949                         case ID_EYE:                                    // an eye position(s)
1950                                 {
1951                                         int num_eyes, i;
1952
1953                                         // all eyes points are stored simply as vectors and their normals.
1954                                         // 0th element is used as usual player view position.
1955
1956                                         num_eyes = cfread_int( fp );
1957                                         pm->n_view_positions = num_eyes;
1958                                         Assert ( num_eyes < MAX_EYES );
1959                                         for (i = 0; i < num_eyes; i++ ) {
1960                                                 pm->view_positions[i].parent = cfread_int( fp );
1961                                                 cfread_vector( &pm->view_positions[i].pnt, fp );
1962                                                 cfread_vector( &pm->view_positions[i].norm, fp );
1963                                         }
1964                                 }
1965                                 break;                  
1966
1967                         case ID_INSG:                           
1968                                 int num_ins, num_verts, num_faces, idx, idx2, idx3;                     
1969                                 
1970                                 // get the # of insignias
1971                                 num_ins = cfread_int(fp);
1972                                 pm->num_ins = num_ins;
1973                                 
1974                                 // read in the insignias
1975                                 for(idx=0; idx<num_ins; idx++){
1976                                         // get the detail level
1977                                         pm->ins[idx].detail_level = cfread_int(fp);
1978
1979                                         // # of faces
1980                                         num_faces = cfread_int(fp);
1981                                         pm->ins[idx].num_faces = num_faces;
1982                                         Assert(num_faces <= MAX_INS_FACES);
1983
1984                                         // # of vertices
1985                                         num_verts = cfread_int(fp);
1986                                         Assert(num_verts <= MAX_INS_VECS);
1987
1988                                         // read in all the vertices
1989                                         for(idx2=0; idx2<num_verts; idx2++){
1990                                                 cfread_vector(&pm->ins[idx].vecs[idx2], fp);
1991                                         }
1992
1993                                         // read in world offset
1994                                         cfread_vector(&pm->ins[idx].offset, fp);
1995
1996                                         // read in all the faces
1997                                         for(idx2=0; idx2<pm->ins[idx].num_faces; idx2++){                                               
1998                                                 // read in 3 vertices
1999                                                 for(idx3=0; idx3<3; idx3++){
2000                                                         pm->ins[idx].faces[idx2][idx3] = cfread_int(fp);
2001                                                         pm->ins[idx].u[idx2][idx3] = cfread_float(fp);
2002                                                         pm->ins[idx].v[idx2][idx3] = cfread_float(fp);
2003                                                 }
2004                                         }
2005                                 }                                       
2006                                 break;
2007
2008                         // autocentering info
2009                         case ID_ACEN:
2010                                 cfread_vector(&pm->autocenter, fp);
2011                                 pm->flags |= PM_FLAG_AUTOCEN;
2012                                 break;
2013
2014                         default:
2015                                 mprintf(("Unknown chunk <%c%c%c%c>, len = %d\n",id,id>>8,id>>16,id>>24,len));
2016                                 cfseek(fp,len,SEEK_CUR);
2017                                 break;
2018
2019                 }
2020                 cfseek(fp,next_chunk,SEEK_SET);
2021
2022                 id = cfread_int(fp);
2023                 len = cfread_int(fp);
2024                 next_chunk = cftell(fp) + len;
2025
2026         }
2027
2028 #ifndef NDEBUG
2029         if ( ss_fp) {
2030                 int size;
2031                 
2032                 cfclose(ss_fp);
2033                 ss_fp = cfopen(debug_name, "rb");
2034                 if ( ss_fp )    {
2035                         size = cfilelength(ss_fp);
2036                         cfclose(ss_fp);
2037                         if ( size <= 0 )        {
2038                                 _unlink(debug_name);
2039                         }
2040                 }
2041         }
2042 #endif
2043
2044         cfclose(fp);
2045         // mprintf(("Done processing chunks\n"));
2046         return 1;
2047 }
2048
2049
2050
2051 //returns the number of this model
2052 int model_load(char *filename, int n_subsystems, model_subsystem *subsystems)
2053 {
2054         int i, num, arc_idx;
2055
2056         if ( !model_initted )
2057                 model_init();
2058
2059 //      int Model_ram = 0;
2060
2061 #ifndef NDEBUG
2062         int ram_before = TotalRam;
2063 #endif
2064
2065         //Assert(strlen(filename) <= 12);
2066
2067         num = -1;
2068
2069         for (i=0; i< MAX_POLYGON_MODELS; i++)   {
2070                 if ( Polygon_models[i] )        {
2071                         if (!stricmp(filename, Polygon_models[i]->filename))            {
2072                                 // Model already loaded; just return.
2073                                 return Polygon_models[i]->id;
2074                         }
2075                 } else if ( num == -1 ) {
2076                         // This is the first empty slot
2077                         num = i;
2078                 }
2079         }
2080
2081         // No empty slot
2082         if ( num == -1 )        {
2083                 Error( LOCATION, "Too many models" );
2084                 return -1;
2085         }       
2086
2087         mprintf(( "Loading model '%s'\n", filename ));
2088
2089         polymodel * pm = (polymodel *)malloc( sizeof(polymodel) );
2090         
2091         Polygon_models[num] = pm;
2092         
2093         memset(pm, 0, sizeof(polymodel));
2094
2095         pm->n_paths = 0;
2096         pm->paths = NULL;
2097
2098         int org_sig = Model_signature;
2099         Model_signature+=MAX_POLYGON_MODELS;
2100         if ( Model_signature < org_sig )        {
2101                 Model_signature = 0;
2102         }
2103         Assert( (Model_signature % MAX_POLYGON_MODELS) == 0 );
2104         pm->id = Model_signature + num;
2105
2106         if (!read_model_file(pm, filename, n_subsystems, subsystems))   {
2107                 return -1;
2108         }
2109
2110 //mprintf(( "Loading model '%s'\n", filename ));
2111 //key_getch();
2112
2113 //=============================
2114 // Find the destroyed replacement models
2115
2116         // Set up the default values
2117         for (i=0; i<pm->n_models; i++ ) {
2118                 pm->submodel[i].my_replacement = -1;    // assume nothing replaces this
2119                 pm->submodel[i].i_replace = -1;         // assume this doesn't replaces anything
2120         }
2121
2122         // Search for models that have destroyed versions
2123         for (i=0; i<pm->n_models; i++ ) {
2124                 int j;
2125                 char destroyed_name[128];
2126
2127                 strcpy( destroyed_name, pm->submodel[i].name );
2128                 strcat( destroyed_name, "-destroyed" );
2129                 for (j=0; j<pm->n_models; j++ ) {
2130                         if ( !stricmp( pm->submodel[j].name, destroyed_name ))  {
2131                                 // mprintf(( "Found destroyed model for '%s'\n", pm->submodel[i].name ));
2132                                 pm->submodel[i].my_replacement = j;
2133                                 pm->submodel[j].i_replace = i;
2134                         }
2135                 }
2136
2137                 // Search for models with live debris
2138                 // This debris comes from a destroyed subsystem when ship is still alive
2139                 char live_debris_name[128];
2140
2141                 strcpy( live_debris_name, "debris-" );
2142                 strcat( live_debris_name, pm->submodel[i].name );
2143
2144
2145                 pm->submodel[i].num_live_debris = 0;
2146                 for (j=0; j<pm->n_models; j++ ) {
2147                         // check if current model name is substring of destroyed
2148                         if ( strstr( pm->submodel[j].name, live_debris_name ))  {
2149                                 mprintf(( "Found live debris model for '%s'\n", pm->submodel[i].name ));
2150                                 Assert(pm->submodel[i].num_live_debris < MAX_LIVE_DEBRIS);
2151                                 pm->submodel[i].live_debris[pm->submodel[i].num_live_debris++] = j;
2152                                 pm->submodel[j].is_live_debris = 1;
2153                         }
2154                 }
2155
2156         }
2157
2158         create_family_tree(pm);
2159 //      dump_object_tree(pm);
2160
2161 //==============================
2162 // Find all the lower detail versions of the hires model
2163         for (i=0; i<pm->n_models; i++ ) {
2164                 int j, l1;
2165                 bsp_info * sm1 = &pm->submodel[i];
2166
2167                 // set all arc types to be default              
2168                 for(arc_idx=0; arc_idx < MAX_ARC_EFFECTS; arc_idx++){
2169                         sm1->arc_type[arc_idx] = MARC_TYPE_NORMAL;
2170                 }
2171
2172                 sm1->num_details = 0;
2173                 l1 = strlen(sm1->name);
2174
2175                 for (j=0; j<pm->num_debris_objects;j++ )        {
2176                         if ( i == pm->debris_objects[j] )       {
2177                                 sm1->is_damaged = 1;
2178                         } 
2179                 }
2180
2181
2182                 for (j=0; j<MAX_MODEL_DETAIL_LEVELS; j++ )      {
2183                         sm1->details[j] = -1;
2184                 }
2185
2186                 for (j=0; j<pm->n_models; j++ ) {
2187                         int k;
2188                         bsp_info * sm2 = &pm->submodel[j];
2189
2190                         if ( i==j ) continue;
2191                         
2192                         // set all arc types to be default              
2193                         for(arc_idx=0; arc_idx < MAX_ARC_EFFECTS; arc_idx++){
2194                                 sm2->arc_type[arc_idx] = MARC_TYPE_NORMAL;
2195                         }
2196
2197                         // if sm2 is a detail of sm1 and sm1 is a high detail, then add it to sm1's list
2198                         if ((int)strlen(sm2->name)!=l1) continue;
2199         
2200                         int ndiff = 0;
2201                         int first_diff = 0;
2202                         for ( k=0; k<l1; k++)   {
2203                                 if (sm1->name[k] != sm2->name[k] )      {
2204                                         if (ndiff==0) first_diff = k;
2205                                         ndiff++;
2206                                 }
2207                         }
2208                         if (ndiff==1)   {               // They only differ by one character!
2209                                 int dl1, dl2;
2210                                 dl1 = tolower(sm1->name[first_diff]) - 'a';
2211                                 dl2 = tolower(sm2->name[first_diff]) - 'a';
2212
2213                                 if ( (dl1<0) || (dl2<0) || (dl1>=MAX_MODEL_DETAIL_LEVELS) || (dl2>=MAX_MODEL_DETAIL_LEVELS) ) continue; // invalid detail levels
2214
2215                                 if ( dl1 == 0 ) {
2216                                         dl2--;  // Start from 1 up...
2217                                         if (dl2 >= sm1->num_details ) sm1->num_details = dl2+1;
2218                                         sm1->details[dl2] = j;
2219                                         //mprintf(( "Submodel '%s' is detail level %d of '%s'\n", sm2->name, dl2, sm1->name ));
2220                                 }
2221                         }
2222                 }
2223
2224                 for (j=0; j<sm1->num_details; j++ )     {
2225                         if ( sm1->details[j] == -1 )    {
2226                                 Warning( LOCATION, "Model '%s' could not find all detail levels for submodel '%s'", pm->filename, sm1->name );
2227                                 sm1->num_details = 0;
2228                         }
2229                 }
2230
2231         }
2232
2233
2234         model_octant_create( pm );
2235
2236         // Find the core_radius... the minimum of 
2237         float rx, ry, rz;
2238         rx = fl_abs( pm->submodel[pm->detail[0]].max.xyz.x - pm->submodel[pm->detail[0]].min.xyz.x );
2239         ry = fl_abs( pm->submodel[pm->detail[0]].max.xyz.y - pm->submodel[pm->detail[0]].min.xyz.y );
2240         rz = fl_abs( pm->submodel[pm->detail[0]].max.xyz.z - pm->submodel[pm->detail[0]].min.xyz.z );
2241
2242         pm->core_radius = min( rx, min(ry, rz) ) / 2.0f;
2243
2244         for (i=0; i<pm->n_view_positions; i++ ) {
2245                 if ( pm->view_positions[i].parent == pm->detail[0] )    {
2246                         float d = vm_vec_mag( &pm->view_positions[i].pnt );
2247
2248                         d += 0.1f;              // Make the eye 1/10th of a meter inside the sphere.
2249
2250                         if ( d > pm->core_radius )      {
2251                                 //mprintf(( "Model %s core radius increased from %.1f to %.1f to fit eye\n", pm->filename, pm->core_radius, d ));
2252                                 pm->core_radius = d;
2253                         }               
2254                 }
2255         }
2256
2257 #ifndef NDEBUG
2258         int ram_after = TotalRam;
2259
2260         pm->ram_used = ram_after - ram_before;
2261         Model_ram += pm->ram_used;
2262         //mprintf(( "Model RAM = %d KB\n", Model_ram ));
2263 #endif
2264
2265         return pm->id;
2266 }
2267
2268 // Get "parent" submodel for live debris submodel
2269 int model_get_parent_submodel_for_live_debris( int model_num, int live_debris_model_num )
2270 {
2271         polymodel *pm = model_get(model_num);
2272
2273         Assert(pm->submodel[live_debris_model_num].is_live_debris == 1);
2274
2275         int mn;
2276         bsp_info *child;
2277
2278         // Start with the high level of detail hull 
2279         // Check all its children until we find the submodel to which the live debris belongs
2280         child = &pm->submodel[pm->detail[0]];
2281         mn = child->first_child;
2282
2283         while (mn > 0) {
2284                 child = &pm->submodel[mn];
2285
2286                 if (child->num_live_debris > 0) {
2287                         // check all live debris submodels for the current child
2288                         for (int idx=0; idx<child->num_live_debris; idx++) {
2289                                 if (child->live_debris[idx] == live_debris_model_num) {
2290                                         return mn;
2291                                 }
2292                         }
2293                         // DKA 5/26/99: can multiple live debris subsystems with each ship
2294                         // NO LONGER TRUE Can only be 1 submodel with live debris
2295                         // Error( LOCATION, "Could not find parent submodel for live debris.  Possible model error");
2296                 }
2297
2298                 // get next child
2299                 mn = child->next_sibling;
2300         }
2301         Error( LOCATION, "Could not find parent submodel for live debris");
2302         return -1;
2303 }
2304
2305
2306 float model_get_radius( int modelnum )
2307 {
2308         polymodel *pm;
2309
2310         pm = model_get(modelnum);
2311
2312         return pm->rad;
2313 }
2314
2315 float model_get_core_radius( int modelnum )
2316 {
2317         polymodel *pm;
2318
2319         pm = model_get(modelnum);
2320
2321         return pm->core_radius;
2322 }
2323
2324 float submodel_get_radius( int modelnum, int submodelnum )
2325 {
2326         polymodel *pm;
2327
2328         pm = model_get(modelnum);
2329
2330         return pm->submodel[submodelnum].rad;
2331 }
2332
2333
2334
2335 polymodel * model_get(int model_num)
2336 {
2337         Assert( model_num > -1 );
2338
2339         int num = model_num % MAX_POLYGON_MODELS;
2340         
2341         Assert( num > -1 );
2342         Assert( num < MAX_POLYGON_MODELS );
2343         Assert( Polygon_models[num]->id == model_num );
2344
2345         return Polygon_models[num];
2346 }
2347
2348
2349 /*
2350 // Finds the 3d bounding box of a model.  If submodel_num is -1,
2351 // then it starts from the root object.   If inc_children is non-zero, 
2352 // then this will recurse and find the bounding box for all children
2353 // also.
2354 void model_find_bound_box_3d(int model_num,int submodel_num, int inc_children, matrix *orient, vector * pos, vector * box )
2355 {
2356         polymodel * pm;
2357         vector to_root_xlat;
2358         matrix to_root_rotate;
2359         int n_steps, steps[16];
2360         int tmp_sobj;
2361         
2362         if ( (model_num < 0) || (model_num >= N_polygon_models) ) return;
2363
2364         pm = &Polygon_models[model_num];
2365
2366         if ( submodel_num < 0 ) submodel_num = pm->detail[0];
2367
2368         // traverse up the model tree to a root object.
2369         // Store this path in n_steps,
2370         n_steps = 0;
2371         tmp_sobj = submodel_num;
2372         while( tmp_sobj > -1 )  {
2373                 steps[n_steps++] = tmp_sobj;
2374                 tmp_sobj = pm->submodel[tmp_sobj].parent;
2375         }
2376         
2377         
2378
2379 //      vm_copy_transpose_matrix(&to_world_rotate, orient );
2380 //      to_world_xlat = *pos;
2381
2382 }
2383 */
2384
2385
2386
2387 // Returns zero is x1,y1,x2,y2 are valid
2388 // returns 1 for invalid model, 2 for point offscreen.
2389 // note that x1,y1,x2,y2 aren't clipped to 2d screen coordinates!
2390 int model_find_2d_bound_min(int model_num,matrix *orient, vector * pos,int *x1, int *y1, int *x2, int *y2 )
2391 {
2392         polymodel * po;
2393         int n_valid_pts;
2394         int i, x,y,min_x, min_y, max_x, max_y;
2395         int rval = 0;
2396
2397         po = model_get(model_num);
2398
2399         g3_start_instance_matrix(pos,orient);
2400         
2401         n_valid_pts = 0;
2402
2403         int hull = po->detail[0];
2404
2405         min_x = min_y = max_x = max_y = 0;
2406
2407         for (i=0; i<8; i++ )    {
2408                 vertex pt;
2409                 ubyte flags;
2410
2411                 flags = g3_rotate_vertex(&pt,&po->submodel[hull].bounding_box[i]);
2412                 if ( !(flags&CC_BEHIND) ) {
2413                         g3_project_vertex(&pt);
2414
2415                         if (!(pt.flags & PF_OVERFLOW)) {
2416                                 x = fl2i(pt.sx);
2417                                 y = fl2i(pt.sy);
2418                                 if ( n_valid_pts == 0 ) {
2419                                         min_x = x;
2420                                         min_y = y;
2421                                         max_x = x;
2422                                         max_y = y;
2423                                 } else {
2424                                         if ( x < min_x ) min_x = x;
2425                                         if ( y < min_y ) min_y = y;
2426
2427                                         if ( x > max_x ) max_x = x;
2428                                         if ( y > max_y ) max_y = y;
2429                                 }
2430                                 n_valid_pts++;
2431                         }
2432                 }
2433         }
2434
2435         if ( n_valid_pts < 8 )  {
2436                 rval = 2;
2437         }
2438
2439         if (x1) *x1 = min_x;
2440         if (y1) *y1 = min_y;
2441
2442         if (x2) *x2 = max_x;
2443         if (y2) *y2 = max_y;
2444
2445         g3_done_instance();
2446
2447         return rval;
2448 }
2449
2450
2451 // Returns zero is x1,y1,x2,y2 are valid
2452 // returns 1 for invalid model, 2 for point offscreen.
2453 // note that x1,y1,x2,y2 aren't clipped to 2d screen coordinates!
2454 int submodel_find_2d_bound_min(int model_num,int submodel, matrix *orient, vector * pos,int *x1, int *y1, int *x2, int *y2 )
2455 {
2456         polymodel * po;
2457         int n_valid_pts;
2458         int i, x,y,min_x, min_y, max_x, max_y;
2459         bsp_info * sm;
2460
2461         po = model_get(model_num);
2462         if ( (submodel < 0) || (submodel >= po->n_models ) ) return 1;
2463         sm = &po->submodel[submodel];
2464         
2465         g3_start_instance_matrix(pos,orient);
2466         
2467         n_valid_pts = 0;
2468
2469         min_x = min_y = max_x = max_y = 0;
2470
2471         for (i=0; i<8; i++ )    {
2472                 vertex pt;
2473                 ubyte flags;
2474
2475                 flags = g3_rotate_vertex(&pt,&sm->bounding_box[i]);
2476                 if ( !(flags&CC_BEHIND) ) {
2477                         g3_project_vertex(&pt);
2478
2479                         if (!(pt.flags & PF_OVERFLOW)) {
2480                                 x = fl2i(pt.sx);
2481                                 y = fl2i(pt.sy);
2482                                 if ( n_valid_pts == 0 ) {
2483                                         min_x = x;
2484                                         min_y = y;
2485                                         max_x = x;
2486                                         max_y = y;
2487                                 } else {
2488                                         if ( x < min_x ) min_x = x;
2489                                         if ( y < min_y ) min_y = y;
2490
2491                                         if ( x > max_x ) max_x = x;
2492                                         if ( y > max_y ) max_y = y;
2493                                 }
2494                                 n_valid_pts++;
2495                         }
2496                 }
2497         }
2498
2499         if ( n_valid_pts == 0 ) {
2500                 return 2;
2501         }
2502
2503         if (x1) *x1 = min_x;
2504         if (y1) *y1 = min_y;
2505
2506         if (x2) *x2 = max_x;
2507         if (y2) *y2 = max_y;
2508
2509         g3_done_instance();
2510
2511         return 0;
2512 }
2513
2514
2515 // Returns zero is x1,y1,x2,y2 are valid
2516 // returns 1 for invalid model, 2 for point offscreen.
2517 // note that x1,y1,x2,y2 aren't clipped to 2d screen coordinates!
2518 int model_find_2d_bound(int model_num,matrix *orient, vector * pos,int *x1, int *y1, int *x2, int *y2 )
2519 {
2520         float t,w,h;
2521         vertex pnt;
2522         ubyte flags;
2523         polymodel * po;
2524
2525         po = model_get(model_num);
2526         float width = po->rad;
2527         float height = po->rad;
2528
2529         flags = g3_rotate_vertex(&pnt,pos);
2530
2531         if ( pnt.flags & CC_BEHIND ) 
2532                 return 2;
2533
2534         if (!(pnt.flags&PF_PROJECTED))
2535                 g3_project_vertex(&pnt);
2536
2537         if (pnt.flags & PF_OVERFLOW)
2538                 return 2;
2539
2540         t = (width * Canv_w2)/pnt.z;
2541         w = t*Matrix_scale.xyz.x;
2542
2543         t = (height*Canv_h2)/pnt.z;
2544         h = t*Matrix_scale.xyz.y;
2545
2546         if (x1) *x1 = fl2i(pnt.sx - w);
2547         if (y1) *y1 = fl2i(pnt.sy - h);
2548
2549         if (x2) *x2 = fl2i(pnt.sx + w);
2550         if (y2) *y2 = fl2i(pnt.sy + h);
2551
2552         return 0;
2553 }
2554
2555 // Returns zero is x1,y1,x2,y2 are valid
2556 // returns 2 for point offscreen.
2557 // note that x1,y1,x2,y2 aren't clipped to 2d screen coordinates!
2558 int subobj_find_2d_bound(float radius ,matrix *orient, vector * pos,int *x1, int *y1, int *x2, int *y2 )
2559 {
2560         float t,w,h;
2561         vertex pnt;
2562         ubyte flags;
2563
2564         float width = radius;
2565         float height = radius;
2566
2567         flags = g3_rotate_vertex(&pnt,pos);
2568
2569         if ( pnt.flags & CC_BEHIND ) 
2570                 return 2;
2571
2572         if (!(pnt.flags&PF_PROJECTED))
2573                 g3_project_vertex(&pnt);
2574
2575         if (pnt.flags & PF_OVERFLOW)
2576                 return 2;
2577
2578         t = (width * Canv_w2)/pnt.z;
2579         w = t*Matrix_scale.xyz.x;
2580
2581         t = (height*Canv_h2)/pnt.z;
2582         h = t*Matrix_scale.xyz.y;
2583
2584         if (x1) *x1 = fl2i(pnt.sx - w);
2585         if (y1) *y1 = fl2i(pnt.sy - h);
2586
2587         if (x2) *x2 = fl2i(pnt.sx + w);
2588         if (y2) *y2 = fl2i(pnt.sy + h);
2589
2590         return 0;
2591 }
2592
2593
2594 // Given a vector that is in sub_model_num's frame of
2595 // reference, and given the object's orient and position,
2596 // return the vector in the model's frame of reference.
2597 void model_find_obj_dir(vector *w_vec, vector *m_vec, object *ship_obj, int sub_model_num)
2598 {
2599         vector tvec, vec;
2600         matrix m;
2601         int mn;
2602
2603         Assert(ship_obj->type == OBJ_SHIP);
2604
2605         polymodel *pm = model_get(Ships[ship_obj->instance].modelnum);
2606         vec = *m_vec;
2607         mn = sub_model_num;
2608
2609         // instance up the tree for this point
2610         while ((mn>-1) && (pm->submodel[mn].parent > -1)) {
2611                 
2612                 vm_angles_2_matrix(&m, &pm->submodel[mn].angs);
2613                 vm_vec_unrotate(&tvec, &vec, &m);
2614                 vec = tvec;
2615
2616                 mn = pm->submodel[mn].parent;
2617         }
2618
2619         // now instance for the entire object
2620         vm_vec_unrotate(w_vec, &vec, &ship_obj->orient);
2621 }
2622
2623
2624 // Given a point (pnt) that is in sub_model_num's frame of
2625 // reference, return the point in in the object's frame of reference
2626 void model_rot_sub_into_obj(vector * outpnt, vector *mpnt,polymodel *pm, int sub_model_num)
2627 {
2628         vector pnt;
2629         vector tpnt;
2630         matrix m;
2631         int mn;
2632
2633         pnt = *mpnt;
2634         mn = sub_model_num;
2635
2636         //instance up the tree for this point
2637         while ((mn>-1) && (pm->submodel[mn].parent > -1) ) {
2638                 
2639                 vm_angles_2_matrix(&m,&pm->submodel[mn].angs );
2640                 vm_transpose_matrix(&m);
2641                 vm_vec_rotate(&tpnt,&pnt,&m);
2642
2643                 vm_vec_add(&pnt,&tpnt,&pm->submodel[mn].offset );
2644
2645                 mn = pm->submodel[mn].parent;
2646         }
2647
2648         //now instance for the entire object
2649         *outpnt = pnt;
2650 }
2651
2652
2653 // Given a rotating submodel, find the ship and world axes or rotatation.
2654 void model_get_rotating_submodel_axis(vector *model_axis, vector *world_axis, int modelnum, int submodel_num, object *obj)
2655 {
2656         polymodel *pm = model_get(modelnum);
2657
2658         bsp_info *sm = &pm->submodel[submodel_num];
2659         Assert(sm->movement_type == MOVEMENT_TYPE_ROT);
2660
2661         if (sm->movement_axis == MOVEMENT_AXIS_X) {
2662                 (void) vm_vec_make(model_axis, 1.0f, 0.0f, 0.0f);
2663         } else if (sm->movement_axis == MOVEMENT_AXIS_Y) {
2664                 (void) vm_vec_make(model_axis, 0.0f, 1.0f, 0.0f);
2665         } else {
2666                 Assert(sm->movement_axis == MOVEMENT_AXIS_Z);
2667                 (void) vm_vec_make(model_axis, 0.0f, 0.0f, 1.0f);
2668         }
2669
2670         model_find_obj_dir(world_axis, model_axis, obj, submodel_num);
2671 }
2672
2673
2674 // Does stepped rotation of a submodel
2675 #ifndef PLAT_UNIX
2676 #pragma warning ( push )
2677 #pragma warning (disable : 4701)
2678 #endif
2679 void submodel_stepped_rotate(model_subsystem *psub, submodel_instance_info *sii)
2680 {
2681         Assert(psub->flags & MSS_FLAG_STEPPED_ROTATE);
2682
2683         if ( psub->subobj_num < 0 ) return;
2684
2685         polymodel *pm = model_get(psub->model_num);
2686         bsp_info *sm = &pm->submodel[psub->subobj_num];
2687
2688         if ( sm->movement_type != MOVEMENT_TYPE_ROT ) return;
2689
2690         // get active rotation time this frame
2691         int end_stamp = timestamp();
2692         float rotation_time = 0.001f * (end_stamp - sii->step_zero_timestamp);
2693         Assert(rotation_time >= 0);
2694
2695         // save last angles
2696         sii->prev_angs = sii->angs;
2697
2698         // float pointer into struct to get angle (either p,b,h)
2699         float *ang_prev = NULL, *ang_next = NULL;
2700         switch( sm->movement_axis ) {
2701         case MOVEMENT_AXIS_X:
2702                 ang_prev = &sii->prev_angs.p;
2703                 ang_next = &sii->angs.p;
2704                 break;
2705
2706         case MOVEMENT_AXIS_Y:   
2707                 ang_prev = &sii->prev_angs.h;
2708                 ang_next = &sii->angs.h;
2709                 break;
2710
2711         case MOVEMENT_AXIS_Z:   
2712                 ang_prev = &sii->prev_angs.b;
2713                 ang_next = &sii->angs.b;
2714                 break;
2715         }
2716         
2717         // angular displacement of one step
2718         float step_size = (PI2 / psub->stepped_rotation->num_steps);
2719
2720         // get time to complete one step, including pause
2721         float step_time = psub->stepped_rotation->t_transit + psub->stepped_rotation->t_pause;
2722
2723         // cur_step is step number relative to zero (0 - num_steps)
2724         // step_offset_time is TIME into current step
2725         float step_offset_time = (float)fmod(rotation_time, step_time);
2726         // subtract off fractional step part, round up  (ie, 1.999999 -> 2)
2727         int cur_step = int( ((rotation_time - step_offset_time) / step_time) + 0.5f);
2728         // mprintf(("cur step %d\n", cur_step));
2729         // Assert(step_offset_time >= 0);
2730
2731         if (cur_step >= psub->stepped_rotation->num_steps) {
2732                 // I don;t know why, but removing this line makes it all good.
2733                 // sii->step_zero_timestamp += int(1000.0f * (psub->stepped_rotation->num_steps * step_time) + 0.5f);
2734
2735                 // reset cur_step (use mod to handle physics/ai pause)
2736                 cur_step = cur_step % psub->stepped_rotation->num_steps;
2737         }
2738
2739         // get base angle
2740         *ang_next = cur_step * step_size;
2741
2742         // determine which phase of rotation we're in
2743         float coast_start_time = psub->stepped_rotation->fraction * psub->stepped_rotation->t_transit;
2744         float decel_start_time = psub->stepped_rotation->t_transit * (1.0f - psub->stepped_rotation->fraction);
2745         float pause_start_time = psub->stepped_rotation->t_transit;
2746
2747         float start_coast_angle = 0.5f * psub->stepped_rotation->max_turn_accel * coast_start_time * coast_start_time;
2748
2749         if (step_offset_time < coast_start_time) {
2750                 // do accel
2751                 float accel_time = step_offset_time;
2752                 *ang_next += 0.5f * psub->stepped_rotation->max_turn_accel * accel_time * accel_time;
2753                 sii->cur_turn_rate = psub->stepped_rotation->max_turn_accel * accel_time;
2754         } else if (step_offset_time < decel_start_time) {
2755                 // do coast
2756                 float coast_time = step_offset_time - coast_start_time;
2757                 *ang_next += start_coast_angle + psub->stepped_rotation->max_turn_rate * coast_time;
2758                 sii->cur_turn_rate = psub->stepped_rotation->max_turn_rate;
2759         } else if (step_offset_time < pause_start_time) {
2760                 // do decel
2761                 float time_to_pause = psub->stepped_rotation->t_transit - step_offset_time;
2762                 *ang_next += (step_size - 0.5f * psub->stepped_rotation->max_turn_accel * time_to_pause * time_to_pause);
2763                 sii->cur_turn_rate = psub->stepped_rotation->max_turn_rate * time_to_pause;
2764         } else {
2765                 // do pause
2766                 *ang_next += step_size;
2767                 sii->cur_turn_rate = 0.0f;
2768         }
2769 }
2770 #ifndef PLAT_UNIX
2771 #pragma warning ( pop )
2772 #endif
2773
2774 // Rotates the angle of a submodel.  Use this so the right unlocked axis
2775 // gets stuffed.
2776 void submodel_rotate(model_subsystem *psub, submodel_instance_info *sii)
2777 {
2778         bsp_info * sm;
2779
2780         if ( psub->subobj_num < 0 ) return;
2781
2782         polymodel *pm = model_get(psub->model_num);
2783         sm = &pm->submodel[psub->subobj_num];
2784
2785         if ( sm->movement_type != MOVEMENT_TYPE_ROT ) return;
2786
2787         // save last angles
2788         sii->prev_angs = sii->angs;
2789
2790         // probably send in a calculated desired turn rate
2791         float diff = sii->desired_turn_rate - sii->cur_turn_rate;
2792
2793         float final_turn_rate;
2794         if (diff > 0) {
2795                 final_turn_rate = sii->cur_turn_rate + sii->turn_accel * flFrametime;
2796                 if (final_turn_rate > sii->desired_turn_rate) {
2797                         final_turn_rate = sii->desired_turn_rate;
2798                 }
2799         } else if (diff < 0) {
2800                 final_turn_rate = sii->cur_turn_rate - sii->turn_accel * flFrametime;
2801                 if (final_turn_rate < sii->desired_turn_rate) {
2802                         final_turn_rate = sii->desired_turn_rate;
2803                 }
2804         } else {
2805                 final_turn_rate = sii->desired_turn_rate;
2806         }
2807
2808         float delta = (sii->cur_turn_rate + final_turn_rate) * 0.5f * flFrametime;
2809         sii->cur_turn_rate = final_turn_rate;
2810
2811
2812         //float delta = psub->turn_rate * flFrametime;
2813
2814         switch( sm->movement_axis )     {
2815         case MOVEMENT_AXIS_X:   
2816                 sii->angs.p += delta;
2817                 if (sii->angs.p > PI2 )
2818                         sii->angs.p -= PI2;
2819                 else if (sii->angs.p < 0.0f )
2820                         sii->angs.p += PI2;
2821                 break;
2822         case MOVEMENT_AXIS_Y:   
2823                 sii->angs.h += delta;
2824                 if (sii->angs.h > PI2 )
2825                         sii->angs.h -= PI2;
2826                 else if (sii->angs.h < 0.0f )
2827                         sii->angs.h += PI2;
2828                 break;
2829         case MOVEMENT_AXIS_Z:   
2830                 sii->angs.b += delta;
2831                 if (sii->angs.b > PI2 )
2832                         sii->angs.b -= PI2;
2833                 else if (sii->angs.b < 0.0f )
2834                         sii->angs.b += PI2;
2835                 break;
2836         }
2837 }
2838
2839
2840 //=========================================================================
2841 // Make a turret's correct orientation matrix.   This should be done when 
2842 // the model is read, but I wasn't sure at what point all the data that I
2843 // needed was read, so I just check a flag and call this routine when
2844 // I determine I need the correct matrix.   In this code, you can't use
2845 // vm_vec_2_matrix or anything, since these turrets could be either 
2846 // right handed or left handed.
2847 void model_make_turrent_matrix(int model_num, model_subsystem * turret )
2848 {
2849         polymodel * pm;
2850         vector fvec, uvec, rvec;
2851
2852         pm = model_get(model_num);
2853         bsp_info * sm = &pm->submodel[turret->turret_gun_sobj];
2854         bsp_info * sm_parent = &pm->submodel[turret->subobj_num];
2855
2856
2857         model_clear_instance(model_num);
2858         model_find_world_dir(&fvec, &turret->turret_norm, model_num, turret->turret_gun_sobj, &vmd_identity_matrix, NULL );
2859
2860         sm_parent->angs.h = -PI/2.0f;
2861         sm->angs.p = -PI/2.0f;
2862         model_find_world_dir(&rvec, &turret->turret_norm, model_num, turret->turret_gun_sobj, &vmd_identity_matrix, NULL );
2863
2864         sm_parent->angs.h = 0.0f;
2865         sm->angs.p = -PI/2.0f;
2866         model_find_world_dir(&uvec, &turret->turret_norm, model_num, turret->turret_gun_sobj, &vmd_identity_matrix, NULL );
2867                                                                         
2868         vm_vec_normalize(&fvec);
2869         vm_vec_normalize(&rvec);
2870         vm_vec_normalize(&uvec);
2871
2872         turret->turret_matrix.v.fvec = fvec;
2873         turret->turret_matrix.v.rvec = rvec;
2874         turret->turret_matrix.v.uvec = uvec;
2875
2876 //      vm_vector_2_matrix(&turret->turret_matrix,&turret->turret_norm,NULL,NULL);
2877
2878         // HACK!! WARNING!!!
2879         // I'm doing nothing to verify that this matrix is orthogonal!!
2880         // In other words, there's no guarantee that the vectors are 90 degrees
2881         // from each other.
2882         // I'm not doing this because I don't know how to do it without ruining
2883         // the handedness of the matrix... however, I'm not too worried about   
2884         // this because I am creating these 3 vectors by making them 90 degrees
2885         // apart, so this should be close enough.  I think this will start 
2886         // causing weird errors when we view from turrets. -John
2887         turret->flags |= MSS_FLAG_TURRET_MATRIX;
2888 }
2889
2890 // Tries to move joints so that the turrent points to the point dst.
2891 // turret1 is the angles of the turret, turret2 is the angles of the gun from turret
2892 //      Returns 1 if rotated gun, 0 if no gun to rotate (rotation handled by AI)
2893 int model_rotate_gun(int model_num, model_subsystem *turret, matrix *orient, angles *turret1, angles *turret2, vector *pos, vector *dst)
2894 {
2895         polymodel * pm;
2896
2897         pm = model_get(model_num);
2898         bsp_info * sm = &pm->submodel[turret->turret_gun_sobj];
2899         bsp_info * sm_parent = &pm->submodel[turret->subobj_num];
2900
2901         // Check for a valid turret
2902         Assert( turret->turret_num_firing_points > 0 );
2903
2904
2905         if ( sm_parent == sm ) {
2906                 return 0;
2907         }
2908
2909         // Build the correct turret matrix if there isn't already one
2910         if ( !(turret->flags & MSS_FLAG_TURRET_MATRIX) )
2911                 model_make_turrent_matrix(model_num, turret );
2912
2913         Assert( turret->flags & MSS_FLAG_TURRET_MATRIX);
2914 //      Assert( sm->movement_axis == MOVEMENT_AXIS_X );                         // Gun must be able to change pitch
2915 //      Assert( sm_parent->movement_axis == MOVEMENT_AXIS_Z );  // Parent must be able to change heading
2916
2917 //======================================================
2918 // DEBUG code to draw the normal out of this gun and a circle
2919 // at the gun point.
2920 #if 0
2921         {
2922                 vector tmp;
2923                 vector tmp1;
2924                 vertex dpnt1, dpnt2;
2925
2926                 model_clear_instance(model_num);
2927                 sm->angs.p = turret2->p;
2928                 sm_parent->angs.h = turret1->h;
2929
2930                 model_find_world_point(&tmp, &vmd_zero_vector, model_num, turret->turret_gun_sobj, orient, pos );
2931                 gr_set_color(255,0,0);
2932                 g3_rotate_vertex( &dpnt1, &tmp );
2933
2934                 gr_set_color(255,0,0);
2935                 g3_draw_sphere(&dpnt1,1.0f);
2936
2937                 vm_vec_copy_scale( &tmp1, &turret->turret_matrix.v.fvec, 10.0f );
2938                 model_find_world_point(&tmp, &tmp1, model_num, turret->turret_gun_sobj, orient, pos );
2939                 g3_rotate_vertex( &dpnt2, &tmp );
2940
2941                 gr_set_color(0,255,0);
2942                 g3_draw_line(&dpnt1,&dpnt2);
2943                 gr_set_color(0,128,0);
2944                 g3_draw_sphere(&dpnt2,0.2f);
2945
2946                 vm_vec_copy_scale( &tmp1, &turret->turret_matrix.v.rvec, 10.0f );
2947                 model_find_world_point(&tmp, &tmp1, model_num, turret->turret_gun_sobj, orient, pos );
2948                 g3_rotate_vertex( &dpnt2, &tmp );
2949
2950                 gr_set_color(0,0,255);
2951                 g3_draw_line(&dpnt1,&dpnt2);
2952
2953                 vm_vec_copy_scale( &tmp1, &turret->turret_matrix.v.uvec, 10.0f );
2954                 model_find_world_point(&tmp, &tmp1, model_num, turret->turret_gun_sobj, orient, pos );
2955                 g3_rotate_vertex( &dpnt2, &tmp );
2956
2957                 gr_set_color(255,0,0);
2958                 g3_draw_line(&dpnt1,&dpnt2);
2959         }
2960 #endif
2961
2962         //------------  
2963         // rotate the dest point into the turret gun normal's frame of
2964         // reference, but not using the turret's angles.
2965         // Call this vector of_dst
2966         vector of_dst;                                                  
2967         matrix world_to_turret_matrix;          // converts world coordinates to turret's FOR
2968         vector world_to_turret_translate;       // converts world coordinates to turret's FOR
2969         vector tempv;
2970
2971         vm_vec_unrotate( &tempv, &sm_parent->offset, orient);
2972         vm_vec_add( &world_to_turret_translate, pos, &tempv );
2973
2974         vm_matrix_x_matrix( &world_to_turret_matrix, orient, &turret->turret_matrix );
2975
2976         vm_vec_sub( &tempv, dst, &world_to_turret_translate );
2977         vm_vec_rotate( &of_dst, &tempv, &world_to_turret_matrix );
2978
2979         vm_vec_normalize(&of_dst);      
2980
2981         //------------  
2982         // Find the heading and pitch that the gun needs to turn to
2983         // by extracting them from the of_dst vector.
2984         // Call this the desired_angles
2985         angles desired_angles;
2986
2987         desired_angles.p = (float)acos(of_dst.xyz.z);
2988         desired_angles.h = PI - atan2_safe(of_dst.xyz.x, of_dst.xyz.y);
2989         desired_angles.b = 0.0f;
2990
2991         //      mprintf(( "Z = %.1f, atan= %.1f\n", of_dst.xyz.z, desired_angles.p ));
2992
2993         //------------  
2994         // Gradually turn the turret towards the desired angles
2995         float step_size = turret->turret_turning_rate * flFrametime;
2996
2997         vm_interp_angle(&turret1->h,desired_angles.h,step_size);
2998         vm_interp_angle(&turret2->p,desired_angles.p,step_size);
2999
3000 //      turret1->h -= step_size*(key_down_timef(KEY_1)-key_down_timef(KEY_2) );
3001 //      turret2->p += step_size*(key_down_timef(KEY_3)-key_down_timef(KEY_4) );
3002
3003         return 1;
3004
3005 }
3006
3007
3008 // Given a point (pnt) that is in sub_model_num's frame of
3009 // reference, and given the object's orient and position, 
3010 // return the point in 3-space in outpnt.
3011 void model_find_world_point(vector * outpnt, vector *mpnt,int model_num,int sub_model_num, matrix * objorient, vector * objpos )
3012 {
3013         vector pnt;
3014         vector tpnt;
3015         matrix m;
3016         int mn;
3017         polymodel *pm = model_get(model_num);
3018
3019         pnt = *mpnt;
3020         mn = sub_model_num;
3021
3022         //instance up the tree for this point
3023         while ((mn>-1) && (pm->submodel[mn].parent > -1) ) {
3024                 
3025                 vm_angles_2_matrix(&m,&pm->submodel[mn].angs );
3026                 vm_vec_unrotate(&tpnt,&pnt,&m);
3027
3028                 vm_vec_add(&pnt,&tpnt,&pm->submodel[mn].offset );
3029
3030                 mn = pm->submodel[mn].parent;
3031         }
3032
3033         //now instance for the entire object
3034         vm_vec_unrotate(outpnt,&pnt,objorient);
3035         vm_vec_add2(outpnt,objpos);
3036 }
3037
3038 // Given a point in the world RF, find the corresponding point in the model RF.
3039 // This is special purpose code, specific for model collision.
3040 // NOTE - this code ASSUMES submodel is 1 level down from hull (detail[0])
3041 //
3042 // out - point in model RF
3043 // world_pt - point in world RF
3044 // pm - polygon model
3045 // submodel_num - submodel in whose RF we're trying to find the corresponding world point
3046 // orient - orient matrix of ship
3047 // pos - pos vector of ship
3048 void world_find_model_point(vector *out, vector *world_pt, polymodel *pm, int submodel_num, matrix *orient, vector *pos)
3049 {
3050         Assert( (pm->submodel[submodel_num].parent == pm->detail[0]) || (pm->submodel[submodel_num].parent == -1) );
3051
3052         vector tempv1, tempv2;
3053         matrix m;
3054
3055         // get into ship RF
3056         vm_vec_sub(&tempv1, world_pt, pos);
3057         vm_vec_rotate(&tempv2, &tempv1, orient);
3058
3059         if (pm->submodel[submodel_num].parent == -1) {
3060                 *out  = tempv2;
3061                 return;
3062         }
3063
3064         // put into submodel RF
3065         vm_vec_sub2(&tempv2, &pm->submodel[submodel_num].offset);
3066         vm_angles_2_matrix(&m, &pm->submodel[submodel_num].angs);
3067         vm_vec_rotate(out, &tempv2, &m);
3068 }
3069
3070 // Verify rotating submodel has corresponding ship subsystem -- info in which to store rotation angle
3071 int rotating_submodel_has_ship_subsys(int submodel, ship *shipp)
3072 {
3073         model_subsystem *psub;
3074         ship_subsys                     *pss;
3075
3076         int found = 0;
3077
3078         // Go through all subsystems and look for submodel
3079         // the subsystems that need it.
3080         for ( pss = GET_FIRST(&shipp->subsys_list); pss != END_OF_LIST(&shipp->subsys_list); pss = GET_NEXT(pss) ) {
3081                 psub = pss->system_info;
3082                 if (psub->subobj_num == submodel) {
3083                         found = 1;
3084                         break;
3085                 }
3086         }
3087         
3088         return found;
3089 }
3090
3091 void model_get_rotating_submodel_list(int *submodel_list, int *num_rotating_submodels, object *objp)
3092 {
3093         Assert(objp->type == OBJ_SHIP);
3094
3095         // Check if not currently rotating - then treat as part of superstructure.
3096         int modelnum = Ships[objp->instance].modelnum;
3097         polymodel *pm = model_get(modelnum);
3098         bsp_info *child_submodel;
3099
3100         *num_rotating_submodels = 0;
3101         child_submodel = &pm->submodel[pm->detail[0]];
3102
3103         int i = child_submodel->first_child;
3104         while ( i>-1 )  {
3105                 child_submodel = &pm->submodel[i];
3106
3107                 // Don't check it or its children if it is destroyed or it is a replacement (non-moving)
3108                 if ( !child_submodel->blown_off && (child_submodel->i_replace == -1) )  {
3109
3110                         // Only look for submodels that rotate
3111                         if (child_submodel->movement_type == MOVEMENT_TYPE_ROT) {
3112
3113                                 // find ship subsys and check submodel rotation is less than max allowed.
3114                                 ship *pship = &Ships[objp->instance];
3115                                 ship_subsys *subsys;
3116
3117                                 for ( subsys = GET_FIRST(&pship->subsys_list); subsys !=END_OF_LIST(&pship->subsys_list); subsys = GET_NEXT(subsys) ) {
3118                                         Assert(subsys->system_info->model_num == modelnum);
3119                                         if (i == subsys->system_info->subobj_num) {
3120                                                 // found the correct subsystem - now check delta rotation angle not too large
3121                                                 float delta_angle = get_submodel_delta_angle(&subsys->submodel_info_1);
3122                                                 if (delta_angle < MAX_SUBMODEL_COLLISION_ROT_ANGLE) {
3123                                                         Assert(*num_rotating_submodels < MAX_ROTATING_SUBMODELS-1);
3124                                                         submodel_list[(*num_rotating_submodels)++] = i;
3125                                                 }
3126                                                 break;
3127                                         }
3128                                 }
3129                         }
3130                 }
3131                 i = child_submodel->next_sibling;
3132         }
3133
3134         // error checking
3135 //#define MODEL_CHECK
3136 #ifdef MODEL_CHECK
3137         ship *pship = &Ships[objp->instance];
3138         for (int idx=0; idx<*num_rotating_submodels; idx++) {
3139                 int valid = rotating_submodel_has_ship_subsys(submodel_list[idx], pship);
3140 //              Assert( valid );
3141                 if ( !valid ) {
3142
3143                         Warning( LOCATION, "Ship %s has rotating submodel [%s] without ship subsystem\n", pship->ship_name, pm->submodel[submodel_list[idx]].name );
3144                         pm->submodel[submodel_list[idx]].movement_type &= ~MOVEMENT_TYPE_ROT;
3145                         *num_rotating_submodels = 0;
3146                 }
3147         }
3148 #endif
3149
3150 }
3151
3152
3153 // Given a direction (pnt) that is in sub_model_num's frame of
3154 // reference, and given the object's orient and position, 
3155 // return the point in 3-space in outpnt.
3156 void model_find_world_dir(vector * out_dir, vector *in_dir,int model_num, int sub_model_num, matrix * objorient, vector * objpos )
3157 {
3158         vector pnt;
3159         vector tpnt;
3160         matrix m;
3161         int mn;
3162         polymodel *pm = model_get(model_num);
3163
3164         pnt = *in_dir;
3165         mn = sub_model_num;
3166
3167         //instance up the tree for this point
3168         while ((mn>-1) && (pm->submodel[mn].parent > -1) ) {
3169                 
3170                 vm_angles_2_matrix(&m,&pm->submodel[mn].angs );
3171                 vm_vec_unrotate(&tpnt,&pnt,&m);
3172                 pnt = tpnt;
3173
3174                 mn = pm->submodel[mn].parent;
3175         }
3176
3177         //now instance for the entire object
3178         vm_vec_unrotate(out_dir,&pnt,objorient);
3179 }
3180
3181
3182
3183 // Clears all the submodel instances stored in a model to their defaults.
3184 void model_clear_instance(int model_num)
3185 {
3186         polymodel * pm;
3187         int i;
3188
3189         pm = model_get(model_num);
3190
3191         // reset textures to original ones
3192         for (i=0; i<pm->n_textures; i++ )       {
3193                 pm->textures[i] = pm->original_textures[i];
3194         }
3195         
3196         for (i=0; i<pm->n_models; i++ ) {
3197                 bsp_info *sm = &pm->submodel[i];
3198                 
3199                 if ( pm->submodel[i].is_damaged )       {
3200                         sm->blown_off = 1;
3201                 } else {
3202                         sm->blown_off = 0;
3203                 }
3204                 sm->angs.p = 0.0f;
3205                 sm->angs.b = 0.0f;
3206                 sm->angs.h = 0.0f;
3207
3208                 // set pointer to other ship subsystem info [turn rate, accel, moment, axis, ...]
3209                 sm->sii = NULL;
3210
3211                 sm->num_arcs = 0;               // Turn off any electric arcing effects
3212         }
3213
3214         for (i=0; i<pm->num_lights; i++ )       {
3215                 pm->lights[i].value = 0.0f;
3216         }
3217
3218         interp_clear_instance();
3219
3220 //      if ( keyd_pressed[KEY_1] ) pm->lights[0].value = 1.0f/255.0f;
3221 //      if ( keyd_pressed[KEY_2] ) pm->lights[1].value = 1.0f/255.0f;
3222 //      if ( keyd_pressed[KEY_3] ) pm->lights[2].value = 1.0f/255.0f;
3223 //      if ( keyd_pressed[KEY_4] ) pm->lights[3].value = 1.0f/255.0f;
3224 //      if ( keyd_pressed[KEY_5] ) pm->lights[4].value = 1.0f/255.0f;
3225 //      if ( keyd_pressed[KEY_6] ) pm->lights[5].value = 1.0f/255.0f;
3226
3227
3228 }
3229
3230 // initialization during ship set
3231 void model_clear_instance_info( submodel_instance_info * sii )
3232 {
3233         sii->blown_off = 0;
3234         sii->angs.p = 0.0f;
3235         sii->angs.b = 0.0f;
3236         sii->angs.h = 0.0f;
3237         sii->prev_angs.p = 0.0f;
3238         sii->prev_angs.b = 0.0f;
3239         sii->prev_angs.h = 0.0f;
3240
3241         sii->cur_turn_rate = 0.0f;
3242         sii->desired_turn_rate = 0.0f;
3243         sii->turn_accel = 0.0f;
3244 }
3245
3246 // initialization during ship set
3247 void model_set_instance_info(submodel_instance_info *sii, float turn_rate, float turn_accel)
3248 {
3249         sii->blown_off = 0;
3250         sii->angs.p = 0.0f;
3251         sii->angs.b = 0.0f;
3252         sii->angs.h = 0.0f;
3253         sii->prev_angs.p = 0.0f;
3254         sii->prev_angs.b = 0.0f;
3255         sii->prev_angs.h = 0.0f;
3256
3257         sii->cur_turn_rate = turn_rate * 0.0f;
3258         sii->desired_turn_rate = turn_rate;
3259         sii->turn_accel = turn_accel;
3260         sii->axis_set = 0;
3261         sii->step_zero_timestamp = timestamp();
3262 }
3263
3264
3265
3266 // Sets the submodel instance data in a submodel (for all detail levels)
3267 void model_set_instance(int model_num, int sub_model_num, submodel_instance_info * sii)
3268 {
3269         int i;
3270         polymodel * pm;
3271
3272         pm = model_get(model_num);
3273
3274         Assert( sub_model_num >= 0 );
3275         Assert( sub_model_num < pm->n_models );
3276
3277         if ( sub_model_num < 0 ) return;
3278         if ( sub_model_num >= pm->n_models ) return;
3279         bsp_info *sm = &pm->submodel[sub_model_num];
3280
3281         // Set the "blown out" flags    
3282         sm->blown_off = sii->blown_off;
3283
3284         if ( sm->blown_off )    {
3285                 if ( sm->my_replacement > -1 )  {
3286                         pm->submodel[sm->my_replacement].blown_off = 0;
3287                         pm->submodel[sm->my_replacement].angs = sii->angs;
3288                         pm->submodel[sm->my_replacement].sii = sii;
3289                 }
3290         } else {
3291                 if ( sm->my_replacement > -1 )  {
3292                         pm->submodel[sm->my_replacement].blown_off = 1;
3293                 }
3294         }
3295
3296         // Set the angles
3297         sm->angs = sii->angs;
3298         sm->sii = sii;
3299
3300         // For all the detail levels of this submodel, set them also.
3301         for (i=0; i<sm->num_details; i++ )      {
3302                 model_set_instance(model_num, sm->details[i], sii );
3303         }
3304 }
3305
3306
3307 // Finds a point on the rotation axis of a submodel, used in collision, generally find rotational velocity
3308 void model_init_submodel_axis_pt(submodel_instance_info *sii, int model_num, int submodel_num)
3309 {
3310         vector axis;
3311         vector *mpoint1, *mpoint2;
3312         vector p1, v1, p2, v2, int1;
3313
3314         polymodel *pm = model_get(model_num);
3315         Assert(pm->submodel[submodel_num].movement_type == MOVEMENT_TYPE_ROT);
3316         Assert(sii);
3317
3318         mpoint1 = NULL;
3319         mpoint2 = NULL;
3320
3321         // find 2 fixed points in submodel RF
3322         // these will be rotated to about the axis an angle of 0 and PI and we'll find the intersection of the
3323         // two lines to find a point on the axis
3324         if (pm->submodel[submodel_num].movement_axis == MOVEMENT_AXIS_X) {
3325                 axis = vmd_x_vector;
3326                 mpoint1 = &vmd_y_vector;
3327                 mpoint2 = &vmd_z_vector;
3328         } else if (pm->submodel[submodel_num].movement_axis == MOVEMENT_AXIS_Y) {
3329                 mpoint1 = &vmd_x_vector;
3330                 axis = vmd_z_vector;            // rotation about y is a change in heading (p,b,h), so we need z
3331                 mpoint2 = &vmd_z_vector;
3332         } else if (pm->submodel[submodel_num].movement_axis == MOVEMENT_AXIS_Z) {
3333                 mpoint1 = &vmd_x_vector;
3334                 mpoint2 = &vmd_y_vector;
3335                 axis = vmd_y_vector;            // rotation about z is a change in bank (p,b,h), so we need y
3336         } else {
3337                 // must be one of these axes or submodel_rot_hit is incorrectly set
3338                 Int3();
3339         }
3340
3341         // copy submodel angs
3342         angles copy_angs = pm->submodel[submodel_num].angs;
3343
3344         // find two points rotated into model RF when angs set to 0
3345         vm_vec_copy_scale((vector*)&pm->submodel[submodel_num].angs, &axis, 0.0f);
3346         model_find_world_point(&p1, mpoint1, model_num, submodel_num, &vmd_identity_matrix, &vmd_zero_vector);
3347         model_find_world_point(&p2, mpoint2, model_num, submodel_num, &vmd_identity_matrix, &vmd_zero_vector);
3348
3349         // find two points rotated into model RF when angs set to PI
3350         vm_vec_copy_scale((vector*)&pm->submodel[submodel_num].angs, &axis, PI);
3351         model_find_world_point(&v1, mpoint1, model_num, submodel_num, &vmd_identity_matrix, &vmd_zero_vector);
3352         model_find_world_point(&v2, mpoint2, model_num, submodel_num, &vmd_identity_matrix, &vmd_zero_vector);
3353
3354         // reset submodel angs
3355         pm->submodel[submodel_num].angs = copy_angs;
3356
3357         // find direction vectors of the two lines
3358         vm_vec_sub2(&v1, &p1);
3359         vm_vec_sub2(&v2, &p2);
3360
3361         // find the intersection of the two lines
3362         float s, t;
3363         fvi_two_lines_in_3space(&p1, &v1, &p2, &v2, &s, &t);
3364
3365         // find the actual intersection points
3366         vm_vec_scale_add(&int1, &p1, &v1, s);
3367
3368         // set flag to init
3369         sii->pt_on_axis = int1;
3370         sii->axis_set = 1;
3371 }
3372
3373
3374 // Adds an electrical arcing effect to a submodel
3375 void model_add_arc(int model_num, int sub_model_num, vector *v1, vector *v2, int arc_type )
3376 {
3377         polymodel * pm;
3378
3379         pm = model_get(model_num);
3380
3381         if ( sub_model_num == -1 )      {
3382                 sub_model_num = pm->detail[0];
3383         }
3384
3385         Assert( sub_model_num >= 0 );
3386         Assert( sub_model_num < pm->n_models );
3387
3388         if ( sub_model_num < 0 ) return;
3389         if ( sub_model_num >= pm->n_models ) return;
3390         bsp_info *sm = &pm->submodel[sub_model_num];
3391
3392         if ( sm->num_arcs < MAX_ARC_EFFECTS )   {
3393                 sm->arc_type[sm->num_arcs] = (ubyte)arc_type;
3394                 sm->arc_pts[sm->num_arcs][0] = *v1;
3395                 sm->arc_pts[sm->num_arcs][1] = *v2;
3396                 sm->num_arcs++;
3397         }
3398 }
3399
3400 // function to return an index into the docking_bays array which matches the criteria passed
3401 // to this function.  dock_type is one of the DOCK_TYPE_XXX defines in model.h
3402 int model_find_dock_index(int modelnum, int dock_type)
3403 {
3404         int i;
3405
3406         polymodel *pm;
3407
3408         pm = model_get(modelnum);
3409
3410         // no docking points -- return -1
3411         if ( pm->n_docks <= 0 )
3412                 return -1;
3413
3414         for (i = 0; i < pm->n_docks; i++ ) {
3415                 if ( dock_type & pm->docking_bays[i].type_flags )
3416                         return i;
3417         }
3418
3419         return -1;
3420 }
3421
3422 int model_get_dock_index_type(int modelnum, int index)
3423 {
3424         polymodel *pm = model_get(modelnum);                            
3425
3426         return pm->docking_bays[index].type_flags;
3427 }
3428
3429 // get all the different docking point types on a model
3430 int model_get_dock_types(int modelnum)
3431 {
3432         int i, type = 0;
3433         polymodel *pm;
3434
3435         pm = model_get(modelnum);
3436         for (i=0; i<pm->n_docks; i++)
3437                 type |= pm->docking_bays[i].type_flags;
3438
3439         return type;
3440 }
3441
3442 // function to return an index into the docking_bays array which matches the string passed
3443 // Fred uses strings to identify docking positions.  This functin also accepts generic strings
3444 // so that a desginer doesn't have to know exact names if building a mission from hand.
3445 int model_find_dock_name_index( int modelnum, char *name )
3446 {
3447         int i;
3448         polymodel *pm;
3449
3450         pm = model_get(modelnum);
3451         if ( pm->n_docks <= 0 )
3452                 return -1;
3453
3454         // check the generic names and call previous function to find first dock point of
3455         // the specified type
3456         if ( !stricmp(name, "cargo") )
3457                 return model_find_dock_index( modelnum, DOCK_TYPE_CARGO );
3458         else if (!stricmp( name, "rearm") )
3459                 return model_find_dock_index( modelnum, DOCK_TYPE_REARM );
3460         else if (!stricmp( name, "generic") )
3461                 return model_find_dock_index( modelnum, DOCK_TYPE_GENERIC );
3462
3463         for (i = 0; i < pm->n_docks; i++ ) {
3464                 if ( !stricmp(pm->docking_bays[i].name, name) )
3465                         return i;
3466         }
3467
3468         // if we get here, name wasn't found -- return -1 and hope for the best
3469         return -1;
3470 }
3471
3472 // returns the actual name of a docking point on a model, needed by Fred.
3473 char *model_get_dock_name(int modelnum, int index)
3474 {
3475         polymodel *pm;
3476
3477         pm = model_get(modelnum);
3478         Assert((index >= 0) && (index < pm->n_docks));
3479         return pm->docking_bays[index].name;
3480 }
3481
3482 int model_get_num_dock_points(int modelnum)
3483 {
3484         polymodel *pm;
3485
3486         pm = model_get(modelnum);
3487         return pm->n_docks;
3488 }
3489
3490 #if SDL_BYTEORDER == SDL_BIG_ENDIAN                     // tigital
3491 void swap_bsp_defpoints(ubyte * p)
3492 {
3493         int n, i;
3494         int nverts = INTEL_INT( w(p+8) );
3495         w(p+8) = nverts;        
3496         int offset = INTEL_INT( w(p+16) );
3497         w(p+16) = offset;
3498         int n_norms = INTEL_INT( w(p+12) );
3499         w(p+12) = n_norms;
3500
3501         ubyte * normcount = p+20;
3502         vector *src = vp(p+offset);
3503
3504         Assert( nverts < MAX_POLYGON_VECS );
3505         // Assert( nnorms < MAX_POLYGON_NORMS );
3506
3507         for (n=0; n<nverts; n++ )       {
3508             src->xyz.x = INTEL_FLOAT( &src->xyz.x );
3509             src->xyz.y = INTEL_FLOAT( &src->xyz.y );
3510             src->xyz.z = INTEL_FLOAT( &src->xyz.z );
3511
3512             Interp_verts[n] = src;
3513             src++;
3514             for (i=0;i<normcount[n];i++){
3515                 src->xyz.x = INTEL_FLOAT( &src->xyz.x );
3516                 src->xyz.y = INTEL_FLOAT( &src->xyz.y );
3517                 src->xyz.z = INTEL_FLOAT( &src->xyz.z );
3518                 src++;
3519             }
3520             
3521         }
3522 }
3523 void swap_bsp_tmappoly( polymodel * pm, ubyte * p )
3524 {
3525         int i, nv;
3526         model_tmap_vert *verts;
3527         vector * normal = vp(p+8);
3528         vector * center = vp(p+20);
3529         float radius = INTEL_FLOAT( &fl(p+32) );
3530         fl(p+32) = radius;
3531         normal->xyz.x = INTEL_FLOAT( &normal->xyz.x );
3532         normal->xyz.y = INTEL_FLOAT( &normal->xyz.y );
3533         normal->xyz.z = INTEL_FLOAT( &normal->xyz.z );
3534         center->xyz.x = INTEL_FLOAT( &center->xyz.x );
3535         center->xyz.y = INTEL_FLOAT( &center->xyz.y );
3536         center->xyz.z = INTEL_FLOAT( &center->xyz.z );
3537
3538         nv = INTEL_INT( w(p+36));
3539         w(p+36) = nv;
3540         int tmap_num = INTEL_INT( w(p+40) );
3541         w(p+40) = tmap_num;
3542         
3543         if ( nv < 0 ) return;
3544
3545         verts = (model_tmap_vert *)(p+44);
3546         for (i=0;i<nv;i++){
3547             verts[i].vertnum = INTEL_SHORT( verts[i].vertnum );
3548             verts[i].normnum = INTEL_SHORT( verts[i].normnum );
3549             verts[i].u = INTEL_FLOAT( &verts[i].u );
3550             verts[i].v = INTEL_FLOAT( &verts[i].v );
3551         }
3552
3553         if ( pm->version < 2003 )       {
3554                 // Set the "normal_point" part of field to be the center of the polygon
3555                 vector center_point;
3556                 vm_vec_zero( &center_point );
3557
3558                 for (i=0;i<nv;i++)      {
3559                         vm_vec_add2( &center_point, Interp_verts[verts[i].vertnum] );
3560                 }
3561
3562                 center_point.xyz.x /= nv;
3563                 center_point.xyz.y /= nv;
3564                 center_point.xyz.z /= nv;
3565
3566                 *vp(p+20) = center_point;
3567
3568                 float rad = 0.0f;
3569
3570                 for (i=0;i<nv;i++)      {
3571                         float dist = vm_vec_dist( &center_point, Interp_verts[verts[i].vertnum] );
3572                         if ( dist > rad )       {
3573                                 rad = dist;
3574                         }
3575                 }
3576                 fl(p+32) = rad;
3577         }
3578 }
3579 void swap_bsp_flatpoly( polymodel * pm, ubyte * p )
3580 {
3581         int i, nv;
3582         short *verts;
3583         vector * normal = vp(p+8);
3584         vector * center = vp(p+20);
3585         float radius = INTEL_FLOAT( &fl(p+32) );
3586         fl(p+32) = radius; 
3587         mprintf(("flatpoly radius = %f\n", radius ));
3588         normal->xyz.x = INTEL_FLOAT( &normal->xyz.x );
3589         normal->xyz.y = INTEL_FLOAT( &normal->xyz.y );
3590         normal->xyz.z = INTEL_FLOAT( &normal->xyz.z );
3591         center->xyz.x = INTEL_FLOAT( &center->xyz.x );
3592         center->xyz.y = INTEL_FLOAT( &center->xyz.y );
3593         center->xyz.z = INTEL_FLOAT( &center->xyz.z );
3594
3595         nv = INTEL_INT( w(p+36));               //tigital
3596         w(p+36) = nv;
3597         
3598         if ( nv < 0 ) return;
3599
3600         verts = (short *)(p+44);
3601         for (i=0; i<nv*2; i++){
3602             verts[i] = INTEL_SHORT( verts[i] );
3603         }
3604
3605         if ( pm->version < 2003 )       {
3606                 // Set the "normal_point" part of field to be the center of the polygon
3607                 vector center_point;
3608                 vm_vec_zero( &center_point );
3609
3610                 for (i=0;i<nv;i++)      {
3611                         vm_vec_add2( &center_point, Interp_verts[verts[i*2]] );
3612                 }
3613
3614                 center_point.xyz.x /= nv;
3615                 center_point.xyz.y /= nv;
3616                 center_point.xyz.z /= nv;
3617
3618                 *vp(p+20) = center_point;
3619
3620                 float rad = 0.0f;
3621
3622                 for (i=0;i<nv;i++)      {
3623                         float dist = vm_vec_dist( &center_point, Interp_verts[verts[i*2]] );
3624                         if ( dist > rad )       {
3625                                 rad = dist;
3626                         }
3627                 }
3628                 fl(p+32) = rad;
3629         }
3630 }
3631 void swap_bsp_sortnorms( polymodel * pm, ubyte * p )
3632 {
3633     int frontlist = INTEL_INT( w(p+36) );
3634     int backlist = INTEL_INT( w(p+40) );
3635     int prelist = INTEL_INT( w(p+44) );
3636     int postlist = INTEL_INT( w(p+48) );
3637     int onlist = INTEL_INT( w(p+52) );
3638     w(p+36) = frontlist;
3639     w(p+40) = backlist;
3640     w(p+44) = prelist;
3641     w(p+48) = postlist;
3642     w(p+52) = onlist;
3643             
3644     vector * normal = vp(p+8);
3645     vector * center = vp(p+20);
3646     int  tmp = INTEL_INT( w(p+32) );
3647     w(p+32) = tmp;
3648     normal->xyz.x = INTEL_FLOAT( &normal->xyz.x );
3649     normal->xyz.y = INTEL_FLOAT( &normal->xyz.y );
3650     normal->xyz.z = INTEL_FLOAT( &normal->xyz.z );
3651     center->xyz.x = INTEL_FLOAT( &center->xyz.x );
3652     center->xyz.y = INTEL_FLOAT( &center->xyz.y );
3653     center->xyz.z = INTEL_FLOAT( &center->xyz.z );
3654     
3655     vector * bmin = vp(p+56);
3656     vector * bmax = vp(p+68);
3657     bmin->xyz.x = INTEL_FLOAT( &bmin->xyz.x );
3658     bmin->xyz.y = INTEL_FLOAT( &bmin->xyz.y );
3659     bmin->xyz.z = INTEL_FLOAT( &bmin->xyz.z );
3660     bmax->xyz.x = INTEL_FLOAT( &bmax->xyz.x );
3661     bmax->xyz.y = INTEL_FLOAT( &bmax->xyz.y );
3662     bmax->xyz.z = INTEL_FLOAT( &bmax->xyz.z );
3663
3664     if (prelist) swap_bsp_data(pm,p+prelist);
3665     if (backlist) swap_bsp_data(pm,p+backlist);
3666     if (onlist) swap_bsp_data(pm,p+onlist);
3667     if (frontlist) swap_bsp_data(pm,p+frontlist);
3668     if (postlist) swap_bsp_data(pm,p+postlist);
3669 }
3670 void swap_bsp_data( polymodel * pm, void *model_ptr )
3671 {
3672     ubyte *p = (ubyte *)model_ptr;
3673     int chunk_type, chunk_size;
3674     vector * min;
3675     vector * max;
3676     
3677     chunk_type = INTEL_INT( w(p) );
3678     chunk_size = INTEL_INT( w(p+4) );
3679     w(p) = chunk_type;
3680     w(p+4) = chunk_size;
3681         
3682     while (chunk_type != OP_EOF)        {
3683
3684         switch (chunk_type) {
3685             case OP_EOF:
3686                     return;
3687             case OP_DEFPOINTS:
3688                     swap_bsp_defpoints(p); 
3689                     break;
3690             case OP_FLATPOLY:
3691                     swap_bsp_flatpoly(pm, p ); break;
3692             case OP_TMAPPOLY:
3693                     swap_bsp_tmappoly(pm, p ); break;
3694             case OP_SORTNORM:
3695                     swap_bsp_sortnorms(pm,p ); break;
3696             case OP_BOUNDBOX:
3697                     min = vp(p+8);
3698                     max = vp(p+20);
3699                     min->xyz.x = INTEL_FLOAT( &min->xyz.x );
3700                     min->xyz.y = INTEL_FLOAT( &min->xyz.y );
3701                     min->xyz.z = INTEL_FLOAT( &min->xyz.z );
3702                     max->xyz.x = INTEL_FLOAT( &max->xyz.x );
3703                     max->xyz.y = INTEL_FLOAT( &max->xyz.y );
3704                     max->xyz.z = INTEL_FLOAT( &max->xyz.z );
3705                     break;
3706         default:
3707             mprintf(( "Bad chunk type %d, len=%d in modelread:swap_bsp_data\n", chunk_type, chunk_size ));
3708             Int3();             // Bad chunk type!
3709             return;
3710         }
3711         p += chunk_size;
3712         chunk_type = INTEL_INT( w(p));
3713         chunk_size = INTEL_INT( w(p+4) );
3714         w(p) = chunk_type;
3715         w(p+4) = chunk_size;
3716     }
3717     return;
3718 }
3719 #endif // SDL_BYTEORDER == SDL_BIG_ENDIAN