allow the editor to be built with NDEBUG
[btb/d2x.git] / main / render.c
1 /* $Id: render.c,v 1.25 2006-03-05 12:19:42 chris Exp $ */
2 /*
3 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
4 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
5 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
6 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
7 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
8 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
9 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
10 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
11 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
12 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
13 */
14
15 /*
16  *
17  * Rendering Stuff
18  *
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include <conf.h>
23 #endif
24
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <string.h>
28
29 #include "inferno.h"
30 #include "segment.h"
31 #include "error.h"
32 #include "bm.h"
33 #include "texmap.h"
34 #include "mono.h"
35 #include "render.h"
36 #include "game.h"
37 #include "object.h"
38 #include "laser.h"
39 #include "textures.h"
40 #include "screens.h"
41 #include "segpoint.h"
42 #include "wall.h"
43 #include "texmerge.h"
44 #include "physics.h"
45 #include "3d.h"
46 #include "gameseg.h"
47 #include "vclip.h"
48 #include "lighting.h"
49 #include "cntrlcen.h"
50 #include "newdemo.h"
51 #include "automap.h"
52 #include "endlevel.h"
53 #include "key.h"
54 #include "newmenu.h"
55 #include "u_mem.h"
56 #include "piggy.h"
57
58 #ifdef OGL
59 #include "ogl_init.h"
60 #endif
61
62 #define INITIAL_LOCAL_LIGHT (F1_0/4)    // local light value in segment of occurence (of light emission)
63
64 #ifdef EDITOR
65 #include "editor/editor.h"
66 #endif
67
68 //used for checking if points have been rotated
69 int     Clear_window_color=-1;
70 int     Clear_window=2; // 1 = Clear whole background window, 2 = clear view portals into rest of world, 0 = no clear
71
72 int RL_framecount=-1;
73 short Rotated_last[MAX_VERTICES];
74
75 // When any render function needs to know what's looking at it, it should 
76 // access Viewer members.
77 object * Viewer = NULL;
78
79 vms_vector Viewer_eye;  //valid during render
80
81 int     N_render_segs;
82
83 #ifndef MACINTOSH
84 fix Render_zoom = 0x9000;                                       //the player's zoom factor
85 #else
86 fix Render_zoom = 0xB000;
87 #endif
88
89 #ifndef NDEBUG
90 ubyte object_rendered[MAX_OBJECTS];
91 #endif
92
93 #define DEFAULT_RENDER_DEPTH 16
94 int Render_depth=DEFAULT_RENDER_DEPTH;          //how many segments deep to render
95
96 int     Detriangulation_on = 1;                                 // 1 = allow rendering of triangulated side as a quad, 0 = don't allow
97
98 #ifdef EDITOR
99 int     Render_only_bottom=0;
100 int     Bottom_bitmap_num = 9;
101 #endif
102
103 fix     Face_reflectivity = (F1_0/2);
104
105 #if 0           //this stuff could probably just be deleted
106
107 int inc_render_depth(void)
108 {
109         return ++Render_depth;
110 }
111
112 int dec_render_depth(void)
113 {
114         return Render_depth==1?Render_depth:--Render_depth;
115 }
116
117 int reset_render_depth(void)
118 {
119         return Render_depth = DEFAULT_RENDER_DEPTH;
120 }
121
122 #endif
123
124 #ifdef EDITOR
125 int _search_mode = 0;                   //true if looking for curseg,side,face
126 short _search_x,_search_y;      //pixel we're looking at
127 int found_seg,found_side,found_face,found_poly;
128 #else
129 #define _search_mode 0
130 #endif
131
132 #ifdef NDEBUG           //if no debug code, set these vars to constants
133
134 #define Outline_mode 0
135 #define Show_only_curside 0
136
137 #else
138
139 int Outline_mode=0,Show_only_curside=0;
140
141 int toggle_outline_mode(void)
142 {
143         return Outline_mode = !Outline_mode;
144 }
145
146 int toggle_show_only_curside(void)
147 {
148         return Show_only_curside = !Show_only_curside;
149 }
150
151 void draw_outline(int nverts,g3s_point **pointlist)
152 {
153         int i;
154
155         gr_setcolor(BM_XRGB(63,63,63));
156
157         for (i=0;i<nverts-1;i++)
158                 g3_draw_line(pointlist[i],pointlist[i+1]);
159
160         g3_draw_line(pointlist[i],pointlist[0]);
161
162 }
163 #endif
164
165 grs_canvas * reticle_canvas = NULL;
166
167 void free_reticle_canvas()
168 {
169         if (reticle_canvas)     {
170                 d_free( reticle_canvas->cv_bitmap.bm_data );
171                 d_free( reticle_canvas );
172                 reticle_canvas  = NULL;
173         }
174 }
175
176 extern void show_reticle(int force_big);
177
178 // Draw the reticle in 3D for head tracking
179 void draw_3d_reticle(fix eye_offset)
180 {
181         g3s_point       reticle_points[4];
182         g3s_uvl         uvl[4];
183         g3s_point       *pointlist[4];
184         int                     i;
185         vms_vector v1, v2;
186         grs_canvas *saved_canvas;
187         int saved_interp_method;
188
189 //      if (!Use_player_head_angles) return;
190         
191         for (i=0; i<4; i++ )    {
192                 pointlist[i] = &reticle_points[i];
193                 uvl[i].l = MAX_LIGHT;
194         }
195         uvl[0].u = 0; uvl[0].v = 0;
196         uvl[1].u = F1_0; uvl[1].v = 0;
197         uvl[2].u = F1_0; uvl[2].v = F1_0;
198         uvl[3].u = 0; uvl[3].v = F1_0;
199
200         vm_vec_scale_add( &v1, &Viewer->pos, &Viewer->orient.fvec, F1_0*4 );
201         vm_vec_scale_add2(&v1,&Viewer->orient.rvec,eye_offset);
202
203         vm_vec_scale_add( &v2, &v1, &Viewer->orient.rvec, -F1_0*1 );
204         vm_vec_scale_add2( &v2, &Viewer->orient.uvec, F1_0*1 );
205         g3_rotate_point(&reticle_points[0],&v2);
206
207         vm_vec_scale_add( &v2, &v1, &Viewer->orient.rvec, +F1_0*1 );
208         vm_vec_scale_add2( &v2, &Viewer->orient.uvec, F1_0*1 );
209         g3_rotate_point(&reticle_points[1],&v2);
210
211         vm_vec_scale_add( &v2, &v1, &Viewer->orient.rvec, +F1_0*1 );
212         vm_vec_scale_add2( &v2, &Viewer->orient.uvec, -F1_0*1 );
213         g3_rotate_point(&reticle_points[2],&v2);
214
215         vm_vec_scale_add( &v2, &v1, &Viewer->orient.rvec, -F1_0*1 );
216         vm_vec_scale_add2( &v2, &Viewer->orient.uvec, -F1_0*1 );
217         g3_rotate_point(&reticle_points[3],&v2);
218
219         if ( reticle_canvas == NULL )   {
220                 reticle_canvas = gr_create_canvas(64,64);
221                 if ( !reticle_canvas )
222                         Error( "Couldn't malloc reticle_canvas" );
223                 atexit( free_reticle_canvas );
224                 reticle_canvas->cv_bitmap.bm_handle = 0;
225                 reticle_canvas->cv_bitmap.bm_flags = BM_FLAG_TRANSPARENT;
226         }
227
228         saved_canvas = grd_curcanv;
229         gr_set_current_canvas(reticle_canvas);
230         gr_clear_canvas( TRANSPARENCY_COLOR );          // Clear to Xparent
231         show_reticle(1);
232         gr_set_current_canvas(saved_canvas);
233         
234         saved_interp_method=Interpolation_method;
235         Interpolation_method    = 3;            // The best, albiet slowest.
236         g3_draw_tmap(4,pointlist,uvl,&reticle_canvas->cv_bitmap);
237         Interpolation_method    = saved_interp_method;
238 }
239
240
241 extern fix Seismic_tremor_magnitude;
242
243 fix flash_scale;
244
245 #define FLASH_CYCLE_RATE f1_0
246
247 fix Flash_rate = FLASH_CYCLE_RATE;
248
249 //cycle the flashing light for when mine destroyed
250 void flash_frame()
251 {
252         static fixang flash_ang=0;
253
254         if (!Control_center_destroyed && !Seismic_tremor_magnitude)
255                 return;
256
257         if (Endlevel_sequence)
258                 return;
259
260         if (PaletteBlueAdd > 10 )               //whiting out
261                 return;
262
263 //      flash_ang += fixmul(FLASH_CYCLE_RATE,FrameTime);
264         if (Seismic_tremor_magnitude) {
265                 fix     added_flash;
266
267                 added_flash = abs(Seismic_tremor_magnitude);
268                 if (added_flash < F1_0)
269                         added_flash *= 16;
270
271                 flash_ang += fixmul(Flash_rate, fixmul(FrameTime, added_flash+F1_0));
272                 fix_fastsincos(flash_ang,&flash_scale,NULL);
273                 flash_scale = (flash_scale + F1_0*3)/4; //      gets in range 0.5 to 1.0
274         } else {
275                 flash_ang += fixmul(Flash_rate,FrameTime);
276                 fix_fastsincos(flash_ang,&flash_scale,NULL);
277                 flash_scale = (flash_scale + f1_0)/2;
278                 if (Difficulty_level == 0)
279                         flash_scale = (flash_scale+F1_0*3)/4;
280         }
281
282
283 }
284
285 // ----------------------------------------------------------------------------
286 //      Render a face.
287 //      It would be nice to not have to pass in segnum and sidenum, but
288 //      they are used for our hideously hacked in headlight system.
289 //      vp is a pointer to vertex ids.
290 //      tmap1, tmap2 are texture map ids.  tmap2 is the pasty one.
291 void render_face(int segnum, int sidenum, int nv, short *vp, int tmap1, int tmap2, uvl *uvlp, int wid_flags)
292 {
293         // -- Using new headlight system...fix                  face_light;
294         grs_bitmap  *bm;
295 #ifdef OGL
296         grs_bitmap  *bm2 = NULL;
297 #endif
298
299         fix                     reflect;
300         uvl                     uvl_copy[8];
301         int                     i;
302         g3s_point       *pointlist[8];
303
304         Assert(nv <= 8);
305
306         for (i=0; i<nv; i++) {
307                 uvl_copy[i] = uvlp[i];
308                 pointlist[i] = &Segment_points[vp[i]];
309         }
310
311         //handle cloaked walls
312         if (wid_flags & WID_CLOAKED_FLAG) {
313                 int wall_num = Segments[segnum].sides[sidenum].wall_num;
314                 Assert(wall_num != -1);
315                 Gr_scanline_darkening_level = Walls[wall_num].cloak_value;
316                 gr_setcolor(BM_XRGB(0, 0, 0));  // set to black (matters for s3)
317
318                 g3_draw_poly(nv, pointlist);    // draw as flat poly
319
320                 Gr_scanline_darkening_level = GR_FADE_LEVELS;
321
322                 return;
323         }
324
325         // -- Using new headlight system...face_light = -vm_vec_dot(&Viewer->orient.fvec,norm);
326
327         if (tmap1 >= NumTextures) {
328                 mprintf((0,"Invalid tmap number %d, NumTextures=%d, changing to 0\n",tmap1,NumTextures));
329
330         #ifndef RELEASE
331                 Int3();
332         #endif
333
334                 Segments[segnum].sides[sidenum].tmap_num = 0;
335         }
336
337 #ifdef OGL
338         if (ogl_alttexmerge){
339                 PIGGY_PAGE_IN(Textures[tmap1]);
340                 bm = &GameBitmaps[Textures[tmap1].index];
341                 if (tmap2){
342                         PIGGY_PAGE_IN(Textures[tmap2&0x3FFF]);
343                         bm2 = &GameBitmaps[Textures[tmap2&0x3FFF].index];
344                 }
345                 if (!OGL_SUPER_TRANSPARENT_OK && bm2 && (bm2->bm_flags & BM_FLAG_SUPER_TRANSPARENT))
346                 {
347                         bm = texmerge_get_cached_bitmap( tmap1, tmap2 );
348                         bm2 = NULL;
349                 }
350         } else
351 #endif
352
353                 // New code for overlapping textures...
354                 if (tmap2 != 0) {
355                         bm = texmerge_get_cached_bitmap( tmap1, tmap2 );
356                 } else {
357                         bm = &GameBitmaps[Textures[tmap1].index];
358                         PIGGY_PAGE_IN(Textures[tmap1]);
359                 }
360
361         Assert( !(bm->bm_flags & BM_FLAG_PAGED_OUT) );
362
363         //reflect = fl2f((1.0-TmapInfo[p->tmap_num].reflect)/2.0 + 0.5);
364         //reflect = fl2f((1.0-TmapInfo[p->tmap_num].reflect));
365
366         reflect = Face_reflectivity;            // f1_0;        //until we figure this stuff out...
367
368         //set light values for each vertex & build pointlist
369         {
370                 int i;
371
372                 // -- Using new headlight system...face_light = fixmul(face_light,reflect);
373
374                 for (i=0;i<nv;i++) {
375
376                         //the uvl struct has static light already in it
377
378                         //scale static light for destruction effect
379                         if (Control_center_destroyed || Seismic_tremor_magnitude)       //make lights flash
380                                 uvl_copy[i].l = fixmul(flash_scale,uvl_copy[i].l);
381
382                         //add in dynamic light (from explosions, etc.)
383                         uvl_copy[i].l += Dynamic_light[vp[i]];
384
385                         //add in light from player's headlight
386                         // -- Using new headlight system...uvl_copy[i].l += compute_headlight_light(&Segment_points[vp[i]].p3_vec,face_light);
387
388                         //saturate at max value
389                         if (uvl_copy[i].l > MAX_LIGHT)
390                                 uvl_copy[i].l = MAX_LIGHT;
391
392                 }
393         }
394
395 #ifdef EDITOR
396         if ((Render_only_bottom) && (sidenum == WBOTTOM))
397                 g3_draw_tmap(nv,pointlist,(g3s_uvl *) uvl_copy,&GameBitmaps[Textures[Bottom_bitmap_num].index]);
398         else
399 #endif
400
401 #ifdef OGL
402                 if (bm2){
403                         g3_draw_tmap_2(nv,pointlist,(g3s_uvl *) uvl_copy,bm,bm2,((tmap2&0xC000)>>14) & 3);
404                 }else
405 #endif
406                         g3_draw_tmap(nv,pointlist,(g3s_uvl *) uvl_copy,bm);
407
408 #ifndef NDEBUG
409         if (Outline_mode) draw_outline(nv, pointlist);
410 #endif
411 }
412
413 #ifdef EDITOR
414 // ----------------------------------------------------------------------------
415 //      Only called if editor active.
416 //      Used to determine which face was clicked on.
417 void check_face(int segnum, int sidenum, int facenum, int nv, short *vp, int tmap1, int tmap2, uvl *uvlp)
418 {
419         int     i;
420
421         if (_search_mode) {
422                 int save_lighting;
423                 grs_bitmap *bm;
424                 uvl uvl_copy[8];
425                 g3s_point *pointlist[4];
426
427                 if (tmap2 > 0 )
428                         bm = texmerge_get_cached_bitmap( tmap1, tmap2 );
429                 else
430                         bm = &GameBitmaps[Textures[tmap1].index];
431
432                 for (i=0; i<nv; i++) {
433                         uvl_copy[i] = uvlp[i];
434                         pointlist[i] = &Segment_points[vp[i]];
435                 }
436
437                 gr_setcolor(0);
438                 gr_pixel(_search_x,_search_y);  //set our search pixel to color zero
439                 gr_setcolor(1);                                 //and render in color one
440  save_lighting = Lighting_on;
441  Lighting_on = 2;
442                 //g3_draw_poly(nv,vp);
443                 g3_draw_tmap(nv,pointlist, (g3s_uvl *)uvl_copy, bm);
444  Lighting_on = save_lighting;
445
446                 if (gr_ugpixel(&grd_curcanv->cv_bitmap,_search_x,_search_y) == 1) {
447                         found_seg = segnum;
448                         found_side = sidenum;
449                         found_face = facenum;
450                 }
451         }
452 }
453 #endif
454
455 fix     Tulate_min_dot = (F1_0/4);
456 //--unused-- fix        Tulate_min_ratio = (2*F1_0);
457 fix     Min_n0_n1_dot   = (F1_0*15/16);
458
459 extern int contains_flare(segment *segp, int sidenum);
460 extern fix      Obj_light_xlate[16];
461
462 // -----------------------------------------------------------------------------------
463 //      Render a side.
464 //      Check for normal facing.  If so, render faces on side dictated by sidep->type.
465 void render_side(segment *segp, int sidenum)
466 {
467         short                   vertnum_list[4];
468         side                    *sidep = &segp->sides[sidenum];
469         vms_vector      tvec;
470         fix                     v_dot_n0, v_dot_n1;
471         uvl                     temp_uvls[3];
472         fix                     min_dot, max_dot;
473         vms_vector  normals[2];
474         int                     wid_flags;
475
476
477         wid_flags = WALL_IS_DOORWAY(segp,sidenum);
478
479         if (!(wid_flags & WID_RENDER_FLAG))             //if (WALL_IS_DOORWAY(segp, sidenum) == WID_NO_WALL)
480                 return;
481
482 #ifdef COMPACT_SEGS
483         get_side_normals(segp, sidenum, &normals[0], &normals[1] );
484 #else
485         normals[0] = segp->sides[sidenum].normals[0];
486         normals[1] = segp->sides[sidenum].normals[1];
487 #endif
488
489         //      ========== Mark: Here is the change...beginning here: ==========
490
491         if (sidep->type == SIDE_IS_QUAD) {
492
493                 vm_vec_sub(&tvec, &Viewer_eye, &Vertices[segp->verts[Side_to_verts[sidenum][0]]]);
494
495                 // -- Old, slow way --  //      Regardless of whether this side is comprised of a single quad, or two triangles, we need to know one normal, so
496                 // -- Old, slow way --  //      deal with it, get the dot product.
497                 // -- Old, slow way --  if (sidep->type == SIDE_IS_TRI_13)
498                 // -- Old, slow way --          vm_vec_normalized_dir(&tvec, &Viewer_eye, &Vertices[segp->verts[Side_to_verts[sidenum][1]]]);
499                 // -- Old, slow way --  else
500                 // -- Old, slow way --          vm_vec_normalized_dir(&tvec, &Viewer_eye, &Vertices[segp->verts[Side_to_verts[sidenum][0]]]);
501
502                 get_side_verts(vertnum_list,segp-Segments,sidenum);
503                 v_dot_n0 = vm_vec_dot(&tvec, &normals[0]);
504
505 // -- flare creates point -- {
506 // -- flare creates point --    int     flare_index;
507 // -- flare creates point -- 
508 // -- flare creates point --    flare_index = contains_flare(segp, sidenum);
509 // -- flare creates point -- 
510 // -- flare creates point --    if (flare_index != -1) {
511 // -- flare creates point --            int                     tri;
512 // -- flare creates point --            fix                     u, v, l;
513 // -- flare creates point --            vms_vector      *hit_point;
514 // -- flare creates point --            short                   vertnum_list[4];
515 // -- flare creates point -- 
516 // -- flare creates point --            hit_point = &Objects[flare_index].pos;
517 // -- flare creates point -- 
518 // -- flare creates point --            find_hitpoint_uv( &u, &v, &l, hit_point, segp, sidenum, 0);     //      last parm means always use face 0.
519 // -- flare creates point -- 
520 // -- flare creates point --            get_side_verts(vertnum_list, segp-Segments, sidenum);
521 // -- flare creates point -- 
522 // -- flare creates point --            g3_rotate_point(&Segment_points[MAX_VERTICES-1], hit_point);
523 // -- flare creates point -- 
524 // -- flare creates point --            for (tri=0; tri<4; tri++) {
525 // -- flare creates point --                    short   tri_verts[3];
526 // -- flare creates point --                    uvl     tri_uvls[3];
527 // -- flare creates point -- 
528 // -- flare creates point --                    tri_verts[0] = vertnum_list[tri];
529 // -- flare creates point --                    tri_verts[1] = vertnum_list[(tri+1) % 4];
530 // -- flare creates point --                    tri_verts[2] = MAX_VERTICES-1;
531 // -- flare creates point -- 
532 // -- flare creates point --                    tri_uvls[0] = sidep->uvls[tri];
533 // -- flare creates point --                    tri_uvls[1] = sidep->uvls[(tri+1)%4];
534 // -- flare creates point --                    tri_uvls[2].u = u;
535 // -- flare creates point --                    tri_uvls[2].v = v;
536 // -- flare creates point --                    tri_uvls[2].l = F1_0;
537 // -- flare creates point -- 
538 // -- flare creates point --                    render_face(segp-Segments, sidenum, 3, tri_verts, sidep->tmap_num, sidep->tmap_num2, tri_uvls, &normals[0]);
539 // -- flare creates point --            }
540 // -- flare creates point -- 
541 // -- flare creates point --    return;
542 // -- flare creates point --    }
543 // -- flare creates point -- }
544
545                 if (v_dot_n0 >= 0) {
546                         render_face(segp-Segments, sidenum, 4, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls, wid_flags);
547                         #ifdef EDITOR
548                         check_face(segp-Segments, sidenum, 0, 4, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls);
549                         #endif
550                 }
551         } else {
552                 //      Regardless of whether this side is comprised of a single quad, or two triangles, we need to know one normal, so
553                 //      deal with it, get the dot product.
554                 if (sidep->type == SIDE_IS_TRI_13)
555                         vm_vec_normalized_dir_quick(&tvec, &Viewer_eye, &Vertices[segp->verts[Side_to_verts[sidenum][1]]]);
556                 else
557                         vm_vec_normalized_dir_quick(&tvec, &Viewer_eye, &Vertices[segp->verts[Side_to_verts[sidenum][0]]]);
558
559                 get_side_verts(vertnum_list,segp-Segments,sidenum);
560
561                 v_dot_n0 = vm_vec_dot(&tvec, &normals[0]);
562
563                 //      ========== Mark: The change ends here. ==========
564
565                 //      Although this side has been triangulated, because it is not planar, see if it is acceptable
566                 //      to render it as a single quadrilateral.  This is a function of how far away the viewer is, how non-planar
567                 //      the face is, how normal to the surfaces the view is.
568                 //      Now, if both dot products are close to 1.0, then render two triangles as a single quad.
569                 v_dot_n1 = vm_vec_dot(&tvec, &normals[1]);
570
571                 if (v_dot_n0 < v_dot_n1) {
572                         min_dot = v_dot_n0;
573                         max_dot = v_dot_n1;
574                 } else {
575                         min_dot = v_dot_n1;
576                         max_dot = v_dot_n0;
577                 }
578
579                 //      Determine whether to detriangulate side: (speed hack, assumes Tulate_min_ratio == F1_0*2, should fixmul(min_dot, Tulate_min_ratio))
580                 if (Detriangulation_on && ((min_dot+F1_0/256 > max_dot) || ((Viewer->segnum != segp-Segments) &&  (min_dot > Tulate_min_dot) && (max_dot < min_dot*2)))) {
581                         fix     n0_dot_n1;
582
583                         //      The other detriangulation code doesn't deal well with badly non-planar sides.
584                         n0_dot_n1 = vm_vec_dot(&normals[0], &normals[1]);
585                         if (n0_dot_n1 < Min_n0_n1_dot)
586                                 goto im_so_ashamed;
587
588                         render_face(segp-Segments, sidenum, 4, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls, wid_flags);
589                         #ifdef EDITOR
590                         check_face(segp-Segments, sidenum, 0, 4, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls);
591                         #endif
592                 } else {
593 im_so_ashamed: ;
594                         if (sidep->type == SIDE_IS_TRI_02) {
595                                 if (v_dot_n0 >= 0) {
596                                         render_face(segp-Segments, sidenum, 3, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls, wid_flags);
597                                         #ifdef EDITOR
598                                         check_face(segp-Segments, sidenum, 0, 3, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls);
599                                         #endif
600                                 }
601
602                                 if (v_dot_n1 >= 0) {
603                                         temp_uvls[0] = sidep->uvls[0];          temp_uvls[1] = sidep->uvls[2];          temp_uvls[2] = sidep->uvls[3];
604                                         vertnum_list[1] = vertnum_list[2];      vertnum_list[2] = vertnum_list[3];      // want to render from vertices 0, 2, 3 on side
605                                         render_face(segp-Segments, sidenum, 3, &vertnum_list[0], sidep->tmap_num, sidep->tmap_num2, temp_uvls, wid_flags);
606                                         #ifdef EDITOR
607                                         check_face(segp-Segments, sidenum, 1, 3, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls);
608                                         #endif
609                                 }
610                         } else if (sidep->type ==  SIDE_IS_TRI_13) {
611                                 if (v_dot_n1 >= 0) {
612                                         render_face(segp-Segments, sidenum, 3, &vertnum_list[1], sidep->tmap_num, sidep->tmap_num2, &sidep->uvls[1], wid_flags);        // rendering 1,2,3, so just skip 0
613                                         #ifdef EDITOR
614                                         check_face(segp-Segments, sidenum, 1, 3, &vertnum_list[1], sidep->tmap_num, sidep->tmap_num2, sidep->uvls);
615                                         #endif
616                                 }
617
618                                 if (v_dot_n0 >= 0) {
619                                         temp_uvls[0] = sidep->uvls[0];          temp_uvls[1] = sidep->uvls[1];          temp_uvls[2] = sidep->uvls[3];
620                                         vertnum_list[2] = vertnum_list[3];              // want to render from vertices 0,1,3
621                                         render_face(segp-Segments, sidenum, 3, vertnum_list, sidep->tmap_num, sidep->tmap_num2, temp_uvls, wid_flags);
622                                         #ifdef EDITOR
623                                         check_face(segp-Segments, sidenum, 0, 3, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls);
624                                         #endif
625                                 }
626
627                         } else
628 #ifdef __DJGPP__
629                                 Error("Illegal side type in render_side, type = %i, segment # = %li, side # = %i\n", sidep->type, segp-Segments, sidenum);
630 #else
631                                 Error("Illegal side type in render_side, type = %i, segment # = %i, side # = %i\n", sidep->type, segp-Segments, sidenum);
632 #endif
633                 }
634         }
635
636 }
637
638 #ifdef EDITOR
639 void render_object_search(object *obj)
640 {
641         int changed=0;
642
643         //note that we draw each pixel object twice, since we cannot control
644         //what color the object draws in, so we try color 0, then color 1,
645         //in case the object itself is rendering color 0
646
647         gr_setcolor(0);
648         gr_pixel(_search_x,_search_y);  //set our search pixel to color zero
649         render_object(obj);
650         if (gr_ugpixel(&grd_curcanv->cv_bitmap,_search_x,_search_y) != 0)
651                 changed=1;
652
653         gr_setcolor(1);
654         gr_pixel(_search_x,_search_y);  //set our search pixel to color zero
655         render_object(obj);
656         if (gr_ugpixel(&grd_curcanv->cv_bitmap,_search_x,_search_y) != 1)
657                 changed=1;
658
659         if (changed) {
660                 if (obj->segnum != -1)
661                         Cursegp = &Segments[obj->segnum];
662                 found_seg = -(obj-Objects+1);
663         }
664 }
665 #endif
666
667 extern ubyte DemoDoingRight,DemoDoingLeft;
668
669 void do_render_object(int objnum, int window_num)
670 {
671         #ifdef EDITOR
672         int save_3d_outline=0;
673         #endif
674         object *obj = &Objects[objnum];
675         int count = 0;
676         int n;
677
678         Assert(objnum < MAX_OBJECTS);
679
680         #ifndef NDEBUG
681         if (object_rendered[objnum]) {          //already rendered this...
682                 Int3();         //get Matt!!!
683                 return;
684         }
685
686         object_rendered[objnum] = 1;
687         #endif
688
689    if (Newdemo_state==ND_STATE_PLAYBACK)  
690          {
691           if ((DemoDoingLeft==6 || DemoDoingRight==6) && Objects[objnum].type==OBJ_PLAYER)
692                 {
693                         // A nice fat hack: keeps the player ship from showing up in the
694                         // small extra view when guiding a missile in the big window
695                         
696                         mprintf ((0,"Returning from render_object prematurely...\n"));
697                         return; 
698                 }
699          }
700
701         //      Added by MK on 09/07/94 (at about 5:28 pm, CDT, on a beautiful, sunny late summer day!) so
702         //      that the guided missile system will know what objects to look at.
703         //      I didn't know we had guided missiles before the release of D1. --MK
704         if ((Objects[objnum].type == OBJ_ROBOT) || (Objects[objnum].type == OBJ_PLAYER)) {
705                 //Assert(Window_rendered_data[window_num].rendered_objects < MAX_RENDERED_OBJECTS);
706                 //      This peculiar piece of code makes us keep track of the most recently rendered objects, which
707                 //      are probably the higher priority objects, without overflowing the buffer
708                 if (Window_rendered_data[window_num].num_objects >= MAX_RENDERED_OBJECTS) {
709                         Int3();
710                         Window_rendered_data[window_num].num_objects /= 2;
711                 }
712                 Window_rendered_data[window_num].rendered_objects[Window_rendered_data[window_num].num_objects++] = objnum;
713         }
714
715         if ((count++ > MAX_OBJECTS) || (obj->next == objnum)) {
716                 Int3();                                 // infinite loop detected
717                 obj->next = -1;         // won't this clean things up?
718                 return;                                 // get out of this infinite loop!
719         }
720
721                 //g3_draw_object(obj->class_id,&obj->pos,&obj->orient,obj->size);
722
723         //check for editor object
724
725         #ifdef EDITOR
726         if (Function_mode==FMODE_EDITOR && objnum==Cur_object_index) {
727                 save_3d_outline = g3d_interp_outline;
728                 g3d_interp_outline=1;
729         }
730         #endif
731
732         #ifdef EDITOR
733         if (_search_mode)
734                 render_object_search(obj);
735         else
736         #endif
737                 //NOTE LINK TO ABOVE
738                 render_object(obj);
739
740         for (n=obj->attached_obj;n!=-1;n=Objects[n].ctype.expl_info.next_attach) {
741
742                 Assert(Objects[n].type == OBJ_FIREBALL);
743                 Assert(Objects[n].control_type == CT_EXPLOSION);
744                 Assert(Objects[n].flags & OF_ATTACHED);
745
746                 render_object(&Objects[n]);
747         }
748
749
750         #ifdef EDITOR
751         if (Function_mode==FMODE_EDITOR && objnum==Cur_object_index)
752                 g3d_interp_outline = save_3d_outline;
753         #endif
754
755
756         //DEBUG mprintf( (0, "%d ", objnum ));
757
758 }
759
760 #ifndef NDEBUG
761 int     draw_boxes=0;
762 int window_check=1,draw_edges=0,new_seg_sorting=1,pre_draw_segs=0;
763 int no_migrate_segs=1,migrate_objects=1,behind_check=1;
764 int check_window_check=0;
765 #else
766 #define draw_boxes                      0
767 #define window_check                    1
768 #define draw_edges                      0
769 #define new_seg_sorting         1
770 #define pre_draw_segs           0
771 #define no_migrate_segs         1
772 #define migrate_objects         1
773 #define behind_check                    1
774 #define check_window_check      0
775 #endif
776
777 //increment counter for checking if points rotated
778 //This must be called at the start of the frame if rotate_list() will be used
779 void render_start_frame()
780 {
781         RL_framecount++;
782
783         if (RL_framecount==0) {         //wrap!
784
785                 memset(Rotated_last,0,sizeof(Rotated_last));            //clear all to zero
786                 RL_framecount=1;                                                                                        //and set this frame to 1
787         }
788 }
789
790 //Given a lit of point numbers, rotate any that haven't been rotated this frame
791 g3s_codes rotate_list(int nv,short *pointnumlist)
792 {
793         int i,pnum;
794         g3s_point *pnt;
795         g3s_codes cc;
796
797         cc.and = 0xff;  cc.or = 0;
798
799         for (i=0;i<nv;i++) {
800
801                 pnum = pointnumlist[i];
802
803                 pnt = &Segment_points[pnum];
804
805                 if (Rotated_last[pnum] != RL_framecount) {
806
807                         g3_rotate_point(pnt,&Vertices[pnum]);
808
809                         Rotated_last[pnum] = RL_framecount;
810                 }
811
812                 cc.and &= pnt->p3_codes;
813                 cc.or  |= pnt->p3_codes;
814         }
815
816         return cc;
817
818 }
819
820 //Given a lit of point numbers, project any that haven't been projected
821 void project_list(int nv,short *pointnumlist)
822 {
823         int i,pnum;
824
825         for (i=0;i<nv;i++) {
826
827                 pnum = pointnumlist[i];
828
829                 if (!(Segment_points[pnum].p3_flags & PF_PROJECTED))
830
831                         g3_project_point(&Segment_points[pnum]);
832
833         }
834 }
835
836
837 // -----------------------------------------------------------------------------------
838 void render_segment(int segnum, int window_num)
839 {
840         segment         *seg = &Segments[segnum];
841         g3s_codes       cc;
842         int                     sn;
843
844         Assert(segnum!=-1 && segnum<=Highest_segment_index);
845
846         cc=rotate_list(8,seg->verts);
847
848         if (! cc.and) {         //all off screen?
849
850 //mprintf( (0, "!"));
851                 //DEBUG mprintf( (0, "[Segment %d: ", segnum ));
852
853                 // set_segment_local_light_value(segnum,INITIAL_LOCAL_LIGHT);
854
855       if (Viewer->type!=OBJ_ROBOT)
856                 Automap_visited[segnum]=1;
857
858                 for (sn=0; sn<MAX_SIDES_PER_SEGMENT; sn++)
859                         render_side(seg, sn);
860         }
861
862         //draw any objects that happen to be in this segment
863
864         //sort objects!
865         //object_sort_segment_objects( seg );
866                 
867         #ifndef NDEBUG
868         if (!migrate_objects) {
869                 int objnum;
870                 for (objnum=seg->objects;objnum!=-1;objnum=Objects[objnum].next)
871                         do_render_object(objnum, window_num);
872         }
873         #endif
874
875         //DEBUG mprintf( (0, "]\n", segnum ));
876
877 }
878
879 // ----- This used to be called when Show_only_curside was set.
880 // ----- It is wholly and superiorly replaced by render_side.
881 // -- //render one side of one segment
882 // -- void render_seg_side(segment *seg,int _side)
883 // -- {
884 // --   g3s_codes cc;
885 // --   short vertnum_list[4];
886 // -- 
887 // --   cc=g3_rotate_list(8,&seg->verts);
888 // -- 
889 // --   if (! cc.and) {         //all off screen?
890 // --           int fn,pn,i;
891 // --           side *s;
892 // --           face *f;
893 // --           poly *p;
894 // -- 
895 // --           s=&seg->sides[_side];
896 // -- 
897 // --           for (f=s->faces,fn=s->num_faces;fn;fn--,f++)
898 // --                   for (p=f->polys,pn=f->num_polys;pn;pn--,p++) {
899 // --                           grs_bitmap *tmap;
900 // --   
901 // --                           for (i=0;i<p->num_vertices;i++) vertnum_list[i] = seg->verts[p->verts[i]];
902 // --   
903 // --                           if (p->tmap_num >= NumTextures) {
904 // --                                   Warning("Invalid tmap number %d, NumTextures=%d\n...Changing in poly structure to tmap 0",p->tmap_num,NumTextures);
905 // --                                   p->tmap_num = 0;                //change it permanantly
906 // --                           }
907 // --   
908 // --                           tmap = Textures[p->tmap_num];
909 // --   
910 // --                           g3_check_and_draw_tmap(p->num_vertices,vertnum_list,(g3s_uvl *) &p->uvls,tmap,&f->normal);
911 // --   
912 // --                           if (Outline_mode) draw_outline(p->num_vertices,vertnum_list);
913 // --                   }
914 // --           }
915 // -- 
916 // -- }
917
918 #define CROSS_WIDTH  i2f(8)
919 #define CROSS_HEIGHT i2f(8)
920
921 #ifndef NDEBUG
922
923 //draw outline for curside
924 void outline_seg_side(segment *seg,int _side,int edge,int vert)
925 {
926         g3s_codes cc;
927
928         cc=rotate_list(8,seg->verts);
929
930         if (! cc.and) {         //all off screen?
931                 side *s;
932                 g3s_point *pnt;
933
934                 s=&seg->sides[_side];
935
936                 //render curedge of curside of curseg in green
937
938                 gr_setcolor(BM_XRGB(0,63,0));
939                 g3_draw_line(&Segment_points[seg->verts[Side_to_verts[_side][edge]]],&Segment_points[seg->verts[Side_to_verts[_side][(edge+1)%4]]]);
940
941                 //draw a little cross at the current vert
942
943                 pnt = &Segment_points[seg->verts[Side_to_verts[_side][vert]]];
944
945                 g3_project_point(pnt);          //make sure projected
946
947 //              gr_setcolor(BM_XRGB(0,0,63));
948 //              gr_line(pnt->p3_sx-CROSS_WIDTH,pnt->p3_sy,pnt->p3_sx+CROSS_WIDTH,pnt->p3_sy);
949 //              gr_line(pnt->p3_sx,pnt->p3_sy-CROSS_HEIGHT,pnt->p3_sx,pnt->p3_sy+CROSS_HEIGHT);
950
951                 gr_line(pnt->p3_sx-CROSS_WIDTH,pnt->p3_sy,pnt->p3_sx,pnt->p3_sy-CROSS_HEIGHT);
952                 gr_line(pnt->p3_sx,pnt->p3_sy-CROSS_HEIGHT,pnt->p3_sx+CROSS_WIDTH,pnt->p3_sy);
953                 gr_line(pnt->p3_sx+CROSS_WIDTH,pnt->p3_sy,pnt->p3_sx,pnt->p3_sy+CROSS_HEIGHT);
954                 gr_line(pnt->p3_sx,pnt->p3_sy+CROSS_HEIGHT,pnt->p3_sx-CROSS_WIDTH,pnt->p3_sy);
955         }
956 }
957
958 #endif
959
960 #if 0           //this stuff could probably just be deleted
961
962 #define DEFAULT_PERSPECTIVE_DEPTH 6
963
964 int Perspective_depth=DEFAULT_PERSPECTIVE_DEPTH;        //how many levels deep to render in perspective
965
966 int inc_perspective_depth(void)
967 {
968         return ++Perspective_depth;
969
970 }
971
972 int dec_perspective_depth(void)
973 {
974         return Perspective_depth==1?Perspective_depth:--Perspective_depth;
975
976 }
977
978 int reset_perspective_depth(void)
979 {
980         return Perspective_depth = DEFAULT_PERSPECTIVE_DEPTH;
981
982 }
983 #endif
984
985 typedef struct window {
986         short left,top,right,bot;
987 } window;
988
989 ubyte code_window_point(fix x,fix y,window *w)
990 {
991         ubyte code=0;
992
993         if (x <= w->left)  code |= 1;
994         if (x >= w->right) code |= 2;
995
996         if (y <= w->top) code |= 4;
997         if (y >= w->bot) code |= 8;
998
999         return code;
1000 }
1001
1002 #ifndef NDEBUG
1003 void draw_window_box(int color,short left,short top,short right,short bot)
1004 {
1005         short l,t,r,b;
1006
1007         gr_setcolor(color);
1008
1009         l=left; t=top; r=right; b=bot;
1010
1011         if ( r<0 || b<0 || l>=grd_curcanv->cv_bitmap.bm_w || (t>=grd_curcanv->cv_bitmap.bm_h && b>=grd_curcanv->cv_bitmap.bm_h))
1012                 return;
1013
1014         if (l<0) l=0;
1015         if (t<0) t=0;
1016         if (r>=grd_curcanv->cv_bitmap.bm_w) r=grd_curcanv->cv_bitmap.bm_w-1;
1017         if (b>=grd_curcanv->cv_bitmap.bm_h) b=grd_curcanv->cv_bitmap.bm_h-1;
1018
1019         gr_line(i2f(l),i2f(t),i2f(r),i2f(t));
1020         gr_line(i2f(r),i2f(t),i2f(r),i2f(b));
1021         gr_line(i2f(r),i2f(b),i2f(l),i2f(b));
1022         gr_line(i2f(l),i2f(b),i2f(l),i2f(t));
1023
1024 }
1025 #endif
1026
1027 int matt_find_connect_side(int seg0,int seg1);
1028
1029 #ifndef NDEBUG
1030 char visited2[MAX_SEGMENTS];
1031 #endif
1032
1033 unsigned char visited[MAX_SEGMENTS];
1034 short Render_list[MAX_RENDER_SEGS];
1035 short Seg_depth[MAX_RENDER_SEGS];               //depth for each seg in Render_list
1036 ubyte processed[MAX_RENDER_SEGS];               //whether each entry has been processed
1037 int     lcnt_save,scnt_save;
1038 //@@short *persp_ptr;
1039 short render_pos[MAX_SEGMENTS]; //where in render_list does this segment appear?
1040 //ubyte no_render_flag[MAX_RENDER_SEGS];
1041 window render_windows[MAX_RENDER_SEGS];
1042
1043 short render_obj_list[MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS][OBJS_PER_SEG];
1044
1045 //for objects
1046
1047
1048
1049 #define RED   BM_XRGB(63,0,0)
1050 #define WHITE BM_XRGB(63,63,63)
1051
1052 //Given two sides of segment, tell the two verts which form the 
1053 //edge between them
1054 short Two_sides_to_edge[6][6][2] = {
1055         { {-1,-1}, {3,7}, {-1,-1}, {2,6}, {6,7}, {2,3} },
1056         { {3,7}, {-1,-1}, {0,4}, {-1,-1}, {4,7}, {0,3} },
1057         { {-1,-1}, {0,4}, {-1,-1}, {1,5}, {4,5}, {0,1} },
1058         { {2,6}, {-1,-1}, {1,5}, {-1,-1}, {5,6}, {1,2} },
1059         { {6,7}, {4,7}, {4,5}, {5,6}, {-1,-1}, {-1,-1} },
1060         { {2,3}, {0,3}, {0,1}, {1,2}, {-1,-1}, {-1,-1} }
1061 };
1062
1063 //given an edge specified by two verts, give the two sides on that edge
1064 int Edge_to_sides[8][8][2] = {
1065         { {-1,-1}, {2,5}, {-1,-1}, {1,5}, {1,2}, {-1,-1}, {-1,-1}, {-1,-1} },
1066         { {2,5}, {-1,-1}, {3,5}, {-1,-1}, {-1,-1}, {2,3}, {-1,-1}, {-1,-1} },
1067         { {-1,-1}, {3,5}, {-1,-1}, {0,5}, {-1,-1}, {-1,-1}, {0,3}, {-1,-1} },
1068         { {1,5}, {-1,-1}, {0,5}, {-1,-1}, {-1,-1}, {-1,-1}, {-1,-1}, {0,1} },
1069         { {1,2}, {-1,-1}, {-1,-1}, {-1,-1}, {-1,-1}, {2,4}, {-1,-1}, {1,4} },
1070         { {-1,-1}, {2,3}, {-1,-1}, {-1,-1}, {2,4}, {-1,-1}, {3,4}, {-1,-1} },
1071         { {-1,-1}, {-1,-1}, {0,3}, {-1,-1}, {-1,-1}, {3,4}, {-1,-1}, {0,4} },
1072         { {-1,-1}, {-1,-1}, {-1,-1}, {0,1}, {1,4}, {-1,-1}, {0,4}, {-1,-1} },
1073 };
1074
1075 //@@//perform simple check on tables
1076 //@@check_check()
1077 //@@{
1078 //@@    int i,j;
1079 //@@
1080 //@@    for (i=0;i<8;i++)
1081 //@@            for (j=0;j<8;j++)
1082 //@@                    Assert(Edge_to_sides[i][j][0] == Edge_to_sides[j][i][0] && 
1083 //@@                                    Edge_to_sides[i][j][1] == Edge_to_sides[j][i][1]);
1084 //@@
1085 //@@    for (i=0;i<6;i++)
1086 //@@            for (j=0;j<6;j++)
1087 //@@                    Assert(Two_sides_to_edge[i][j][0] == Two_sides_to_edge[j][i][0] && 
1088 //@@                                    Two_sides_to_edge[i][j][1] == Two_sides_to_edge[j][i][1]);
1089 //@@
1090 //@@
1091 //@@}
1092
1093
1094 //given an edge, tell what side is on that edge
1095 int find_seg_side(segment *seg,short *verts,int notside)
1096 {
1097         int i;
1098         int vv0=-1,vv1=-1;
1099         int side0,side1;
1100         int *eptr;
1101         int     v0,v1;
1102         short   *vp;
1103
1104 //@@    check_check();
1105
1106         v0 = verts[0];
1107         v1 = verts[1];
1108         vp = seg->verts;
1109
1110         for (i=0; i<8; i++) {
1111                 int svv = *vp++;        // seg->verts[i];
1112
1113                 if (vv0==-1 && svv == v0) {
1114                         vv0 = i;
1115                         if (vv1 != -1)
1116                                 break;
1117                 }
1118
1119                 if (vv1==-1 && svv == v1) {
1120                         vv1 = i;
1121                         if (vv0 != -1)
1122                                 break;
1123                 }
1124         }
1125
1126         Assert(vv0!=-1 && vv1!=-1);
1127
1128         eptr = Edge_to_sides[vv0][vv1];
1129
1130         side0 = eptr[0];
1131         side1 = eptr[1];
1132
1133         Assert(side0!=-1 && side1!=-1);
1134
1135         if (side0 != notside) {
1136                 Assert(side1==notside);
1137                 return side0;
1138         }
1139         else {
1140                 Assert(side0==notside);
1141                 return side1;
1142         }
1143
1144 }
1145
1146 //find the two segments that join a given seg though two sides, and
1147 //the sides of those segments the abut. 
1148 int find_joining_side_norms(vms_vector *norm0_0,vms_vector *norm0_1,vms_vector *norm1_0,vms_vector *norm1_1,vms_vector **pnt0,vms_vector **pnt1,segment *seg,int s0,int s1)
1149 {
1150         segment *seg0,*seg1;
1151         short edge_verts[2];
1152         int notside0,notside1;
1153         int edgeside0,edgeside1;
1154
1155         Assert(s0!=-1 && s1!=-1);
1156
1157         seg0 = &Segments[seg->children[s0]];
1158         seg1 = &Segments[seg->children[s1]];
1159
1160         edge_verts[0] = seg->verts[Two_sides_to_edge[s0][s1][0]];
1161         edge_verts[1] = seg->verts[Two_sides_to_edge[s0][s1][1]];
1162
1163         Assert(edge_verts[0]!=-1 && edge_verts[1]!=-1);
1164
1165         notside0 = find_connect_side(seg,seg0);
1166         Assert(notside0 != -1);
1167         notside1 = find_connect_side(seg,seg1);
1168         Assert(notside1 != -1);
1169
1170         edgeside0 = find_seg_side(seg0,edge_verts,notside0);
1171         edgeside1 = find_seg_side(seg1,edge_verts,notside1);
1172
1173         //deal with the case where an edge is shared by more than two segments
1174
1175 //@@    if (IS_CHILD(seg0->children[edgeside0])) {
1176 //@@            segment *seg00;
1177 //@@            int notside00;
1178 //@@
1179 //@@            seg00 = &Segments[seg0->children[edgeside0]];
1180 //@@
1181 //@@            if (seg00 != seg1) {
1182 //@@
1183 //@@                    notside00 = find_connect_side(seg0,seg00);
1184 //@@                    Assert(notside00 != -1);
1185 //@@
1186 //@@                    edgeside0 = find_seg_side(seg00,edge_verts,notside00);
1187 //@@                    seg0 = seg00;
1188 //@@            }
1189 //@@
1190 //@@    }
1191 //@@
1192 //@@    if (IS_CHILD(seg1->children[edgeside1])) {
1193 //@@            segment *seg11;
1194 //@@            int notside11;
1195 //@@
1196 //@@            seg11 = &Segments[seg1->children[edgeside1]];
1197 //@@
1198 //@@            if (seg11 != seg0) {
1199 //@@                    notside11 = find_connect_side(seg1,seg11);
1200 //@@                    Assert(notside11 != -1);
1201 //@@
1202 //@@                    edgeside1 = find_seg_side(seg11,edge_verts,notside11);
1203 //@@                    seg1 = seg11;
1204 //@@            }
1205 //@@    }
1206
1207 //      if ( IS_CHILD(seg0->children[edgeside0]) ||
1208 //                IS_CHILD(seg1->children[edgeside1])) 
1209 //              return 0;
1210
1211         #ifdef COMPACT_SEGS
1212                 get_side_normals(seg0, edgeside0, norm0_0, norm0_1 );
1213                 get_side_normals(seg1, edgeside1, norm1_0, norm1_1 );
1214         #else 
1215                 *norm0_0 = seg0->sides[edgeside0].normals[0];
1216                 *norm0_1 = seg0->sides[edgeside0].normals[1];
1217                 *norm1_0 = seg1->sides[edgeside1].normals[0];
1218                 *norm1_1 = seg1->sides[edgeside1].normals[1];
1219         #endif
1220
1221         *pnt0 = &Vertices[seg0->verts[Side_to_verts[edgeside0][seg0->sides[edgeside0].type==3?1:0]]];
1222         *pnt1 = &Vertices[seg1->verts[Side_to_verts[edgeside1][seg1->sides[edgeside1].type==3?1:0]]];
1223
1224         return 1;
1225 }
1226
1227 //see if the order matters for these two children.
1228 //returns 0 if order doesn't matter, 1 if c0 before c1, -1 if c1 before c0
1229 int compare_children(segment *seg,short c0,short c1)
1230 {
1231         vms_vector norm0_0,norm0_1,*pnt0,temp;
1232         vms_vector norm1_0,norm1_1,*pnt1;
1233         fix d0_0,d0_1,d1_0,d1_1,d0,d1;
1234 int t;
1235
1236         if (Side_opposite[c0] == c1) return 0;
1237
1238         Assert(c0!=-1 && c1!=-1);
1239
1240         //find normals of adjoining sides
1241
1242         t = find_joining_side_norms(&norm0_0,&norm0_1,&norm1_0,&norm1_1,&pnt0,&pnt1,seg,c0,c1);
1243
1244 //if (!t)
1245 // return 0;
1246
1247         vm_vec_sub(&temp,&Viewer_eye,pnt0);
1248         d0_0 = vm_vec_dot(&norm0_0,&temp);
1249         d0_1 = vm_vec_dot(&norm0_1,&temp);
1250
1251         vm_vec_sub(&temp,&Viewer_eye,pnt1);
1252         d1_0 = vm_vec_dot(&norm1_0,&temp);
1253         d1_1 = vm_vec_dot(&norm1_1,&temp);
1254
1255         d0 = (d0_0 < 0 || d0_1 < 0)?-1:1;
1256         d1 = (d1_0 < 0 || d1_1 < 0)?-1:1;
1257
1258         if (d0 < 0 && d1 < 0)
1259                 return 0;
1260
1261         if (d0 < 0)
1262                 return 1;
1263         else if (d1 < 0)
1264                 return -1;
1265         else
1266                 return 0;
1267
1268 }
1269
1270 int ssc_total=0,ssc_swaps=0;
1271
1272 //short the children of segment to render in the correct order
1273 //returns non-zero if swaps were made
1274 int sort_seg_children(segment *seg,int n_children,short *child_list)
1275 {
1276         int i,j;
1277         int r;
1278         int made_swaps,count;
1279
1280         if (n_children == 0) return 0;
1281
1282  ssc_total++;
1283
1284         //for each child,  compare with other children and see if order matters
1285         //if order matters, fix if wrong
1286
1287         count = 0;
1288
1289         do {
1290                 made_swaps = 0;
1291
1292                 for (i=0;i<n_children-1;i++)
1293                         for (j=i+1;child_list[i]!=-1 && j<n_children;j++)
1294                                 if (child_list[j]!=-1) {
1295                                         r = compare_children(seg,child_list[i],child_list[j]);
1296
1297                                         if (r == 1) {
1298                                                 int temp = child_list[i];
1299                                                 child_list[i] = child_list[j];
1300                                                 child_list[j] = temp;
1301                                                 made_swaps=1;
1302                                         }
1303                                 }
1304
1305         } while (made_swaps && ++count<n_children);
1306
1307  if (count)
1308   ssc_swaps++;
1309
1310         return count;
1311 }
1312
1313 void add_obj_to_seglist(int objnum,int listnum)
1314 {
1315         int i,checkn,marker;
1316
1317         checkn = listnum;
1318
1319         //first, find a slot
1320
1321 //mprintf((0,"adding obj %d to %d",objnum,listnum));
1322
1323         do {
1324
1325                 for (i=0;render_obj_list[checkn][i] >= 0;i++);
1326         
1327                 Assert(i < OBJS_PER_SEG);
1328         
1329                 marker = render_obj_list[checkn][i];
1330
1331                 if (marker != -1) {
1332                         checkn = -marker;
1333                         //Assert(checkn < MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS);
1334                         if (checkn >= MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS) {
1335                                 Int3();
1336                                 return;
1337                         }
1338                 }
1339
1340         } while (marker != -1);
1341
1342 //mprintf((0,"  slot %d,%d",checkn,i));
1343
1344
1345         //now we have found a slot.  put object in it
1346
1347         if (i != OBJS_PER_SEG-1) {
1348
1349                 render_obj_list[checkn][i] = objnum;
1350                 render_obj_list[checkn][i+1] = -1;
1351         }
1352         else {                          //chain to additional list
1353                 int lookn;
1354
1355                 //find an available sublist
1356
1357                 for (lookn=MAX_RENDER_SEGS;render_obj_list[lookn][0]!=-1 && lookn<MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS;lookn++);
1358
1359                 //Assert(lookn<MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS);
1360                 if (lookn >= MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS) {
1361                         Int3();
1362                         return;
1363                 }
1364
1365                 render_obj_list[checkn][i] = -lookn;
1366                 render_obj_list[lookn][0] = objnum;
1367                 render_obj_list[lookn][1] = -1;
1368
1369         }
1370
1371 //mprintf((0,"  added!\n"));
1372
1373 }
1374 #ifdef __sun__
1375 // the following is a drop-in replacement for the broken libc qsort on solaris
1376 // taken from http://www.snippets.org/snippets/portable/RG_QSORT+C.php3
1377
1378 #define qsort qsort_dropin
1379
1380 /******************************************************************/
1381 /* qsort.c  --  Non-Recursive ANSI Quicksort function             */
1382 /* Public domain by Raymond Gardner, Englewood CO  February 1991  */
1383 /******************************************************************/
1384 #define  COMP(a, b)  ((*comp)((void *)(a), (void *)(b)))
1385 #define  T 7 // subfiles of <= T elements will be insertion sorteded (T >= 3)
1386 #define  SWAP(a, b)  (swap_bytes((char *)(a), (char *)(b), size))
1387
1388 static void swap_bytes(char *a, char *b, size_t nbytes)
1389 {
1390    char tmp;
1391    do {
1392       tmp = *a; *a++ = *b; *b++ = tmp;
1393    } while ( --nbytes );
1394 }
1395
1396 void qsort(void *basep, size_t nelems, size_t size,
1397                             int (*comp)(const void *, const void *))
1398 {
1399    char *stack[40], **sp;       /* stack and stack pointer        */
1400    char *i, *j, *limit;         /* scan and limit pointers        */
1401    size_t thresh;               /* size of T elements in bytes    */
1402    char *base;                  /* base pointer as char *         */
1403    base = (char *)basep;        /* set up char * base pointer     */
1404    thresh = T * size;           /* init threshold                 */
1405    sp = stack;                  /* init stack pointer             */
1406    limit = base + nelems * size;/* pointer past end of array      */
1407    for ( ;; ) {                 /* repeat until break...          */
1408       if ( limit - base > thresh ) {  /* if more than T elements  */
1409                                       /*   swap base with middle  */
1410          SWAP((((limit-base)/size)/2)*size+base, base);
1411          i = base + size;             /* i scans left to right    */
1412          j = limit - size;            /* j scans right to left    */
1413          if ( COMP(i, j) > 0 )        /* Sedgewick's              */
1414             SWAP(i, j);               /*    three-element sort    */
1415          if ( COMP(base, j) > 0 )     /*        sets things up    */
1416             SWAP(base, j);            /*            so that       */
1417          if ( COMP(i, base) > 0 )     /*      *i <= *base <= *j   */
1418             SWAP(i, base);            /* *base is pivot element   */
1419          for ( ;; ) {                 /* loop until break         */
1420             do                        /* move i right             */
1421                i += size;             /*        until *i >= pivot */
1422             while ( COMP(i, base) < 0 );
1423             do                        /* move j left              */
1424                j -= size;             /*        until *j <= pivot */
1425             while ( COMP(j, base) > 0 );
1426             if ( i > j )              /* if pointers crossed      */
1427                break;                 /*     break loop           */
1428             SWAP(i, j);       /* else swap elements, keep scanning*/
1429          }
1430          SWAP(base, j);         /* move pivot into correct place  */
1431          if ( j - base > limit - i ) {  /* if left subfile larger */
1432             sp[0] = base;             /* stack left subfile base  */
1433             sp[1] = j;                /*    and limit             */
1434             base = i;                 /* sort the right subfile   */
1435          } else {                     /* else right subfile larger*/
1436             sp[0] = i;                /* stack right subfile base */
1437             sp[1] = limit;            /*    and limit             */
1438             limit = j;                /* sort the left subfile    */
1439          }
1440          sp += 2;                     /* increment stack pointer  */
1441       } else {      /* else subfile is small, use insertion sort  */
1442          for ( j = base, i = j+size; i < limit; j = i, i += size )
1443             for ( ; COMP(j, j+size) > 0; j -= size ) {
1444                SWAP(j, j+size);
1445                if ( j == base )
1446                   break;
1447             }
1448          if ( sp != stack ) {         /* if any entries on stack  */
1449             sp -= 2;                  /* pop the base and limit   */
1450             base = sp[0];
1451             limit = sp[1];
1452          } else                       /* else stack empty, done   */
1453             break;
1454       }
1455    }
1456 }
1457 #endif // __sun__ qsort drop-in replacement
1458
1459 #define SORT_LIST_SIZE 100
1460
1461 typedef struct sort_item {
1462         int objnum;
1463         fix dist;
1464 } sort_item;
1465
1466 sort_item sort_list[SORT_LIST_SIZE];
1467 int n_sort_items;
1468
1469 //compare function for object sort. 
1470 int sort_func(const sort_item *a,const sort_item *b)
1471 {
1472         fix delta_dist;
1473         object *obj_a,*obj_b;
1474
1475         delta_dist = a->dist - b->dist;
1476
1477         obj_a = &Objects[a->objnum];
1478         obj_b = &Objects[b->objnum];
1479
1480         if (abs(delta_dist) < (obj_a->size + obj_b->size)) {            //same position
1481
1482                 //these two objects are in the same position.  see if one is a fireball
1483                 //or laser or something that should plot on top.  Don't do this for
1484                 //the afterburner blobs, though.
1485
1486                 if (obj_a->type == OBJ_WEAPON || (obj_a->type == OBJ_FIREBALL && obj_a->id != VCLIP_AFTERBURNER_BLOB))
1487                         if (!(obj_b->type == OBJ_WEAPON || obj_b->type == OBJ_FIREBALL))
1488                                 return -1;      //a is weapon, b is not, so say a is closer
1489                         else;                           //both are weapons 
1490                 else
1491                         if (obj_b->type == OBJ_WEAPON || (obj_b->type == OBJ_FIREBALL && obj_b->id != VCLIP_AFTERBURNER_BLOB))
1492                                 return 1;       //b is weapon, a is not, so say a is farther
1493
1494                 //no special case, fall through to normal return
1495         }
1496
1497         return delta_dist;      //return distance
1498 }
1499
1500 void build_object_lists(int n_segs)
1501 {
1502         int nn;
1503
1504 //mprintf((0,"build n_segs=%d",n_segs));
1505
1506         for (nn=0;nn<MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS;nn++)
1507                 render_obj_list[nn][0] = -1;
1508
1509         for (nn=0;nn<n_segs;nn++) {
1510                 int segnum;
1511
1512                 segnum = Render_list[nn];
1513
1514 //mprintf((0,"nn=%d seg=%d ",nn,segnum));
1515
1516                 if (segnum != -1) {
1517                         int objnum;
1518                         object *obj;
1519
1520                         for (objnum=Segments[segnum].objects;objnum!=-1;objnum = obj->next) {
1521                                 int new_segnum,did_migrate,list_pos;
1522
1523                                 obj = &Objects[objnum];
1524
1525                                 Assert( obj->segnum == segnum );
1526
1527                                 if (obj->flags & OF_ATTACHED)
1528                                         continue;               //ignore this object
1529
1530                                 new_segnum = segnum;
1531                                 list_pos = nn;
1532
1533 //mprintf((0,"objnum=%d ",objnum));
1534                                 if (obj->type != OBJ_CNTRLCEN && !(obj->type==OBJ_ROBOT && obj->id==65))                //don't migrate controlcen
1535                                 do {
1536                                         segmasks m;
1537
1538                                         did_migrate = 0;
1539         
1540                                         m = get_seg_masks(&obj->pos, new_segnum, obj->size, __FILE__, __LINE__);
1541         
1542                                         if (m.sidemask) {
1543                                                 int sn,sf;
1544
1545                                                 for (sn=0,sf=1;sn<6;sn++,sf<<=1)
1546                                                         if (m.sidemask & sf) {
1547                                                                 segment *seg = &Segments[new_segnum];
1548                 
1549                                                                 if (WALL_IS_DOORWAY(seg,sn) & WID_FLY_FLAG) {           //can explosion migrate through
1550                                                                         int child = seg->children[sn];
1551                                                                         int checknp;
1552                 
1553                                                                         for (checknp=list_pos;checknp--;)
1554                                                                                 if (Render_list[checknp] == child) {
1555 //mprintf((0,"mig from %d to %d ",new_segnum,child));
1556                                                                                         new_segnum = child;
1557                                                                                         list_pos = checknp;
1558                                                                                         did_migrate = 1;
1559                                                                                 }
1560                                                                 }
1561                                                         }
1562                                         }
1563         
1564                                 } while (0);    //while (did_migrate);
1565
1566                                 add_obj_to_seglist(objnum,list_pos);
1567         
1568                         }
1569
1570                 }
1571         }
1572
1573 //mprintf((0,"done build "));
1574
1575         //now that there's a list for each segment, sort the items in those lists
1576         for (nn=0;nn<n_segs;nn++) {
1577                 int segnum;
1578
1579                 segnum = Render_list[nn];
1580
1581 //mprintf((0,"nn=%d seg=%d ",nn,segnum));
1582
1583                 if (segnum != -1) {
1584                         int t,lookn,i,n;
1585
1586                         //first count the number of objects & copy into sort list
1587
1588                         lookn = nn;
1589                         i = n_sort_items = 0;
1590                         while ((t=render_obj_list[lookn][i++])!=-1)
1591                                 if (t<0)
1592                                         {lookn = -t; i=0;}
1593                                 else
1594                                         if (n_sort_items < SORT_LIST_SIZE-1) {          //add if room
1595                                                 sort_list[n_sort_items].objnum = t;
1596                                                 //NOTE: maybe use depth, not dist - quicker computation
1597                                                 sort_list[n_sort_items].dist = vm_vec_dist_quick(&Objects[t].pos,&Viewer_eye);
1598                                                 n_sort_items++;
1599                                         }
1600                                         else {                  //no room for object
1601                                                 int ii;
1602
1603                                                 #ifndef NDEBUG
1604                                                 FILE *tfile=fopen("sortlist.out","wt");
1605
1606                                                 //I find this strange, so I'm going to write out
1607                                                 //some information to look at later
1608                                                 if (tfile) {
1609                                                         for (ii=0;ii<SORT_LIST_SIZE;ii++) {
1610                                                                 int objnum = sort_list[ii].objnum;
1611
1612                                                                 fprintf(tfile,"Obj %3d  Type = %2d  Id = %2d  Dist = %08x  Segnum = %3d\n",
1613                                                                         objnum,Objects[objnum].type,Objects[objnum].id,sort_list[ii].dist,Objects[objnum].segnum);
1614                                                         }
1615                                                         fclose(tfile);
1616                                                 }
1617                                                 #endif
1618
1619                                                 Int3(); //Get Matt!!!
1620
1621                                                 //Now try to find a place for this object by getting rid
1622                                                 //of an object we don't care about
1623
1624                                                 for (ii=0;ii<SORT_LIST_SIZE;ii++) {
1625                                                         int objnum = sort_list[ii].objnum;
1626                                                         object *obj = &Objects[objnum];
1627                                                         int type = obj->type;
1628
1629                                                         //replace debris & fireballs
1630                                                         if (type == OBJ_DEBRIS || type == OBJ_FIREBALL) {
1631                                                                 fix dist = vm_vec_dist_quick(&Objects[t].pos,&Viewer_eye);
1632
1633                                                                 //don't replace same kind of object unless new 
1634                                                                 //one is closer
1635
1636                                                                 if (Objects[t].type != type || dist < sort_list[ii].dist) {
1637                                                                         sort_list[ii].objnum = t;
1638                                                                         sort_list[ii].dist = dist;
1639                                                                         break;
1640                                                                 }
1641                                                         }
1642                                                 }
1643
1644                                                 Int3(); //still couldn't find a slot
1645                                         }
1646
1647
1648                         //now call qsort
1649                 #if defined(__WATCOMC__) || defined(MACINTOSH)
1650                         qsort(sort_list,n_sort_items,sizeof(*sort_list),
1651                                    sort_func);
1652                 #else
1653                         qsort(sort_list,n_sort_items,sizeof(*sort_list),
1654                                         (int (*)(const void*,const void*))sort_func);
1655                 #endif  
1656
1657                         //now copy back into list
1658
1659                         lookn = nn;
1660                         i = 0;
1661                         n = n_sort_items;
1662                         while ((t=render_obj_list[lookn][i])!=-1 && n>0)
1663                                 if (t<0)
1664                                         {lookn = -t; i=0;}
1665                                 else
1666                                         render_obj_list[lookn][i++] = sort_list[--n].objnum;
1667                         render_obj_list[lookn][i] = -1; //mark (possibly new) end
1668                 }
1669         }
1670 }
1671
1672 int Use_player_head_angles = 0;
1673 vms_angvec Player_head_angles;
1674
1675 extern int Num_tmaps_drawn;
1676 extern int Total_pixels;
1677 //--unused-- int Total_num_tmaps_drawn=0;
1678
1679 int Rear_view=0;
1680 extern ubyte RenderingType;
1681
1682 void start_lighting_frame(object *viewer);
1683
1684 #ifdef JOHN_ZOOM
1685 fix Zoom_factor=F1_0;
1686 #endif
1687 //renders onto current canvas
1688 void render_frame(fix eye_offset, int window_num)
1689 {
1690         int start_seg_num;
1691
1692 //Total_num_tmaps_drawn += Num_tmaps_drawn;
1693 //if ((FrameCount > 0) && (Total_num_tmaps_drawn))
1694 //      mprintf((0, "Frame: %4i, total = %6i, Avg = %7.3f, Avgpix=%7.3f\n", Num_tmaps_drawn, Total_num_tmaps_drawn, (float) Total_num_tmaps_drawn/FrameCount, (float) Total_pixels/Total_num_tmaps_drawn));
1695 //Num_tmaps_drawn = 0;
1696
1697         if (Endlevel_sequence) {
1698                 render_endlevel_frame(eye_offset);
1699                 FrameCount++;
1700                 return;
1701         }
1702
1703 #ifdef NEWDEMO
1704         if ( Newdemo_state == ND_STATE_RECORDING && eye_offset >= 0 )   {
1705      
1706           //    mprintf ((0,"Objnum=%d objtype=%d objid=%d\n",Viewer-Objects,Viewer->type,Viewer->id));
1707                 
1708       if (RenderingType==0)
1709                 newdemo_record_start_frame(FrameCount, FrameTime );
1710       if (RenderingType!=255)
1711                 newdemo_record_viewer_object(Viewer);
1712         }
1713 #endif
1714   
1715    //Here:
1716
1717         start_lighting_frame(Viewer);           //this is for ugly light-smoothing hack
1718   
1719         g3_start_frame();
1720
1721         Viewer_eye = Viewer->pos;
1722
1723 //      if (Viewer->type == OBJ_PLAYER && (Cockpit_mode!=CM_REAR_VIEW))
1724 //              vm_vec_scale_add2(&Viewer_eye,&Viewer->orient.fvec,(Viewer->size*3)/4);
1725
1726         if (eye_offset) {
1727                 vm_vec_scale_add2(&Viewer_eye,&Viewer->orient.rvec,eye_offset);
1728         }
1729
1730         #ifdef EDITOR
1731         if (Function_mode==FMODE_EDITOR)
1732                 Viewer_eye = Viewer->pos;
1733         #endif
1734
1735         start_seg_num = find_point_seg(&Viewer_eye,Viewer->segnum);
1736
1737         if (start_seg_num==-1)
1738                 start_seg_num = Viewer->segnum;
1739
1740         if (Viewer==ConsoleObject && Use_player_head_angles) {
1741                 vms_matrix headm,viewm;
1742                 vm_angles_2_matrix(&headm,&Player_head_angles);
1743                 vm_matrix_x_matrix(&viewm,&Viewer->orient,&headm);
1744                 g3_set_view_matrix(&Viewer_eye,&viewm,Render_zoom);
1745         //@@} else if ((Cockpit_mode==CM_REAR_VIEW) && (Viewer==ConsoleObject)) {
1746         } else if (Rear_view && (Viewer==ConsoleObject)) {
1747                 vms_matrix headm,viewm;
1748                 Player_head_angles.p = Player_head_angles.b = 0;
1749                 Player_head_angles.h = 0x7fff;
1750                 vm_angles_2_matrix(&headm,&Player_head_angles);
1751                 vm_matrix_x_matrix(&viewm,&Viewer->orient,&headm);
1752                 g3_set_view_matrix(&Viewer_eye,&viewm,Render_zoom);
1753         } else  {
1754 #ifdef JOHN_ZOOM
1755                 if (keyd_pressed[KEY_RSHIFT] )  {
1756                         Zoom_factor += FrameTime*4;
1757                         if (Zoom_factor > F1_0*5 ) Zoom_factor=F1_0*5;
1758                 } else {
1759                         Zoom_factor -= FrameTime*4;
1760                         if (Zoom_factor < F1_0 ) Zoom_factor = F1_0;
1761                 }
1762                 g3_set_view_matrix(&Viewer_eye,&Viewer->orient,fixdiv(Render_zoom,Zoom_factor));
1763 #else
1764                 g3_set_view_matrix(&Viewer_eye,&Viewer->orient,Render_zoom);
1765 #endif
1766         }
1767
1768         if (Clear_window == 1) {
1769                 if (Clear_window_color == -1)
1770                         Clear_window_color = BM_XRGB(0, 0, 0);  //BM_XRGB(31, 15, 7);
1771                 gr_clear_canvas(Clear_window_color);
1772         }
1773         #ifndef NDEBUG
1774         if (Show_only_curside)
1775                 gr_clear_canvas(Clear_window_color);
1776         #endif
1777
1778         render_mine(start_seg_num, eye_offset, window_num);
1779
1780         if (Use_player_head_angles ) 
1781                 draw_3d_reticle(eye_offset);
1782
1783         g3_end_frame();
1784
1785    //RenderingType=0;
1786
1787         // -- Moved from here by MK, 05/17/95, wrong if multiple renders/frame! FrameCount++;           //we have rendered a frame
1788 }
1789
1790 int first_terminal_seg;
1791
1792 void update_rendered_data(int window_num, object *viewer, int rear_view_flag, int user)
1793 {
1794         Assert(window_num < MAX_RENDERED_WINDOWS);
1795         Window_rendered_data[window_num].frame = FrameCount;
1796         Window_rendered_data[window_num].viewer = viewer;
1797         Window_rendered_data[window_num].rear_view = rear_view_flag;
1798         Window_rendered_data[window_num].user = user;
1799 }
1800
1801 //build a list of segments to be rendered
1802 //fills in Render_list & N_render_segs
1803 void build_segment_list(int start_seg_num, int window_num)
1804 {
1805         int     lcnt,scnt,ecnt;
1806         int     l,c;
1807         int     ch;
1808
1809         memset(visited, 0, sizeof(visited[0])*(Highest_segment_index+1));
1810         memset(render_pos, -1, sizeof(render_pos[0])*(Highest_segment_index+1));
1811         //memset(no_render_flag, 0, sizeof(no_render_flag[0])*(MAX_RENDER_SEGS));
1812         memset(processed, 0, sizeof(processed));
1813
1814         #ifndef NDEBUG
1815         memset(visited2, 0, sizeof(visited2[0])*(Highest_segment_index+1));
1816         #endif
1817
1818         lcnt = scnt = 0;
1819
1820         Render_list[lcnt] = start_seg_num; visited[start_seg_num]=1;
1821         Seg_depth[lcnt] = 0;
1822         lcnt++;
1823         ecnt = lcnt;
1824         render_pos[start_seg_num] = 0;
1825
1826         #ifndef NDEBUG
1827         if (pre_draw_segs)
1828                 render_segment(start_seg_num, window_num);
1829         #endif
1830
1831         render_windows[0].left=render_windows[0].top=0;
1832         render_windows[0].right=grd_curcanv->cv_bitmap.bm_w-1;
1833         render_windows[0].bot=grd_curcanv->cv_bitmap.bm_h-1;
1834
1835         //breadth-first renderer
1836
1837         //build list
1838
1839         for (l=0;l<Render_depth;l++) {
1840
1841                 //while (scnt < ecnt) {
1842                 for (scnt=0;scnt < ecnt;scnt++) {
1843                         int rotated,segnum;
1844                         window *check_w;
1845                         short child_list[MAX_SIDES_PER_SEGMENT];                //list of ordered sides to process
1846                         int n_children;                                                                         //how many sides in child_list
1847                         segment *seg;
1848
1849                         if (processed[scnt])
1850                                 continue;
1851
1852                         processed[scnt]=1;
1853
1854                         segnum = Render_list[scnt];
1855                         check_w = &render_windows[scnt];
1856
1857                         #ifndef NDEBUG
1858                         if (draw_boxes)
1859                                 draw_window_box(RED,check_w->left,check_w->top,check_w->right,check_w->bot);
1860                         #endif
1861
1862                         if (segnum == -1) continue;
1863
1864                         seg = &Segments[segnum];
1865                         rotated=0;
1866
1867                         //look at all sides of this segment.
1868                         //tricky code to look at sides in correct order follows
1869
1870                         for (c=n_children=0;c<MAX_SIDES_PER_SEGMENT;c++) {              //build list of sides
1871                                 int wid;
1872
1873                                 wid = WALL_IS_DOORWAY(seg, c);
1874
1875                                 ch=seg->children[c];
1876
1877                                 if ( (window_check || !visited[ch]) && (wid & WID_RENDPAST_FLAG) ) {
1878                                         if (behind_check) {
1879                                                 sbyte *sv = Side_to_verts[c];
1880                                                 ubyte codes_and=0xff;
1881                                                 int i;
1882
1883                                                 rotate_list(8,seg->verts);
1884                                                 rotated=1;
1885
1886                                                 for (i=0;i<4;i++)
1887                                                         codes_and &= Segment_points[seg->verts[sv[i]]].p3_codes;
1888
1889                                                 if (codes_and & CC_BEHIND) continue;
1890
1891                                         }
1892                                         child_list[n_children++] = c;
1893                                 }
1894                         }
1895
1896                         //now order the sides in some magical way
1897
1898                         if (new_seg_sorting)
1899                                 sort_seg_children(seg,n_children,child_list);
1900
1901                         //for (c=0;c<MAX_SIDES_PER_SEGMENT;c++) {
1902                         //      ch=seg->children[c];
1903
1904                         for (c=0;c<n_children;c++) {
1905                                 int siden;
1906
1907                                 siden = child_list[c];
1908                                 ch=seg->children[siden];
1909                                 //if ( (window_check || !visited[ch])&& (WALL_IS_DOORWAY(seg, c))) {
1910                                 {
1911                                         if (window_check) {
1912                                                 int i;
1913                                                 ubyte codes_and_3d,codes_and_2d;
1914                                                 short _x,_y,min_x=32767,max_x=-32767,min_y=32767,max_y=-32767;
1915                                                 int no_proj_flag=0;     //a point wasn't projected
1916
1917                                                 if (rotated<2) {
1918                                                         if (!rotated)
1919                                                                 rotate_list(8,seg->verts);
1920                                                         project_list(8,seg->verts);
1921                                                         rotated=2;
1922                                                 }
1923
1924                                                 for (i=0,codes_and_3d=codes_and_2d=0xff;i<4;i++) {
1925                                                         int p = seg->verts[Side_to_verts[siden][i]];
1926                                                         g3s_point *pnt = &Segment_points[p];
1927
1928                                                         if (! (pnt->p3_flags&PF_PROJECTED)) {no_proj_flag=1; break;}
1929
1930                                                         _x = f2i(pnt->p3_sx);
1931                                                         _y = f2i(pnt->p3_sy);
1932
1933                                                         codes_and_3d &= pnt->p3_codes;
1934                                                         codes_and_2d &= code_window_point(_x,_y,check_w);
1935
1936                                                         #ifndef NDEBUG
1937                                                         if (draw_edges) {
1938                                                                 gr_setcolor(BM_XRGB(31,0,31));
1939                                                                 gr_line(pnt->p3_sx,pnt->p3_sy,
1940                                                                         Segment_points[seg->verts[Side_to_verts[siden][(i+1)%4]]].p3_sx,
1941                                                                         Segment_points[seg->verts[Side_to_verts[siden][(i+1)%4]]].p3_sy);
1942                                                         }
1943                                                         #endif
1944
1945                                                         if (_x < min_x) min_x = _x;
1946                                                         if (_x > max_x) max_x = _x;
1947
1948                                                         if (_y < min_y) min_y = _y;
1949                                                         if (_y > max_y) max_y = _y;
1950
1951                                                 }
1952
1953                                                 #ifndef NDEBUG
1954                                                 if (draw_boxes)
1955                                                         draw_window_box(WHITE,min_x,min_y,max_x,max_y);
1956                                                 #endif
1957
1958                                                 if (no_proj_flag || (!codes_and_3d && !codes_and_2d)) { //maybe add this segment
1959                                                         int rp = render_pos[ch];
1960                                                         window *new_w = &render_windows[lcnt];
1961
1962                                                         if (no_proj_flag) *new_w = *check_w;
1963                                                         else {
1964                                                                 new_w->left  = max(check_w->left,min_x);
1965                                                                 new_w->right = min(check_w->right,max_x);
1966                                                                 new_w->top   = max(check_w->top,min_y);
1967                                                                 new_w->bot   = min(check_w->bot,max_y);
1968                                                         }
1969
1970                                                         //see if this seg already visited, and if so, does current window
1971                                                         //expand the old window?
1972                                                         if (rp != -1) {
1973                                                                 if (new_w->left < render_windows[rp].left ||
1974                                                                                  new_w->top < render_windows[rp].top ||
1975                                                                                  new_w->right > render_windows[rp].right ||
1976                                                                                  new_w->bot > render_windows[rp].bot) {
1977
1978                                                                         new_w->left  = min(new_w->left,render_windows[rp].left);
1979                                                                         new_w->right = max(new_w->right,render_windows[rp].right);
1980                                                                         new_w->top   = min(new_w->top,render_windows[rp].top);
1981                                                                         new_w->bot   = max(new_w->bot,render_windows[rp].bot);
1982
1983                                                                         if (no_migrate_segs) {
1984                                                                                 //no_render_flag[lcnt] = 1;
1985                                                                                 Render_list[lcnt] = -1;
1986                                                                                 render_windows[rp] = *new_w;            //get updated window
1987                                                                                 processed[rp] = 0;              //force reprocess
1988                                                                                 goto no_add;
1989                                                                         }
1990                                                                         else
1991                                                                                 Render_list[rp]=-1;
1992                                                                 }
1993                                                                 else goto no_add;
1994                                                         }
1995
1996                                                         #ifndef NDEBUG
1997                                                         if (draw_boxes)
1998                                                                 draw_window_box(5,new_w->left,new_w->top,new_w->right,new_w->bot);
1999                                                         #endif
2000
2001                                                         render_pos[ch] = lcnt;
2002                                                         Render_list[lcnt] = ch;
2003                                                         Seg_depth[lcnt] = l;
2004                                                         lcnt++;
2005                                                         if (lcnt >= MAX_RENDER_SEGS) {mprintf((0,"Too many segs in render list!!\n")); goto done_list;}
2006                                                         visited[ch] = 1;
2007
2008                                                         #ifndef NDEBUG
2009                                                         if (pre_draw_segs)
2010                                                                 render_segment(ch, window_num);
2011                                                         #endif
2012 no_add:
2013         ;
2014
2015                                                 }
2016                                         }
2017                                         else {
2018                                                 Render_list[lcnt] = ch;
2019                                                 Seg_depth[lcnt] = l;
2020                                                 lcnt++;
2021                                                 if (lcnt >= MAX_RENDER_SEGS) {mprintf((0,"Too many segs in render list!!\n")); goto done_list;}
2022                                                 visited[ch] = 1;
2023                                         }
2024                                 }
2025                         }
2026                 }
2027
2028                 scnt = ecnt;
2029                 ecnt = lcnt;
2030
2031         }
2032 done_list:
2033
2034         lcnt_save = lcnt;
2035         scnt_save = scnt;
2036
2037         first_terminal_seg = scnt;
2038         N_render_segs = lcnt;
2039
2040 }
2041
2042 //renders onto current canvas
2043 void render_mine(int start_seg_num,fix eye_offset, int window_num)
2044 {
2045 #ifndef NDEBUG
2046         int             i;
2047 #endif
2048         int             nn;
2049
2050         //      Initialize number of objects (actually, robots!) rendered this frame.
2051         Window_rendered_data[window_num].num_objects = 0;
2052
2053 #ifdef LASER_HACK
2054         Hack_nlasers = 0;
2055 #endif
2056
2057         #ifndef NDEBUG
2058         for (i=0;i<=Highest_object_index;i++)
2059                 object_rendered[i] = 0;
2060         #endif
2061
2062         //set up for rendering
2063
2064         render_start_frame();
2065
2066
2067         #if defined(EDITOR)
2068         if (Show_only_curside) {
2069                 rotate_list(8,Cursegp->verts);
2070                 render_side(Cursegp,Curside);
2071                 goto done_rendering;
2072         }
2073         #endif
2074
2075
2076         #ifdef EDITOR
2077         if (_search_mode)       {
2078                 //lcnt = lcnt_save;
2079                 //scnt = scnt_save;
2080         }
2081         else
2082         #endif
2083                 //NOTE LINK TO ABOVE!!
2084                 build_segment_list(start_seg_num, window_num);          //fills in Render_list & N_render_segs
2085
2086         //render away
2087
2088         #ifndef NDEBUG
2089         if (!window_check) {
2090                 Window_clip_left  = Window_clip_top = 0;
2091                 Window_clip_right = grd_curcanv->cv_bitmap.bm_w-1;
2092                 Window_clip_bot   = grd_curcanv->cv_bitmap.bm_h-1;
2093         }
2094         #endif
2095
2096         #ifndef NDEBUG
2097         if (!(_search_mode)) {
2098                 int i;
2099
2100                 for (i=0;i<N_render_segs;i++) {
2101                         int segnum;
2102
2103                         segnum = Render_list[i];
2104
2105                         if (segnum != -1)
2106                         {
2107                                 if (visited2[segnum])
2108                                         Int3();         //get Matt
2109                                 else
2110                                         visited2[segnum] = 1;
2111                         }
2112                 }
2113         }
2114         #endif
2115
2116         if (!(_search_mode))
2117                 build_object_lists(N_render_segs);
2118
2119         if (eye_offset<=0)              // Do for left eye or zero.
2120                 set_dynamic_light();
2121
2122         if (!_search_mode && Clear_window == 2) {
2123                 if (first_terminal_seg < N_render_segs) {
2124                         int i;
2125
2126                         if (Clear_window_color == -1)
2127                                 Clear_window_color = BM_XRGB(0, 0, 0);  //BM_XRGB(31, 15, 7);
2128         
2129                         gr_setcolor(Clear_window_color);
2130         
2131                         for (i=first_terminal_seg; i<N_render_segs; i++) {
2132                                 if (Render_list[i] != -1) {
2133                                         #ifndef NDEBUG
2134                                         if ((render_windows[i].left == -1) || (render_windows[i].top == -1) || (render_windows[i].right == -1) || (render_windows[i].bot == -1))
2135                                                 Int3();
2136                                         else
2137                                         #endif
2138                                                 //NOTE LINK TO ABOVE!
2139                                                 gr_rect(render_windows[i].left, render_windows[i].top, render_windows[i].right, render_windows[i].bot);
2140                                 }
2141                         }
2142                 }
2143         }
2144
2145         for (nn=N_render_segs;nn--;) {
2146                 int segnum;
2147                 int objnp;
2148
2149                 // Interpolation_method = 0;
2150                 segnum = Render_list[nn];
2151                 Current_seg_depth = Seg_depth[nn];
2152
2153                 //if (!no_render_flag[nn])
2154                 if (segnum!=-1 && (_search_mode || visited[segnum]!=255)) {
2155                         //set global render window vars
2156
2157                         if (window_check) {
2158                                 Window_clip_left  = render_windows[nn].left;
2159                                 Window_clip_top   = render_windows[nn].top;
2160                                 Window_clip_right = render_windows[nn].right;
2161                                 Window_clip_bot   = render_windows[nn].bot;
2162                         }
2163
2164                         //mprintf((0," %d",segnum));
2165
2166                         render_segment(segnum, window_num);
2167                         visited[segnum]=255;
2168
2169                         if (window_check) {             //reset for objects
2170                                 Window_clip_left  = Window_clip_top = 0;
2171                                 Window_clip_right = grd_curcanv->cv_bitmap.bm_w-1;
2172                                 Window_clip_bot   = grd_curcanv->cv_bitmap.bm_h-1;
2173                         }
2174
2175                         if (migrate_objects) {
2176                                 //int n_expl_objs=0,expl_objs[5],i;
2177                                 int listnum;
2178                                 int save_linear_depth = Max_linear_depth;
2179
2180                                 Max_linear_depth = Max_linear_depth_objects;
2181
2182                                 listnum = nn;
2183
2184                                 //mprintf((0,"render objs seg %d",segnum));
2185
2186                                 for (objnp=0;render_obj_list[listnum][objnp]!=-1;)      {
2187                                         int ObjNumber = render_obj_list[listnum][objnp];
2188
2189                                         if (ObjNumber >= 0) {
2190
2191                                                 //mprintf( (0, "Type: %d\n", Objects[ObjNumber].type ));
2192         
2193                                                 //if (Objects[ObjNumber].type == OBJ_FIREBALL && n_expl_objs<5) {
2194                                                 //      expl_objs[n_expl_objs++] = ObjNumber;
2195                                                 //} else
2196                                                 #ifdef LASER_HACK
2197                                                 if (    (Objects[ObjNumber].type==OBJ_WEAPON) &&                                                                //if its a weapon
2198                                                                 (Objects[ObjNumber].lifeleft==Laser_max_time ) &&       //  and its in it's first frame
2199                                                                 (Hack_nlasers< MAX_HACKED_LASERS) &&                                                                    //  and we have space for it
2200                                                                 (Objects[ObjNumber].laser_info.parent_num>-1) &&                                        //  and it has a parent
2201                                                                 ((Viewer-Objects)==Objects[ObjNumber].laser_info.parent_num)    //  and it's parent is the viewer
2202                                                    )            {
2203                                                         Hack_laser_list[Hack_nlasers++] = ObjNumber;                                                            //then make it draw after everything else.
2204                                                         //mprintf( (0, "O%d ", ObjNumber ));
2205                                                 } else  
2206                                                 #endif
2207                                                         do_render_object(ObjNumber, window_num);        // note link to above else
2208
2209                                                 objnp++;
2210                                         }
2211                                         else {
2212
2213                                                 listnum = -ObjNumber;
2214                                                 objnp = 0;
2215
2216                                         }
2217
2218                                 }
2219
2220                                 //for (i=0;i<n_expl_objs;i++)
2221                                 //      do_render_object(expl_objs[i], window_num);
2222
2223                                 //mprintf((0,"done seg %d\n",segnum));
2224
2225                                 Max_linear_depth = save_linear_depth;
2226
2227                         }
2228
2229                 }
2230         }
2231
2232         //mprintf((0,"\n"));
2233
2234                                                                 
2235 #ifdef LASER_HACK                                                               
2236         // Draw the hacked lasers last
2237         for (i=0; i < Hack_nlasers; i++ )       {
2238                 //mprintf( (0, "D%d ", Hack_laser_list[i] ));
2239                 do_render_object(Hack_laser_list[i], window_num);
2240         }
2241 #endif
2242
2243         // -- commented out by mk on 09/14/94...did i do a good thing??  object_render_targets();
2244
2245 #ifdef EDITOR
2246         #ifndef NDEBUG
2247         //draw curedge stuff
2248         if (Outline_mode) outline_seg_side(Cursegp,Curside,Curedge,Curvert);
2249         #endif
2250
2251 done_rendering:
2252         ;
2253
2254 #endif
2255
2256 }
2257 #ifdef EDITOR
2258
2259 extern int render_3d_in_big_window;
2260
2261 //finds what segment is at a given x&y -  seg,side,face are filled in
2262 //works on last frame rendered. returns true if found
2263 //if seg<0, then an object was found, and the object number is -seg-1
2264 int find_seg_side_face(short x,short y,int *seg,int *side,int *face,int *poly)
2265 {
2266         _search_mode = -1;
2267
2268         _search_x = x; _search_y = y;
2269
2270         found_seg = -1;
2271
2272         if (render_3d_in_big_window) {
2273                 grs_canvas temp_canvas;
2274
2275                 gr_init_sub_canvas(&temp_canvas,canv_offscreen,0,0,
2276                         LargeView.ev_canv->cv_bitmap.bm_w,LargeView.ev_canv->cv_bitmap.bm_h);
2277
2278                 gr_set_current_canvas(&temp_canvas);
2279
2280                 render_frame(0, 0);
2281         }
2282         else {
2283                 gr_set_current_canvas(&VR_render_sub_buffer[0]);        //render off-screen
2284                 render_frame(0, 0);
2285         }
2286
2287         _search_mode = 0;
2288
2289         *seg = found_seg;
2290         *side = found_side;
2291         *face = found_face;
2292         *poly = found_poly;
2293
2294 //      mprintf((0,"found seg=%d, side=%d, face=%d, poly=%d\n",found_seg,found_side,found_face,found_poly));
2295
2296         return (found_seg!=-1);
2297
2298 }
2299
2300 #endif