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