]> icculus.org git repositories - btb/d2x.git/blob - main/gamesave.c
better mouse grab and cursor handling
[btb/d2x.git] / main / gamesave.c
1 /*
2 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
3 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
4 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
5 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
6 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
7 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
8 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
9 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
10 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
11 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
12 */
13
14 /*
15  *
16  * Save game information
17  *
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include <conf.h>
22 #endif
23
24 #include <stdio.h>
25 #include <string.h>
26
27 #include "pstypes.h"
28 #include "strutil.h"
29 #include "mono.h"
30 #include "key.h"
31 #include "gr.h"
32 #include "palette.h"
33 #include "newmenu.h"
34
35 #include "inferno.h"
36 #ifdef EDITOR
37 #include "editor/editor.h"
38 #endif
39 #include "error.h"
40 #include "object.h"
41 #include "game.h"
42 #include "screens.h"
43 #include "wall.h"
44 #include "gamemine.h"
45 #include "robot.h"
46
47
48 #include "cfile.h"
49 #include "bm.h"
50 #include "menu.h"
51 #include "switch.h"
52 #include "fuelcen.h"
53 #include "cntrlcen.h"
54 #include "powerup.h"
55 #include "weapon.h"
56 #include "newdemo.h"
57 #include "gameseq.h"
58 #include "automap.h"
59 #include "polyobj.h"
60 #include "text.h"
61 #include "gamefont.h"
62 #include "gamesave.h"
63 #include "gamepal.h"
64 #include "laser.h"
65 #include "byteswap.h"
66 #include "multi.h"
67 #include "makesig.h"
68
69 char Gamesave_current_filename[PATH_MAX];
70
71 int Gamesave_current_version;
72
73 #define GAME_VERSION            32
74 #define GAME_COMPATIBLE_VERSION 22
75
76 //version 28->29  add delta light support
77 //version 27->28  controlcen id now is reactor number, not model number
78 //version 28->29  ??
79 //version 29->30  changed trigger structure
80 //version 30->31  changed trigger structure some more
81 //version 31->32  change segment structure, make it 512 bytes w/o editor, add Segment2s array.
82
83 #define MENU_CURSOR_X_MIN       MENU_X
84 #define MENU_CURSOR_X_MAX       MENU_X+6
85
86 #ifdef EDITOR
87 struct {
88         ushort  fileinfo_signature;
89         ushort  fileinfo_version;
90         int     fileinfo_sizeof;
91 } game_top_fileinfo;    // Should be same as first two fields below...
92
93 struct {
94         ushort  fileinfo_signature;
95         ushort  fileinfo_version;
96         int     fileinfo_sizeof;
97         char    mine_filename[15];
98         int     level;
99         int     player_offset;              // Player info
100         int     player_sizeof;
101         int     object_offset;              // Object info
102         int     object_howmany;
103         int     object_sizeof;
104         int     walls_offset;
105         int     walls_howmany;
106         int     walls_sizeof;
107         int     doors_offset;
108         int     doors_howmany;
109         int     doors_sizeof;
110         int     triggers_offset;
111         int     triggers_howmany;
112         int     triggers_sizeof;
113         int     links_offset;
114         int     links_howmany;
115         int     links_sizeof;
116         int     control_offset;
117         int     control_howmany;
118         int     control_sizeof;
119         int     matcen_offset;
120         int     matcen_howmany;
121         int     matcen_sizeof;
122         int     dl_indices_offset;
123         int     dl_indices_howmany;
124         int     dl_indices_sizeof;
125         int     delta_light_offset;
126         int     delta_light_howmany;
127         int     delta_light_sizeof;
128 } game_fileinfo;
129 #endif // EDITOR
130
131 //  LINT: adding function prototypes
132 void read_object(object *obj, CFILE *f, int version);
133 #ifdef EDITOR
134 void write_object(object *obj, short version, PHYSFS_file *f);
135 void do_load_save_levels(int save);
136 #endif
137 #ifndef NDEBUG
138 void dump_mine_info(void);
139 #endif
140
141 extern char MaxPowerupsAllowed[MAX_POWERUP_TYPES];
142 extern char PowerupsInMine[MAX_POWERUP_TYPES];
143
144 #ifdef EDITOR
145 extern char mine_filename[];
146 extern int save_mine_data_compiled(PHYSFS_file *SaveFile);
147 //--unused-- #else
148 //--unused-- char mine_filename[128];
149 #endif
150
151 int Gamesave_num_org_robots = 0;
152 //--unused-- grs_bitmap * Gamesave_saved_bitmap = NULL;
153
154 #ifdef EDITOR
155 // Return true if this level has a name of the form "level??"
156 // Note that a pathspec can appear at the beginning of the filename.
157 int is_real_level(char *filename)
158 {
159         int len = strlen(filename);
160
161         if (len < 6)
162                 return 0;
163
164         //mprintf((0, "String = [%s]\n", &filename[len-11]));
165         return !strnicmp(&filename[len-11], "level", 5);
166
167 }
168 #endif
169
170 //--unused-- vms_angvec zero_angles={0,0,0};
171
172 #define vm_angvec_zero(v) do {(v)->p=(v)->b=(v)->h=0;} while (0)
173
174 int Gamesave_num_players=0;
175
176 int N_save_pof_names;
177 char Save_pof_names[MAX_POLYGON_MODELS][FILENAME_LEN];
178
179 void check_and_fix_matrix(vms_matrix *m);
180
181 void verify_object( object * obj )      {
182
183         obj->lifeleft = IMMORTAL_TIME;          //all loaded object are immortal, for now
184
185         if ( obj->type == OBJ_ROBOT )   {
186                 Gamesave_num_org_robots++;
187
188                 // Make sure valid id...
189                 if ( obj->id >= N_robot_types )
190                         obj->id = obj->id % N_robot_types;
191
192                 // Make sure model number & size are correct...
193                 if ( obj->render_type == RT_POLYOBJ ) {
194                         Assert(Robot_info[obj->id].model_num != -1);
195                                 //if you fail this assert, it means that a robot in this level
196                                 //hasn't been loaded, possibly because he's marked as
197                                 //non-shareware.  To see what robot number, print obj->id.
198
199                         Assert(Robot_info[obj->id].always_0xabcd == 0xabcd);
200                                 //if you fail this assert, it means that the robot_ai for
201                                 //a robot in this level hasn't been loaded, possibly because
202                                 //it's marked as non-shareware.  To see what robot number,
203                                 //print obj->id.
204
205                         obj->rtype.pobj_info.model_num = Robot_info[obj->id].model_num;
206                         obj->size = Polygon_models[obj->rtype.pobj_info.model_num].rad;
207
208                         //@@Took out this ugly hack 1/12/96, because Mike has added code
209                         //@@that should fix it in a better way.
210                         //@@//this is a super-ugly hack.  Since the baby stripe robots have
211                         //@@//their firing point on their bounding sphere, the firing points
212                         //@@//can poke through a wall if the robots are very close to it. So
213                         //@@//we make their radii bigger so the guns can't get too close to 
214                         //@@//the walls
215                         //@@if (Robot_info[obj->id].flags & RIF_BIG_RADIUS)
216                         //@@    obj->size = (obj->size*3)/2;
217
218                         //@@if (obj->control_type==CT_AI && Robot_info[obj->id].attack_type)
219                         //@@    obj->size = obj->size*3/4;
220                 }
221
222                 if (obj->id == 65)                                              //special "reactor" robots
223                         obj->movement_type = MT_NONE;
224
225                 if (obj->movement_type == MT_PHYSICS) {
226                         obj->mtype.phys_info.mass = Robot_info[obj->id].mass;
227                         obj->mtype.phys_info.drag = Robot_info[obj->id].drag;
228                 }
229         }
230         else {          //Robots taken care of above
231
232                 if ( obj->render_type == RT_POLYOBJ ) {
233                         int i;
234                         char *name = Save_pof_names[obj->rtype.pobj_info.model_num];
235
236                         for (i=0;i<N_polygon_models;i++)
237                                 if (!stricmp(Pof_names[i],name)) {              //found it!     
238                                         // mprintf((0,"Mapping <%s> to %d (was %d)\n",name,i,obj->rtype.pobj_info.model_num));
239                                         obj->rtype.pobj_info.model_num = i;
240                                         break;
241                                 }
242                 }
243         }
244
245         if ( obj->type == OBJ_POWERUP ) {
246                 if ( obj->id >= N_powerup_types )       {
247                         obj->id = 0;
248                         Assert( obj->render_type != RT_POLYOBJ );
249                 }
250                 obj->control_type = CT_POWERUP;
251                 obj->size = Powerup_info[obj->id].size;
252                 obj->ctype.powerup_info.creation_time = 0;
253
254 #ifdef NETWORK
255                 if (Game_mode & GM_NETWORK)
256                         {
257                           if (multi_powerup_is_4pack(obj->id))
258                                 {
259                                  PowerupsInMine[obj->id-1]+=4;
260                                  MaxPowerupsAllowed[obj->id-1]+=4;
261                                 }
262                           PowerupsInMine[obj->id]++;
263                      MaxPowerupsAllowed[obj->id]++;
264                           mprintf ((0,"PowerupLimiter: ID=%d\n",obj->id));
265                           if (obj->id>MAX_POWERUP_TYPES)
266                                 mprintf ((1,"POWERUP: Overwriting array bounds!! Get JL!\n"));
267                         }
268 #endif
269
270         }
271
272         if ( obj->type == OBJ_WEAPON )  {
273                 if ( obj->id >= N_weapon_types )        {
274                         obj->id = 0;
275                         Assert( obj->render_type != RT_POLYOBJ );
276                 }
277
278                 if (obj->id == PMINE_ID) {              //make sure pmines have correct values
279
280                         obj->mtype.phys_info.mass = Weapon_info[obj->id].mass;
281                         obj->mtype.phys_info.drag = Weapon_info[obj->id].drag;
282                         obj->mtype.phys_info.flags |= PF_FREE_SPINNING;
283
284                         // Make sure model number & size are correct...         
285                         Assert( obj->render_type == RT_POLYOBJ );
286
287                         obj->rtype.pobj_info.model_num = Weapon_info[obj->id].model_num;
288                         obj->size = Polygon_models[obj->rtype.pobj_info.model_num].rad;
289                 }
290         }
291
292         if ( obj->type == OBJ_CNTRLCEN ) {
293
294                 obj->render_type = RT_POLYOBJ;
295                 obj->control_type = CT_CNTRLCEN;
296
297                 if (Gamesave_current_version <= 1) { // descent 1 reactor
298                         obj->id = 0;                         // used to be only one kind of reactor
299                         obj->rtype.pobj_info.model_num = Reactors[0].model_num;// descent 1 reactor
300                 }
301
302                 // Make sure model number is correct...
303                 //obj->rtype.pobj_info.model_num = Reactors[obj->id].model_num;
304         }
305
306         if ( obj->type == OBJ_PLAYER )  {
307                 //int i;
308
309                 //Assert(obj == Player);
310
311                 if ( obj == ConsoleObject )             
312                         init_player_object();
313                 else
314                         if (obj->render_type == RT_POLYOBJ)     //recover from Matt's pof file matchup bug
315                                 obj->rtype.pobj_info.model_num = Player_ship->model_num;
316
317                 //Make sure orient matrix is orthogonal
318                 check_and_fix_matrix(&obj->orient);
319
320                 obj->id = Gamesave_num_players++;
321         }
322
323         if (obj->type == OBJ_HOSTAGE) {
324
325                 //@@if (obj->id > N_hostage_types)
326                 //@@    obj->id = 0;
327
328                 obj->render_type = RT_HOSTAGE;
329                 obj->control_type = CT_POWERUP;
330         }
331
332 }
333
334 //static gs_skip(int len,CFILE *file)
335 //{
336 //
337 //      cfseek(file,len,SEEK_CUR);
338 //}
339
340
341 extern int multi_powerup_is_4pack(int);
342 //reads one object of the given version from the given file
343 void read_object(object *obj,CFILE *f,int version)
344 {
345
346         obj->type           = cfile_read_byte(f);
347         obj->id             = cfile_read_byte(f);
348
349         obj->control_type   = cfile_read_byte(f);
350         obj->movement_type  = cfile_read_byte(f);
351         obj->render_type    = cfile_read_byte(f);
352         obj->flags          = cfile_read_byte(f);
353
354         obj->segnum         = cfile_read_short(f);
355         obj->attached_obj   = -1;
356
357         cfile_read_vector(&obj->pos,f);
358         cfile_read_matrix(&obj->orient,f);
359
360         obj->size           = cfile_read_fix(f);
361         obj->shields        = cfile_read_fix(f);
362
363         cfile_read_vector(&obj->last_pos,f);
364
365         obj->contains_type  = cfile_read_byte(f);
366         obj->contains_id    = cfile_read_byte(f);
367         obj->contains_count = cfile_read_byte(f);
368
369         switch (obj->movement_type) {
370
371                 case MT_PHYSICS:
372
373                         cfile_read_vector(&obj->mtype.phys_info.velocity,f);
374                         cfile_read_vector(&obj->mtype.phys_info.thrust,f);
375
376                         obj->mtype.phys_info.mass               = cfile_read_fix(f);
377                         obj->mtype.phys_info.drag               = cfile_read_fix(f);
378                         obj->mtype.phys_info.brakes     = cfile_read_fix(f);
379
380                         cfile_read_vector(&obj->mtype.phys_info.rotvel,f);
381                         cfile_read_vector(&obj->mtype.phys_info.rotthrust,f);
382
383                         obj->mtype.phys_info.turnroll   = cfile_read_fixang(f);
384                         obj->mtype.phys_info.flags              = cfile_read_short(f);
385
386                         break;
387
388                 case MT_SPINNING:
389
390                         cfile_read_vector(&obj->mtype.spin_rate,f);
391                         break;
392
393                 case MT_NONE:
394                         break;
395
396                 default:
397                         Int3();
398         }
399
400         switch (obj->control_type) {
401
402                 case CT_AI: {
403                         int i;
404
405                         obj->ctype.ai_info.behavior                             = cfile_read_byte(f);
406
407                         for (i=0;i<MAX_AI_FLAGS;i++)
408                                 obj->ctype.ai_info.flags[i]                     = cfile_read_byte(f);
409
410                         obj->ctype.ai_info.hide_segment                 = cfile_read_short(f);
411                         obj->ctype.ai_info.hide_index                   = cfile_read_short(f);
412                         obj->ctype.ai_info.path_length                  = cfile_read_short(f);
413                         obj->ctype.ai_info.cur_path_index               = cfile_read_short(f);
414
415                         if (version <= 25) {
416                                 cfile_read_short(f);    //                              obj->ctype.ai_info.follow_path_start_seg        = 
417                                 cfile_read_short(f);    //                              obj->ctype.ai_info.follow_path_end_seg          = 
418                         }
419
420                         break;
421                 }
422
423                 case CT_EXPLOSION:
424
425                         obj->ctype.expl_info.spawn_time         = cfile_read_fix(f);
426                         obj->ctype.expl_info.delete_time                = cfile_read_fix(f);
427                         obj->ctype.expl_info.delete_objnum      = cfile_read_short(f);
428                         obj->ctype.expl_info.next_attach = obj->ctype.expl_info.prev_attach = obj->ctype.expl_info.attach_parent = -1;
429
430                         break;
431
432                 case CT_WEAPON:
433
434                         //do I really need to read these?  Are they even saved to disk?
435
436                         obj->ctype.laser_info.parent_type               = cfile_read_short(f);
437                         obj->ctype.laser_info.parent_num                = cfile_read_short(f);
438                         obj->ctype.laser_info.parent_signature  = cfile_read_int(f);
439
440                         break;
441
442                 case CT_LIGHT:
443
444                         obj->ctype.light_info.intensity = cfile_read_fix(f);
445                         break;
446
447                 case CT_POWERUP:
448
449                         if (version >= 25)
450                                 obj->ctype.powerup_info.count = cfile_read_int(f);
451                         else
452                                 obj->ctype.powerup_info.count = 1;
453
454                         if (obj->id == POW_VULCAN_WEAPON)
455                                         obj->ctype.powerup_info.count = VULCAN_WEAPON_AMMO_AMOUNT;
456
457                         if (obj->id == POW_GAUSS_WEAPON)
458                                         obj->ctype.powerup_info.count = VULCAN_WEAPON_AMMO_AMOUNT;
459
460                         if (obj->id == POW_OMEGA_WEAPON)
461                                         obj->ctype.powerup_info.count = MAX_OMEGA_CHARGE;
462
463                         break;
464
465
466                 case CT_NONE:
467                 case CT_FLYING:
468                 case CT_DEBRIS:
469                         break;
470
471                 case CT_SLEW:           //the player is generally saved as slew
472                         break;
473
474                 case CT_CNTRLCEN:
475                         break;
476
477                 case CT_MORPH:
478                 case CT_FLYTHROUGH:
479                 case CT_REPAIRCEN:
480                 default:
481                         Int3();
482         
483         }
484
485         switch (obj->render_type) {
486
487                 case RT_NONE:
488                         break;
489
490                 case RT_MORPH:
491                 case RT_POLYOBJ: {
492                         int i,tmo;
493
494                         obj->rtype.pobj_info.model_num          = cfile_read_int(f);
495
496                         for (i=0;i<MAX_SUBMODELS;i++)
497                                 cfile_read_angvec(&obj->rtype.pobj_info.anim_angles[i],f);
498
499                         obj->rtype.pobj_info.subobj_flags       = cfile_read_int(f);
500
501                         tmo = cfile_read_int(f);
502
503                         #ifndef EDITOR
504                         obj->rtype.pobj_info.tmap_override      = tmo;
505                         #else
506                         if (tmo==-1)
507                                 obj->rtype.pobj_info.tmap_override      = -1;
508                         else {
509                                 int xlated_tmo = tmap_xlate_table[tmo];
510                                 if (xlated_tmo < 0)     {
511                                         mprintf( (0, "Couldn't find texture for demo object, model_num = %d\n", obj->rtype.pobj_info.model_num));
512                                         Int3();
513                                         xlated_tmo = 0;
514                                 }
515                                 obj->rtype.pobj_info.tmap_override      = xlated_tmo;
516                         }
517                         #endif
518
519                         obj->rtype.pobj_info.alt_textures       = 0;
520
521                         break;
522                 }
523
524                 case RT_WEAPON_VCLIP:
525                 case RT_HOSTAGE:
526                 case RT_POWERUP:
527                 case RT_FIREBALL:
528
529                         obj->rtype.vclip_info.vclip_num = cfile_read_int(f);
530                         obj->rtype.vclip_info.frametime = cfile_read_fix(f);
531                         obj->rtype.vclip_info.framenum  = cfile_read_byte(f);
532
533                         break;
534
535                 case RT_LASER:
536                         break;
537
538                 default:
539                         Int3();
540
541         }
542
543 }
544
545 #ifdef EDITOR
546
547 //writes one object to the given file
548 void write_object(object *obj, short version, PHYSFS_file *f)
549 {
550         PHYSFSX_writeU8(f, obj->type);
551         PHYSFSX_writeU8(f, obj->id);
552
553         PHYSFSX_writeU8(f, obj->control_type);
554         PHYSFSX_writeU8(f, obj->movement_type);
555         PHYSFSX_writeU8(f, obj->render_type);
556         PHYSFSX_writeU8(f, obj->flags);
557
558         PHYSFS_writeSLE16(f, obj->segnum);
559
560         PHYSFSX_writeVector(f, &obj->pos);
561         PHYSFSX_writeMatrix(f, &obj->orient);
562
563         PHYSFSX_writeFix(f, obj->size);
564         PHYSFSX_writeFix(f, obj->shields);
565
566         PHYSFSX_writeVector(f, &obj->last_pos);
567
568         PHYSFSX_writeU8(f, obj->contains_type);
569         PHYSFSX_writeU8(f, obj->contains_id);
570         PHYSFSX_writeU8(f, obj->contains_count);
571
572         switch (obj->movement_type) {
573
574                 case MT_PHYSICS:
575
576                         PHYSFSX_writeVector(f, &obj->mtype.phys_info.velocity);
577                         PHYSFSX_writeVector(f, &obj->mtype.phys_info.thrust);
578
579                         PHYSFSX_writeFix(f, obj->mtype.phys_info.mass);
580                         PHYSFSX_writeFix(f, obj->mtype.phys_info.drag);
581                         PHYSFSX_writeFix(f, obj->mtype.phys_info.brakes);
582
583                         PHYSFSX_writeVector(f, &obj->mtype.phys_info.rotvel);
584                         PHYSFSX_writeVector(f, &obj->mtype.phys_info.rotthrust);
585
586                         PHYSFSX_writeFixAng(f, obj->mtype.phys_info.turnroll);
587                         PHYSFS_writeSLE16(f, obj->mtype.phys_info.flags);
588
589                         break;
590
591                 case MT_SPINNING:
592
593                         PHYSFSX_writeVector(f, &obj->mtype.spin_rate);
594                         break;
595
596                 case MT_NONE:
597                         break;
598
599                 default:
600                         Int3();
601         }
602
603         switch (obj->control_type) {
604
605                 case CT_AI: {
606                         int i;
607
608                         PHYSFSX_writeU8(f, obj->ctype.ai_info.behavior);
609
610                         for (i = 0; i < MAX_AI_FLAGS; i++)
611                                 PHYSFSX_writeU8(f, obj->ctype.ai_info.flags[i]);
612
613                         PHYSFS_writeSLE16(f, obj->ctype.ai_info.hide_segment);
614                         PHYSFS_writeSLE16(f, obj->ctype.ai_info.hide_index);
615                         PHYSFS_writeSLE16(f, obj->ctype.ai_info.path_length);
616                         PHYSFS_writeSLE16(f, obj->ctype.ai_info.cur_path_index);
617
618                         if (version <= 25)
619                         {
620                                 PHYSFS_writeSLE16(f, -1);       //obj->ctype.ai_info.follow_path_start_seg
621                                 PHYSFS_writeSLE16(f, -1);       //obj->ctype.ai_info.follow_path_end_seg
622                         }
623
624                         break;
625                 }
626
627                 case CT_EXPLOSION:
628
629                         PHYSFSX_writeFix(f, obj->ctype.expl_info.spawn_time);
630                         PHYSFSX_writeFix(f, obj->ctype.expl_info.delete_time);
631                         PHYSFS_writeSLE16(f, obj->ctype.expl_info.delete_objnum);
632
633                         break;
634
635                 case CT_WEAPON:
636
637                         //do I really need to write these objects?
638
639                         PHYSFS_writeSLE16(f, obj->ctype.laser_info.parent_type);
640                         PHYSFS_writeSLE16(f, obj->ctype.laser_info.parent_num);
641                         PHYSFS_writeSLE32(f, obj->ctype.laser_info.parent_signature);
642
643                         break;
644
645                 case CT_LIGHT:
646
647                         PHYSFSX_writeFix(f, obj->ctype.light_info.intensity);
648                         break;
649
650                 case CT_POWERUP:
651
652                         if (version >= 25)
653                                 PHYSFS_writeSLE32(f, obj->ctype.powerup_info.count);
654                         break;
655
656                 case CT_NONE:
657                 case CT_FLYING:
658                 case CT_DEBRIS:
659                         break;
660
661                 case CT_SLEW:           //the player is generally saved as slew
662                         break;
663
664                 case CT_CNTRLCEN:
665                         break;                  //control center object.
666
667                 case CT_MORPH:
668                 case CT_REPAIRCEN:
669                 case CT_FLYTHROUGH:
670                 default:
671                         Int3();
672         
673         }
674
675         switch (obj->render_type) {
676
677                 case RT_NONE:
678                         break;
679
680                 case RT_MORPH:
681                 case RT_POLYOBJ: {
682                         int i;
683
684                         PHYSFS_writeSLE32(f, obj->rtype.pobj_info.model_num);
685
686                         for (i = 0; i < MAX_SUBMODELS; i++)
687                                 PHYSFSX_writeAngleVec(f, &obj->rtype.pobj_info.anim_angles[i]);
688
689                         PHYSFS_writeSLE32(f, obj->rtype.pobj_info.subobj_flags);
690
691                         PHYSFS_writeSLE32(f, obj->rtype.pobj_info.tmap_override);
692
693                         break;
694                 }
695
696                 case RT_WEAPON_VCLIP:
697                 case RT_HOSTAGE:
698                 case RT_POWERUP:
699                 case RT_FIREBALL:
700
701                         PHYSFS_writeSLE32(f, obj->rtype.vclip_info.vclip_num);
702                         PHYSFSX_writeFix(f, obj->rtype.vclip_info.frametime);
703                         PHYSFSX_writeU8(f, obj->rtype.vclip_info.framenum);
704
705                         break;
706
707                 case RT_LASER:
708                         break;
709
710                 default:
711                         Int3();
712
713         }
714
715 }
716 #endif
717
718 extern int remove_trigger_num(int trigger_num);
719
720 // --------------------------------------------------------------------
721 // Load game 
722 // Loads all the relevant data for a level.
723 // If level != -1, it loads the filename with extension changed to .min
724 // Otherwise it loads the appropriate level mine.
725 // returns 0=everything ok, 1=old version, -1=error
726 int load_game_data(CFILE *LoadFile)
727 {
728         int i,j;
729
730         short game_top_fileinfo_version;
731         int object_offset;
732         int gs_num_objects;
733         int num_delta_lights;
734         int trig_size;
735
736         //===================== READ FILE INFO ========================
737
738 #if 0
739         cfread(&game_top_fileinfo, sizeof(game_top_fileinfo), 1, LoadFile);
740 #endif
741
742         // Check signature
743         if (cfile_read_short(LoadFile) != 0x6705)
744                 return -1;
745
746         // Read and check version number
747         game_top_fileinfo_version = cfile_read_short(LoadFile);
748         if (game_top_fileinfo_version < GAME_COMPATIBLE_VERSION )
749                 return -1;
750
751         // We skip some parts of the former game_top_fileinfo
752         cfseek(LoadFile, 31, SEEK_CUR);
753
754         object_offset = cfile_read_int(LoadFile);
755         gs_num_objects = cfile_read_int(LoadFile);
756         cfseek(LoadFile, 8, SEEK_CUR);
757
758         Num_walls = cfile_read_int(LoadFile);
759         cfseek(LoadFile, 20, SEEK_CUR);
760
761         Num_triggers = cfile_read_int(LoadFile);
762         cfseek(LoadFile, 24, SEEK_CUR);
763
764         trig_size = cfile_read_int(LoadFile);
765         Assert(trig_size == sizeof(ControlCenterTriggers));
766         cfseek(LoadFile, 4, SEEK_CUR);
767
768         Num_robot_centers = cfile_read_int(LoadFile);
769         cfseek(LoadFile, 4, SEEK_CUR);
770
771         if (game_top_fileinfo_version >= 29) {
772                 cfseek(LoadFile, 4, SEEK_CUR);
773                 Num_static_lights = cfile_read_int(LoadFile);
774                 cfseek(LoadFile, 8, SEEK_CUR);
775                 num_delta_lights = cfile_read_int(LoadFile);
776                 cfseek(LoadFile, 4, SEEK_CUR);
777         } else {
778                 Num_static_lights = 0;
779                 num_delta_lights = 0;
780         }
781
782         if (game_top_fileinfo_version >= 31) //load mine filename
783                 // read newline-terminated string, not sure what version this changed.
784                 cfgets(Current_level_name,sizeof(Current_level_name),LoadFile);
785         else if (game_top_fileinfo_version >= 14) { //load mine filename
786                 // read null-terminated string
787                 char *p=Current_level_name;
788                 //must do read one char at a time, since no cfgets()
789                 do *p = cfgetc(LoadFile); while (*p++!=0);
790         }
791         else
792                 Current_level_name[0]=0;
793
794         if (game_top_fileinfo_version >= 19) {  //load pof names
795                 N_save_pof_names = cfile_read_short(LoadFile);
796                 if (N_save_pof_names != 0x614d && N_save_pof_names != 0x5547) { // "Ma"de w/DMB beta/"GU"ILE
797                         Assert(N_save_pof_names < MAX_POLYGON_MODELS);
798                         cfread(Save_pof_names,N_save_pof_names,FILENAME_LEN,LoadFile);
799                 }
800         }
801
802         //===================== READ PLAYER INFO ==========================
803         Object_next_signature = 0;
804
805         //===================== READ OBJECT INFO ==========================
806
807         Gamesave_num_org_robots = 0;
808         Gamesave_num_players = 0;
809
810         if (object_offset > -1) {
811                 if (cfseek( LoadFile, object_offset, SEEK_SET ))
812                         Error( "Error seeking to object_offset in gamesave.c" );
813
814                 for (i = 0; i < gs_num_objects; i++) {
815
816                         read_object(&Objects[i], LoadFile, game_top_fileinfo_version);
817
818                         Objects[i].signature = Object_next_signature++;
819                         verify_object( &Objects[i] );
820                 }
821
822         }
823
824         //===================== READ WALL INFO ============================
825
826         for (i = 0; i < Num_walls; i++) {
827                 if (game_top_fileinfo_version >= 20)
828                         wall_read(&Walls[i], LoadFile); // v20 walls and up.
829                 else if (game_top_fileinfo_version >= 17) {
830                         v19_wall w;
831                         v19_wall_read(&w, LoadFile);
832                         Walls[i].segnum         = w.segnum;
833                         Walls[i].sidenum        = w.sidenum;
834                         Walls[i].linked_wall    = w.linked_wall;
835                         Walls[i].type           = w.type;
836                         Walls[i].flags          = w.flags;
837                         Walls[i].hps            = w.hps;
838                         Walls[i].trigger        = w.trigger;
839                         Walls[i].clip_num       = w.clip_num;
840                         Walls[i].keys           = w.keys;
841                         Walls[i].state          = WALL_DOOR_CLOSED;
842                 } else {
843                         v16_wall w;
844                         v16_wall_read(&w, LoadFile);
845                         Walls[i].segnum = Walls[i].sidenum = Walls[i].linked_wall = -1;
846                         Walls[i].type           = w.type;
847                         Walls[i].flags          = w.flags;
848                         Walls[i].hps            = w.hps;
849                         Walls[i].trigger        = w.trigger;
850                         Walls[i].clip_num       = w.clip_num;
851                         Walls[i].keys           = w.keys;
852                 }
853         }
854
855 #if 0
856         //===================== READ DOOR INFO ============================
857
858         if (game_fileinfo.doors_offset > -1)
859         {
860                 if (!cfseek( LoadFile, game_fileinfo.doors_offset,SEEK_SET ))   {
861
862                         for (i=0;i<game_fileinfo.doors_howmany;i++) {
863
864                                 if (game_top_fileinfo_version >= 20)
865                                         active_door_read(&ActiveDoors[i], LoadFile); // version 20 and up
866                                 else {
867                                         v19_door d;
868                                         int p;
869
870                                         v19_door_read(&d, LoadFile);
871
872                                         ActiveDoors[i].n_parts = d.n_parts;
873
874                                         for (p=0;p<d.n_parts;p++) {
875                                                 int cseg,cside;
876
877                                                 cseg = Segments[d.seg[p]].children[d.side[p]];
878                                                 cside = find_connect_side(&Segments[d.seg[p]],&Segments[cseg]);
879
880                                                 ActiveDoors[i].front_wallnum[p] = Segments[d.seg[p]].sides[d.side[p]].wall_num;
881                                                 ActiveDoors[i].back_wallnum[p] = Segments[cseg].sides[cside].wall_num;
882                                         }
883                                 }
884
885                         }
886                 }
887         }
888 #endif // 0
889
890         //==================== READ TRIGGER INFO ==========================
891
892
893 // for MACINTOSH -- assume all triggers >= verion 31 triggers.
894
895         for (i = 0; i < Num_triggers; i++)
896         {
897                 if (game_top_fileinfo_version < 31)
898                 {
899                         v30_trigger trig;
900                         int t,type;
901                         type=0;
902
903                         if (game_top_fileinfo_version < 30) {
904                                 v29_trigger trig29;
905                                 int t;
906                                 v29_trigger_read(&trig29, LoadFile);
907                                 trig.flags      = trig29.flags;
908                                 trig.num_links  = trig29.num_links;
909                                 trig.num_links  = trig29.num_links;
910                                 trig.value      = trig29.value;
911                                 trig.time       = trig29.time;
912
913                                 for (t=0;t<trig.num_links;t++) {
914                                         trig.seg[t]  = trig29.seg[t];
915                                         trig.side[t] = trig29.side[t];
916                                 }
917                         }
918                         else
919                                 v30_trigger_read(&trig, LoadFile);
920
921                         //Assert(trig.flags & TRIGGER_ON);
922                         trig.flags &= ~TRIGGER_ON;
923
924                         if (trig.flags & TRIGGER_CONTROL_DOORS)
925                                 type = TT_OPEN_DOOR;
926                         else if (trig.flags & TRIGGER_SHIELD_DAMAGE)
927                                 Int3();
928                         else if (trig.flags & TRIGGER_ENERGY_DRAIN)
929                                 Int3();
930                         else if (trig.flags & TRIGGER_EXIT)
931                                 type = TT_EXIT;
932                         else if (trig.flags & TRIGGER_ONE_SHOT)
933                                 Int3();
934                         else if (trig.flags & TRIGGER_MATCEN)
935                                 type = TT_MATCEN;
936                         else if (trig.flags & TRIGGER_ILLUSION_OFF)
937                                 type = TT_ILLUSION_OFF;
938                         else if (trig.flags & TRIGGER_SECRET_EXIT)
939                                 type = TT_SECRET_EXIT;
940                         else if (trig.flags & TRIGGER_ILLUSION_ON)
941                                 type = TT_ILLUSION_ON;
942                         else if (trig.flags & TRIGGER_UNLOCK_DOORS)
943                                 type = TT_UNLOCK_DOOR;
944                         else if (trig.flags & TRIGGER_OPEN_WALL)
945                                 type = TT_OPEN_WALL;
946                         else if (trig.flags & TRIGGER_CLOSE_WALL)
947                                 type = TT_CLOSE_WALL;
948                         else if (trig.flags & TRIGGER_ILLUSORY_WALL)
949                                 type = TT_ILLUSORY_WALL;
950                         else
951                                 Int3();
952                         Triggers[i].type        = type;
953                         Triggers[i].flags       = 0;
954                         Triggers[i].num_links   = trig.num_links;
955                         Triggers[i].num_links   = trig.num_links;
956                         Triggers[i].value       = trig.value;
957                         Triggers[i].time        = trig.time;
958                         for (t=0;t<trig.num_links;t++) {
959                                 Triggers[i].seg[t] = trig.seg[t];
960                                 Triggers[i].side[t] = trig.side[t];
961                         }
962                 }
963                 else
964                         trigger_read(&Triggers[i], LoadFile);
965         }
966
967         //================ READ CONTROL CENTER TRIGGER INFO ===============
968
969 #if 0
970         if (game_fileinfo.control_offset > -1)
971                 if (!cfseek(LoadFile, game_fileinfo.control_offset, SEEK_SET))
972                 {
973                         Assert(game_fileinfo.control_sizeof == sizeof(control_center_triggers));
974 #endif // 0
975         control_center_triggers_read_n(&ControlCenterTriggers, 1, LoadFile);
976
977         //================ READ MATERIALOGRIFIZATIONATORS INFO ===============
978
979         // mprintf((0, "Reading %i materialization centers.\n", game_fileinfo.matcen_howmany));
980         for (i = 0; i < Num_robot_centers; i++) {
981                 if (game_top_fileinfo_version < 27) {
982                         old_matcen_info m;
983                         old_matcen_info_read(&m, LoadFile);
984                         RobotCenters[i].robot_flags[0] = m.robot_flags;
985                         RobotCenters[i].robot_flags[1] = 0;
986                         RobotCenters[i].hit_points = m.hit_points;
987                         RobotCenters[i].interval = m.interval;
988                         RobotCenters[i].segnum = m.segnum;
989                         RobotCenters[i].fuelcen_num = m.fuelcen_num;
990                 }
991                 else
992                         matcen_info_read(&RobotCenters[i], LoadFile);
993                         //      Set links in RobotCenters to Station array
994                         for (j = 0; j <= Highest_segment_index; j++)
995                         if (Segment2s[j].special == SEGMENT_IS_ROBOTMAKER)
996                                 if (Segment2s[j].matcen_num == i)
997                                         RobotCenters[i].fuelcen_num = Segment2s[j].value;
998                         // mprintf((0, "   %i: flags = %08x\n", i, RobotCenters[i].robot_flags));
999         }
1000
1001         //================ READ DL_INDICES INFO ===============
1002
1003         for (i = 0; i < Num_static_lights; i++) {
1004                 if (game_top_fileinfo_version < 29) {
1005                         mprintf((0, "Warning: Old mine version.  Not reading Dl_indices info.\n"));
1006                         Int3(); //shouldn't be here!!!
1007                 } else
1008                         dl_index_read(&Dl_indices[i], LoadFile);
1009         }
1010
1011         //      Indicate that no light has been subtracted from any vertices.
1012         clear_light_subtracted();
1013
1014         //================ READ DELTA LIGHT INFO ===============
1015
1016         for (i = 0; i < num_delta_lights; i++) {
1017                 if (game_top_fileinfo_version < 29) {
1018                         mprintf((0, "Warning: Old mine version.  Not reading delta light info.\n"));
1019                 } else
1020                         delta_light_read(&Delta_lights[i], LoadFile);
1021         }
1022
1023         //========================= UPDATE VARIABLES ======================
1024
1025         reset_objects(gs_num_objects);
1026
1027         for (i=0; i<MAX_OBJECTS; i++) {
1028                 Objects[i].next = Objects[i].prev = -1;
1029                 if (Objects[i].type != OBJ_NONE) {
1030                         int objsegnum = Objects[i].segnum;
1031
1032                         if (objsegnum > Highest_segment_index)          //bogus object
1033                                 Objects[i].type = OBJ_NONE;
1034                         else {
1035                                 Objects[i].segnum = -1;                 //avoid Assert()
1036                                 obj_link(i,objsegnum);
1037                         }
1038                 }
1039         }
1040
1041         clear_transient_objects(1);             //1 means clear proximity bombs
1042
1043         // Make sure non-transparent doors are set correctly.
1044         for (i=0; i< Num_segments; i++)
1045                 for (j=0;j<MAX_SIDES_PER_SEGMENT;j++) {
1046                         side    *sidep = &Segments[i].sides[j];
1047                         if ((sidep->wall_num != -1) && (Walls[sidep->wall_num].clip_num != -1)) {
1048                                 //mprintf((0, "Checking Wall %d\n", Segments[i].sides[j].wall_num));
1049                                 if (WallAnims[Walls[sidep->wall_num].clip_num].flags & WCF_TMAP1) {
1050                                         //mprintf((0, "Fixing non-transparent door.\n"));
1051                                         sidep->tmap_num = WallAnims[Walls[sidep->wall_num].clip_num].frames[0];
1052                                         sidep->tmap_num2 = 0;
1053                                 }
1054                         }
1055                 }
1056
1057
1058         reset_walls();
1059
1060 #if 0
1061         Num_open_doors = game_fileinfo.doors_howmany;
1062 #endif // 0
1063         Num_open_doors = 0;
1064
1065         //go through all walls, killing references to invalid triggers
1066         for (i=0;i<Num_walls;i++)
1067                 if (Walls[i].trigger >= Num_triggers) {
1068                         mprintf((0,"Removing reference to invalid trigger %d from wall %d\n",Walls[i].trigger,i));
1069                         Walls[i].trigger = -1;  //kill trigger
1070                 }
1071
1072         //go through all triggers, killing unused ones
1073         for (i=0;i<Num_triggers;) {
1074                 int w;
1075
1076                 //      Find which wall this trigger is connected to.
1077                 for (w=0; w<Num_walls; w++)
1078                         if (Walls[w].trigger == i)
1079                                 break;
1080
1081         #ifdef EDITOR
1082                 if (w == Num_walls) {
1083                         mprintf((0,"Removing unreferenced trigger %d\n",i));
1084                         remove_trigger_num(i);
1085                 }
1086                 else
1087         #endif
1088                         i++;
1089         }
1090
1091         //      MK, 10/17/95: Make walls point back at the triggers that control them.
1092         //      Go through all triggers, stuffing controlling_trigger field in Walls.
1093         {       int t;
1094
1095         for (i=0; i<Num_walls; i++)
1096                 Walls[i].controlling_trigger = -1;
1097
1098         for (t=0; t<Num_triggers; t++) {
1099                 int     l;
1100                 for (l=0; l<Triggers[t].num_links; l++) {
1101                         int     seg_num, side_num, wall_num;
1102
1103                         seg_num = Triggers[t].seg[l];
1104                         side_num = Triggers[t].side[l];
1105                         wall_num = Segments[seg_num].sides[side_num].wall_num;
1106
1107                         // -- if (Walls[wall_num].controlling_trigger != -1)
1108                         // --   Int3();
1109
1110                         //check to see that if a trigger requires a wall that it has one,
1111                         //and if it requires a matcen that it has one
1112
1113                         if (Triggers[t].type == TT_MATCEN) {
1114                                 if (Segment2s[seg_num].special != SEGMENT_IS_ROBOTMAKER)
1115                                         Int3();         //matcen trigger doesn't point to matcen
1116                         }
1117                         else if (Triggers[t].type != TT_LIGHT_OFF && Triggers[t].type != TT_LIGHT_ON) { //light triggers don't require walls
1118                                 if (wall_num == -1)
1119                                         Int3(); //      This is illegal.  This trigger requires a wall
1120                                 else
1121                                         Walls[wall_num].controlling_trigger = t;
1122                         }
1123                 }
1124         }
1125         }
1126
1127         //fix old wall structs
1128         if (game_top_fileinfo_version < 17) {
1129                 int segnum,sidenum,wallnum;
1130
1131                 for (segnum=0; segnum<=Highest_segment_index; segnum++)
1132                         for (sidenum=0;sidenum<6;sidenum++)
1133                                 if ((wallnum=Segments[segnum].sides[sidenum].wall_num) != -1) {
1134                                         Walls[wallnum].segnum = segnum;
1135                                         Walls[wallnum].sidenum = sidenum;
1136                                 }
1137         }
1138
1139         #ifndef NDEBUG
1140         {
1141                 int     sidenum;
1142                 for (sidenum=0; sidenum<6; sidenum++) {
1143                         int     wallnum = Segments[Highest_segment_index].sides[sidenum].wall_num;
1144                         if (wallnum != -1)
1145                                 if ((Walls[wallnum].segnum != Highest_segment_index) || (Walls[wallnum].sidenum != sidenum))
1146                                         Int3(); //      Error.  Bogus walls in this segment.
1147                                                                 // Consult Yuan or Mike.
1148                 }
1149         }
1150         #endif
1151
1152         //create_local_segment_data();
1153
1154         fix_object_segs();
1155
1156         #ifndef NDEBUG
1157         dump_mine_info();
1158         #endif
1159
1160         if (game_top_fileinfo_version < GAME_VERSION
1161             && !(game_top_fileinfo_version == 25 && GAME_VERSION == 26))
1162                 return 1;               //means old version
1163         else
1164                 return 0;
1165 }
1166
1167
1168 int check_segment_connections(void);
1169
1170 extern void     set_ambient_sound_flags(void);
1171
1172 // ----------------------------------------------------------------------------
1173
1174 #define LEVEL_FILE_VERSION      8
1175 //1 -> 2  add palette name
1176 //2 -> 3  add control center explosion time
1177 //3 -> 4  add reactor strength
1178 //4 -> 5  killed hostage text stuff
1179 //5 -> 6  added Secret_return_segment and Secret_return_orient
1180 //6 -> 7  added flickering lights
1181 //7 -> 8  made version 8 to be not compatible with D2 1.0 & 1.1
1182
1183 #ifndef RELEASE
1184 char *Level_being_loaded=NULL;
1185 #endif
1186
1187 #ifdef COMPACT_SEGS
1188 extern void ncache_flush();
1189 #endif
1190
1191 extern int Slide_segs_computed;
1192 extern int d1_pig_present;
1193
1194 int no_old_level_file_error=0;
1195
1196 //loads a level (.LVL) file from disk
1197 //returns 0 if success, else error code
1198 int load_level(char * filename_passed)
1199 {
1200 #ifdef EDITOR
1201         int use_compiled_level=1;
1202 #endif
1203         CFILE * LoadFile;
1204         char filename[PATH_MAX];
1205         int sig, minedata_offset, gamedata_offset;
1206         int mine_err, game_err;
1207 #ifdef NETWORK
1208         int i;
1209 #endif
1210
1211         Slide_segs_computed = 0;
1212
1213 #ifdef NETWORK
1214    if (Game_mode & GM_NETWORK)
1215          {
1216           for (i=0;i<MAX_POWERUP_TYPES;i++)
1217                 {
1218                         MaxPowerupsAllowed[i]=0;
1219                         PowerupsInMine[i]=0;
1220                 }
1221          }
1222 #endif
1223
1224         #ifdef COMPACT_SEGS
1225         ncache_flush();
1226         #endif
1227
1228         #ifndef RELEASE
1229         Level_being_loaded = filename_passed;
1230         #endif
1231
1232         strcpy(filename,filename_passed);
1233
1234         #ifdef EDITOR
1235                 //if we have the editor, try the LVL first, no matter what was passed.
1236                 //if we don't have an LVL, try what was passed or RL2  
1237                 //if we don't have the editor, we just use what was passed
1238         
1239                 change_filename_extension(filename,filename_passed,".lvl");
1240                 use_compiled_level = 0;
1241         
1242                 if (!cfexist(filename))
1243                 {
1244                         char *p = strrchr(filename_passed, '.');
1245
1246                         if (stricmp(p, ".lvl"))
1247                                 strcpy(filename, filename_passed);      // set to what was passed
1248                         else
1249                                 change_filename_extension(filename, filename, ".rl2");
1250                         use_compiled_level = 1;
1251                 }               
1252         #endif
1253
1254         LoadFile = cfopen( filename, "rb" );
1255
1256         if (!LoadFile)  {
1257                 #ifdef EDITOR
1258                         mprintf((0,"Can't open level file <%s>\n", filename));
1259                         return 1;
1260                 #else
1261                         Error("Can't open file <%s>\n",filename);
1262                 #endif
1263         }
1264
1265         strcpy( Gamesave_current_filename, filename );
1266
1267 //      #ifdef NEWDEMO
1268 //      if ( Newdemo_state == ND_STATE_RECORDING )
1269 //              newdemo_record_start_demo();
1270 //      #endif
1271
1272         sig                      = cfile_read_int(LoadFile);
1273         Gamesave_current_version = cfile_read_int(LoadFile);
1274         mprintf((0, "Gamesave_current_version = %d\n", Gamesave_current_version));
1275         minedata_offset          = cfile_read_int(LoadFile);
1276         gamedata_offset          = cfile_read_int(LoadFile);
1277
1278         Assert(sig == MAKE_SIG('P','L','V','L'));
1279
1280         if (Gamesave_current_version >= 8) {    //read dummy data
1281                 cfile_read_int(LoadFile);
1282                 cfile_read_short(LoadFile);
1283                 cfile_read_byte(LoadFile);
1284         }
1285
1286         if (Gamesave_current_version < 5)
1287                 cfile_read_int(LoadFile);       //was hostagetext_offset
1288
1289         if (Gamesave_current_version > 1)
1290                 cfgets(Current_level_palette,sizeof(Current_level_palette),LoadFile);
1291         if (Gamesave_current_version <= 1 || Current_level_palette[0]==0) // descent 1 level
1292                 strcpy(Current_level_palette, DEFAULT_LEVEL_PALETTE);
1293
1294         if (Gamesave_current_version >= 3)
1295                 Base_control_center_explosion_time = cfile_read_int(LoadFile);
1296         else
1297                 Base_control_center_explosion_time = DEFAULT_CONTROL_CENTER_EXPLOSION_TIME;
1298
1299         if (Gamesave_current_version >= 4)
1300                 Reactor_strength = cfile_read_int(LoadFile);
1301         else
1302                 Reactor_strength = -1;  //use old defaults
1303
1304         if (Gamesave_current_version >= 7) {
1305                 int i;
1306
1307                 Num_flickering_lights = cfile_read_int(LoadFile);
1308                 Assert((Num_flickering_lights >= 0) && (Num_flickering_lights < MAX_FLICKERING_LIGHTS));
1309                 for (i = 0; i < Num_flickering_lights; i++)
1310                         flickering_light_read(&Flickering_lights[i], LoadFile);
1311         }
1312         else
1313                 Num_flickering_lights = 0;
1314
1315         if (Gamesave_current_version < 6) {
1316                 Secret_return_segment = 0;
1317                 Secret_return_orient.rvec.x = F1_0;
1318                 Secret_return_orient.rvec.y = 0;
1319                 Secret_return_orient.rvec.z = 0;
1320                 Secret_return_orient.fvec.x = 0;
1321                 Secret_return_orient.fvec.y = F1_0;
1322                 Secret_return_orient.fvec.z = 0;
1323                 Secret_return_orient.uvec.x = 0;
1324                 Secret_return_orient.uvec.y = 0;
1325                 Secret_return_orient.uvec.z = F1_0;
1326         } else {
1327                 Secret_return_segment = cfile_read_int(LoadFile);
1328                 Secret_return_orient.rvec.x = cfile_read_int(LoadFile);
1329                 Secret_return_orient.rvec.y = cfile_read_int(LoadFile);
1330                 Secret_return_orient.rvec.z = cfile_read_int(LoadFile);
1331                 Secret_return_orient.fvec.x = cfile_read_int(LoadFile);
1332                 Secret_return_orient.fvec.y = cfile_read_int(LoadFile);
1333                 Secret_return_orient.fvec.z = cfile_read_int(LoadFile);
1334                 Secret_return_orient.uvec.x = cfile_read_int(LoadFile);
1335                 Secret_return_orient.uvec.y = cfile_read_int(LoadFile);
1336                 Secret_return_orient.uvec.z = cfile_read_int(LoadFile);
1337         }
1338
1339         cfseek(LoadFile,minedata_offset,SEEK_SET);
1340         #ifdef EDITOR
1341         if (!use_compiled_level) {
1342                 mine_err = load_mine_data(LoadFile);
1343 #if 0 // get from d1src if needed
1344                 // Compress all uv coordinates in mine, improves texmap precision. --MK, 02/19/96
1345                 compress_uv_coordinates_all();
1346 #endif
1347         } else
1348         #endif
1349                 //NOTE LINK TO ABOVE!!
1350                 mine_err = load_mine_data_compiled(LoadFile);
1351
1352         if (mine_err == -1) {   //error!!
1353                 cfclose(LoadFile);
1354                 return 2;
1355         }
1356
1357         cfseek(LoadFile,gamedata_offset,SEEK_SET);
1358         game_err = load_game_data(LoadFile);
1359
1360         if (game_err == -1) {   //error!!
1361                 cfclose(LoadFile);
1362                 return 3;
1363         }
1364
1365         //======================== CLOSE FILE =============================
1366
1367         cfclose( LoadFile );
1368
1369         set_ambient_sound_flags();
1370
1371         #if 0   //def EDITOR
1372         write_game_text_file(filename);
1373         if (Errors_in_mine) {
1374                 if (is_real_level(filename)) {
1375                         char  ErrorMessage[200];
1376
1377                         sprintf( ErrorMessage, "Warning: %i errors in %s!\n", Errors_in_mine, Level_being_loaded );
1378                         stop_time();
1379                         gr_palette_load(gr_palette);
1380                         nm_messagebox( NULL, 1, "Continue", ErrorMessage );
1381                         start_time();
1382                 } else
1383                         mprintf((1, "Error: %i errors in %s.\n", Errors_in_mine, Level_being_loaded));
1384         }
1385         #endif
1386
1387         #ifdef EDITOR
1388         //If a Descent 1 level and the Descent 1 pig isn't present, pretend it's a Descent 2 level.
1389         if ((Function_mode == FMODE_EDITOR) && (Gamesave_current_version <= 3) && !d1_pig_present)
1390         {
1391                 if (!no_old_level_file_error)
1392                         Warning("A Descent 1 level was loaded,\n"
1393                                         "and there is no Descent 1 texture\n"
1394                                         "set available. Saving it will\n"
1395                                         "convert it to a Descent 2 level.");
1396
1397                 Gamesave_current_version = LEVEL_FILE_VERSION;
1398         }
1399         #endif
1400
1401         #ifdef EDITOR
1402         if (Function_mode == FMODE_EDITOR)
1403                 editor_status("Loaded NEW mine %s, \"%s\"",filename,Current_level_name);
1404         #endif
1405
1406         #if !defined(NDEBUG) && !defined(COMPACT_SEGS)
1407         if (check_segment_connections())
1408                 nm_messagebox( "ERROR", 1, "Ok", 
1409                                 "Connectivity errors detected in\n"
1410                                 "mine.  See monochrome screen for\n"
1411                                 "details, and contact Matt or Mike." );
1412         #endif
1413
1414         return 0;
1415 }
1416
1417 #ifdef EDITOR
1418 int get_level_name()
1419 {
1420 //NO_UI!!!      UI_WINDOW                               *NameWindow = NULL;
1421 //NO_UI!!!      UI_GADGET_INPUTBOX      *NameText;
1422 //NO_UI!!!      UI_GADGET_BUTTON                *QuitButton;
1423 //NO_UI!!!
1424 //NO_UI!!!      // Open a window with a quit button
1425 //NO_UI!!!      NameWindow = ui_open_window( 20, 20, 300, 110, WIN_DIALOG );
1426 //NO_UI!!!      QuitButton = ui_add_gadget_button( NameWindow, 150-24, 60, 48, 40, "Done", NULL );
1427 //NO_UI!!!
1428 //NO_UI!!!      ui_wprintf_at( NameWindow, 10, 12,"Please enter a name for this mine:" );
1429 //NO_UI!!!      NameText = ui_add_gadget_inputbox( NameWindow, 10, 30, LEVEL_NAME_LEN, LEVEL_NAME_LEN, Current_level_name );
1430 //NO_UI!!!
1431 //NO_UI!!!      NameWindow->keyboard_focus_gadget = (UI_GADGET *)NameText;
1432 //NO_UI!!!      QuitButton->hotkey = KEY_ENTER;
1433 //NO_UI!!!
1434 //NO_UI!!!      ui_gadget_calc_keys(NameWindow);
1435 //NO_UI!!!
1436 //NO_UI!!!      while (!QuitButton->pressed && last_keypress!=KEY_ENTER) {
1437 //NO_UI!!!              ui_mega_process();
1438 //NO_UI!!!              ui_window_do_gadgets(NameWindow);
1439 //NO_UI!!!      }
1440 //NO_UI!!!
1441 //NO_UI!!!      strcpy( Current_level_name, NameText->text );
1442 //NO_UI!!!
1443 //NO_UI!!!      if ( NameWindow!=NULL ) {
1444 //NO_UI!!!              ui_close_window( NameWindow );
1445 //NO_UI!!!              NameWindow = NULL;
1446 //NO_UI!!!      }
1447 //NO_UI!!!
1448
1449         newmenu_item m[2];
1450
1451         m[0].type = NM_TYPE_TEXT; m[0].text = "Please enter a name for this mine:";
1452         m[1].type = NM_TYPE_INPUT; m[1].text = Current_level_name; m[1].text_len = LEVEL_NAME_LEN;
1453
1454         return newmenu_do( NULL, "Enter mine name", 2, m, NULL ) >= 0;
1455
1456 }
1457 #endif
1458
1459
1460 #ifdef EDITOR
1461
1462 int     Errors_in_mine;
1463
1464 // -----------------------------------------------------------------------------
1465 int compute_num_delta_light_records(void)
1466 {
1467         int     i;
1468         int     total = 0;
1469
1470         for (i=0; i<Num_static_lights; i++) {
1471                 total += Dl_indices[i].count;
1472         }
1473
1474         return total;
1475
1476 }
1477
1478 // -----------------------------------------------------------------------------
1479 // Save game
1480 int save_game_data(PHYSFS_file *SaveFile)
1481 {
1482         short game_top_fileinfo_version = Gamesave_current_version >= 5 ? 31 : 25;
1483         int  player_offset, object_offset, walls_offset, doors_offset, triggers_offset, control_offset, matcen_offset; //, links_offset;
1484         int     dl_indices_offset, delta_light_offset;
1485         int offset_offset, end_offset;
1486         int num_delta_lights;
1487         int i;
1488
1489         //===================== SAVE FILE INFO ========================
1490
1491         PHYSFS_writeSLE16(SaveFile, 0x6705);    // signature
1492         PHYSFS_writeSLE16(SaveFile, game_top_fileinfo_version);
1493         PHYSFS_writeSLE32(SaveFile, sizeof(game_fileinfo));
1494         PHYSFS_write(SaveFile, Current_level_name, 15, 1);
1495         PHYSFS_writeSLE32(SaveFile, Current_level_num);
1496         offset_offset = PHYSFS_tell(SaveFile);  // write the offsets later
1497         PHYSFS_writeSLE32(SaveFile, -1);
1498         PHYSFS_writeSLE32(SaveFile, sizeof(player));
1499
1500 #define WRITE_HEADER_ENTRY(t, n) do { PHYSFS_writeSLE32(SaveFile, -1); PHYSFS_writeSLE32(SaveFile, n); PHYSFS_writeSLE32(SaveFile, sizeof(t)); } while(0)
1501
1502         WRITE_HEADER_ENTRY(object, Highest_object_index + 1);
1503         WRITE_HEADER_ENTRY(wall, Num_walls);
1504         WRITE_HEADER_ENTRY(active_door, Num_open_doors);
1505         WRITE_HEADER_ENTRY(trigger, Num_triggers);
1506         WRITE_HEADER_ENTRY(0, 0);               // links (removed by Parallax)
1507         WRITE_HEADER_ENTRY(control_center_triggers, 1);
1508         WRITE_HEADER_ENTRY(matcen_info, Num_robot_centers);
1509
1510         if (game_top_fileinfo_version >= 29)
1511         {
1512                 WRITE_HEADER_ENTRY(dl_index, Num_static_lights);
1513                 WRITE_HEADER_ENTRY(delta_light, num_delta_lights = compute_num_delta_light_records());
1514         }
1515
1516         // Write the mine name
1517         if (game_top_fileinfo_version >= 31)
1518                 PHYSFSX_printf(SaveFile, "%s\n", Current_level_name);
1519         else if (game_top_fileinfo_version >= 14)
1520                 PHYSFSX_writeString(SaveFile, Current_level_name);
1521
1522         if (game_top_fileinfo_version >= 19)
1523         {
1524                 PHYSFS_writeSLE16(SaveFile, N_polygon_models);
1525                 PHYSFS_write(SaveFile, Pof_names, sizeof(*Pof_names), N_polygon_models);
1526         }
1527
1528         //==================== SAVE PLAYER INFO ===========================
1529
1530         player_offset = PHYSFS_tell(SaveFile);
1531         PHYSFS_write(SaveFile, &Players[Player_num], sizeof(player), 1);        // not endian friendly, but not used either
1532
1533         //==================== SAVE OBJECT INFO ===========================
1534
1535         object_offset = PHYSFS_tell(SaveFile);
1536         //fwrite( &Objects, sizeof(object), game_fileinfo.object_howmany, SaveFile );
1537         {
1538                 for (i = 0; i <= Highest_object_index; i++)
1539                         write_object(&Objects[i], game_top_fileinfo_version, SaveFile);
1540         }
1541
1542         //==================== SAVE WALL INFO =============================
1543
1544         walls_offset = PHYSFS_tell(SaveFile);
1545         for (i = 0; i < Num_walls; i++)
1546                 wall_write(&Walls[i], game_top_fileinfo_version, SaveFile);
1547
1548         //==================== SAVE DOOR INFO =============================
1549
1550 #if 0
1551         doors_offset = PHYSFS_tell(SaveFile);
1552         for (i = 0; i < Num_open_doors; i++)
1553                 door_write(&ActiveDoors[i], game_top_fileinfo_version, SaveFile);
1554 #else
1555         doors_offset = 0; // kill warning
1556 #endif
1557
1558         //==================== SAVE TRIGGER INFO =============================
1559
1560         triggers_offset = PHYSFS_tell(SaveFile);
1561         for (i = 0; i < Num_triggers; i++)
1562                 trigger_write(&Triggers[i], game_top_fileinfo_version, SaveFile);
1563
1564         //================ SAVE CONTROL CENTER TRIGGER INFO ===============
1565
1566         control_offset = PHYSFS_tell(SaveFile);
1567         control_center_triggers_write(&ControlCenterTriggers, SaveFile);
1568
1569
1570         //================ SAVE MATERIALIZATION CENTER TRIGGER INFO ===============
1571
1572         matcen_offset = PHYSFS_tell(SaveFile);
1573         // mprintf((0, "Writing %i materialization centers\n", game_fileinfo.matcen_howmany));
1574         // { int i;
1575         // for (i=0; i<game_fileinfo.matcen_howmany; i++)
1576         //      mprintf((0, "   %i: robot_flags = %08x\n", i, RobotCenters[i].robot_flags));
1577         // }
1578         for (i = 0; i < Num_robot_centers; i++)
1579                 matcen_info_write(&RobotCenters[i], game_top_fileinfo_version, SaveFile);
1580
1581         //================ SAVE DELTA LIGHT INFO ===============
1582         if (game_top_fileinfo_version >= 29)
1583         {
1584                 dl_indices_offset = PHYSFS_tell(SaveFile);
1585                 for (i = 0; i < Num_static_lights; i++)
1586                         dl_index_write(&Dl_indices[i], SaveFile);
1587
1588                 delta_light_offset = PHYSFS_tell(SaveFile);
1589                 for (i = 0; i < num_delta_lights; i++)
1590                         delta_light_write(&Delta_lights[i], SaveFile);
1591         }
1592
1593         //============= SAVE OFFSETS ===============
1594
1595         end_offset = PHYSFS_tell(SaveFile);
1596
1597         // Update the offset fields
1598
1599 #define WRITE_OFFSET(o, n) do { PHYSFS_seek(SaveFile, offset_offset); PHYSFS_writeSLE32(SaveFile, o ## _offset); offset_offset += sizeof(int)*n; } while (0)
1600
1601         WRITE_OFFSET(player, 2);
1602         WRITE_OFFSET(object, 3);
1603         WRITE_OFFSET(walls, 3);
1604         WRITE_OFFSET(doors, 3);
1605         WRITE_OFFSET(triggers, 6);
1606         WRITE_OFFSET(control, 3);
1607         WRITE_OFFSET(matcen, 3);
1608         if (game_top_fileinfo_version >= 29)
1609         {
1610                 WRITE_OFFSET(dl_indices, 3);
1611                 WRITE_OFFSET(delta_light, 0);
1612         }
1613
1614         // Go back to end of data
1615         PHYSFS_seek(SaveFile, end_offset);
1616
1617         return 0;
1618 }
1619
1620 int save_mine_data(FILE * SaveFile);
1621
1622 // -----------------------------------------------------------------------------
1623 // Save game
1624 int save_level_sub(char * filename, int compiled_version)
1625 {
1626         PHYSFS_file * SaveFile;
1627         char temp_filename[PATH_MAX];
1628         int minedata_offset=0,gamedata_offset=0;
1629
1630 //      if ( !compiled_version )
1631         {
1632                 write_game_text_file(filename);
1633
1634                 if (Errors_in_mine) {
1635                         if (is_real_level(filename)) {
1636                                 char  ErrorMessage[200];
1637         
1638                                 sprintf( ErrorMessage, "Warning: %i errors in this mine!\n", Errors_in_mine );
1639                                 stop_time();
1640                                 gr_palette_load(gr_palette);
1641          
1642                                 if (nm_messagebox( NULL, 2, "Cancel Save", "Save", ErrorMessage )!=1)   {
1643                                         start_time();
1644                                         return 1;
1645                                 }
1646                                 start_time();
1647                         } else
1648                                 mprintf((1, "Error: %i errors in this mine.  See the 'txm' file.\n", Errors_in_mine));
1649                 }
1650 //              change_filename_extension(temp_filename,filename,".LVL");
1651         }
1652 //      else
1653         {
1654                 if (Gamesave_current_version <= 3)
1655                         change_filename_extension(temp_filename, filename, ".RDL");
1656                 else
1657                         change_filename_extension(temp_filename, filename, ".RL2");
1658         }
1659
1660         SaveFile = PHYSFSX_openWriteBuffered(temp_filename);
1661         if (!SaveFile)
1662         {
1663                 char ErrorMessage[256];
1664
1665                 char fname[20];
1666                 _splitpath( temp_filename, NULL, NULL, fname, NULL );
1667
1668                 sprintf( ErrorMessage, \
1669                         "ERROR: Cannot write to '%s'.\nYou probably need to check out a locked\nversion of the file. You should save\nthis under a different filename, and then\ncheck out a locked copy by typing\n\'co -l %s.lvl'\nat the DOS prompt.\n" 
1670                         , temp_filename, fname );
1671                 stop_time();
1672                 gr_palette_load(gr_palette);
1673                 nm_messagebox( NULL, 1, "Ok", ErrorMessage );
1674                 start_time();
1675                 return 1;
1676         }
1677
1678         if (Current_level_name[0] == 0)
1679                 strcpy(Current_level_name,"Untitled");
1680
1681         clear_transient_objects(1);             //1 means clear proximity bombs
1682
1683         compress_objects();             //after this, Highest_object_index == num objects
1684
1685         //make sure player is in a segment
1686         if (update_object_seg(&Objects[Players[0].objnum]) == 0) {
1687                 if (ConsoleObject->segnum > Highest_segment_index)
1688                         ConsoleObject->segnum = 0;
1689                 compute_segment_center(&ConsoleObject->pos,&(Segments[ConsoleObject->segnum]));
1690         }
1691  
1692         fix_object_segs();
1693
1694         //Write the header
1695
1696         PHYSFS_writeSLE32(SaveFile, MAKE_SIG('P','L','V','L'));
1697         PHYSFS_writeSLE32(SaveFile, Gamesave_current_version);
1698
1699         //save placeholders
1700         PHYSFS_writeSLE32(SaveFile, minedata_offset);
1701         PHYSFS_writeSLE32(SaveFile, gamedata_offset);
1702
1703         //Now write the damn data
1704
1705         if (Gamesave_current_version >= 8)
1706         {
1707                 //write the version 8 data (to make file unreadable by 1.0 & 1.1)
1708                 PHYSFS_writeSLE32(SaveFile, GameTime);
1709                 PHYSFS_writeSLE16(SaveFile, FrameCount);
1710                 PHYSFSX_writeU8(SaveFile, FrameTime);
1711         }
1712
1713         if (Gamesave_current_version < 5)
1714                 PHYSFS_writeSLE32(SaveFile, -1);       //was hostagetext_offset
1715
1716         // Write the palette file name
1717         if (Gamesave_current_version > 1)
1718                 PHYSFSX_printf(SaveFile, "%s\n", Current_level_palette);
1719
1720         if (Gamesave_current_version >= 3)
1721                 PHYSFS_writeSLE32(SaveFile, Base_control_center_explosion_time);
1722         if (Gamesave_current_version >= 4)
1723                 PHYSFS_writeSLE32(SaveFile, Reactor_strength);
1724
1725         if (Gamesave_current_version >= 7)
1726         {
1727                 int i;
1728
1729                 PHYSFS_writeSLE32(SaveFile, Num_flickering_lights);
1730                 for (i = 0; i < Num_flickering_lights; i++)
1731                         flickering_light_write(&Flickering_lights[i], SaveFile);
1732         }
1733
1734         if (Gamesave_current_version >= 6)
1735         {
1736                 PHYSFS_writeSLE32(SaveFile, Secret_return_segment);
1737                 PHYSFSX_writeVector(SaveFile, &Secret_return_orient.rvec);
1738                 PHYSFSX_writeVector(SaveFile, &Secret_return_orient.fvec);
1739                 PHYSFSX_writeVector(SaveFile, &Secret_return_orient.uvec);
1740         }
1741
1742         minedata_offset = PHYSFS_tell(SaveFile);
1743 #if 0   // only save compiled mine data
1744         if ( !compiled_version )        
1745                 save_mine_data(SaveFile);
1746         else
1747 #endif
1748                 save_mine_data_compiled(SaveFile);
1749         gamedata_offset = PHYSFS_tell(SaveFile);
1750         save_game_data(SaveFile);
1751
1752         PHYSFS_seek(SaveFile, sizeof(int) + sizeof(Gamesave_current_version));
1753         PHYSFS_writeSLE32(SaveFile, minedata_offset);
1754         PHYSFS_writeSLE32(SaveFile, gamedata_offset);
1755
1756         if (Gamesave_current_version < 5)
1757                 PHYSFS_writeSLE32(SaveFile, PHYSFS_fileLength(SaveFile));
1758
1759         //==================== CLOSE THE FILE =============================
1760         PHYSFS_close(SaveFile);
1761
1762 //      if ( !compiled_version )
1763         {
1764                 if (Function_mode == FMODE_EDITOR)
1765                         editor_status("Saved mine %s, \"%s\"",filename,Current_level_name);
1766         }
1767
1768         return 0;
1769
1770 }
1771
1772 #if 0 //dunno - 3rd party stuff?
1773 extern void compress_uv_coordinates_all(void);
1774 #endif
1775
1776 int save_level(char * filename)
1777 {
1778         int r1;
1779
1780         // Save normal version...
1781         //save_level_sub(filename, 0);  // just save compiled one
1782
1783         // Save compiled version...
1784         r1 = save_level_sub(filename, 1);
1785
1786         return r1;
1787 }
1788
1789 #endif  //EDITOR
1790
1791 #ifndef NDEBUG
1792 void dump_mine_info(void)
1793 {
1794         int     segnum, sidenum;
1795         fix     min_u, max_u, min_v, max_v, min_l, max_l, max_sl;
1796
1797         min_u = F1_0*1000;
1798         min_v = min_u;
1799         min_l = min_u;
1800
1801         max_u = -min_u;
1802         max_v = max_u;
1803         max_l = max_u;
1804
1805         max_sl = 0;
1806
1807         for (segnum=0; segnum<=Highest_segment_index; segnum++) {
1808                 for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++) {
1809                         int     vertnum;
1810                         side    *sidep = &Segments[segnum].sides[sidenum];
1811
1812                         if (Segment2s[segnum].static_light > max_sl)
1813                                 max_sl = Segment2s[segnum].static_light;
1814
1815                         for (vertnum=0; vertnum<4; vertnum++) {
1816                                 if (sidep->uvls[vertnum].u < min_u)
1817                                         min_u = sidep->uvls[vertnum].u;
1818                                 else if (sidep->uvls[vertnum].u > max_u)
1819                                         max_u = sidep->uvls[vertnum].u;
1820
1821                                 if (sidep->uvls[vertnum].v < min_v)
1822                                         min_v = sidep->uvls[vertnum].v;
1823                                 else if (sidep->uvls[vertnum].v > max_v)
1824                                         max_v = sidep->uvls[vertnum].v;
1825
1826                                 if (sidep->uvls[vertnum].l < min_l)
1827                                         min_l = sidep->uvls[vertnum].l;
1828                                 else if (sidep->uvls[vertnum].l > max_l)
1829                                         max_l = sidep->uvls[vertnum].l;
1830                         }
1831
1832                 }
1833         }
1834
1835 //      mprintf((0, "Smallest uvl = %7.3f %7.3f %7.3f.  Largest uvl = %7.3f %7.3f %7.3f\n", f2fl(min_u), f2fl(min_v), f2fl(min_l), f2fl(max_u), f2fl(max_v), f2fl(max_l)));
1836 //      mprintf((0, "Static light maximum = %7.3f\n", f2fl(max_sl)));
1837 //      mprintf((0, "Number of walls: %i\n", Num_walls));
1838
1839 }
1840
1841 #endif
1842
1843 #ifdef EDITOR
1844
1845 //read in every level in mission and save out compiled version 
1846 void save_all_compiled_levels(void)
1847 {
1848         do_load_save_levels(1);
1849 }
1850
1851 //read in every level in mission
1852 void load_all_levels(void)
1853 {
1854         do_load_save_levels(0);
1855 }
1856
1857
1858 void do_load_save_levels(int save)
1859 {
1860         int level_num;
1861
1862         if (! SafetyCheck())
1863                 return;
1864
1865         no_old_level_file_error=1;
1866
1867         for (level_num=1;level_num<=Last_level;level_num++) {
1868                 load_level(Level_names[level_num-1]);
1869                 load_palette(Current_level_palette,1,1);                //don't change screen
1870                 if (save)
1871                         save_level_sub(Level_names[level_num-1],1);
1872         }
1873
1874         for (level_num=-1;level_num>=Last_secret_level;level_num--) {
1875                 load_level(Secret_level_names[-level_num-1]);
1876                 load_palette(Current_level_palette,1,1);                //don't change screen
1877                 if (save)
1878                         save_level_sub(Secret_level_names[-level_num-1],1);
1879         }
1880
1881         no_old_level_file_error=0;
1882
1883 }
1884
1885 #endif