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