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