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