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