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