download gl_rsurf.c
Language: C
License: GPL
Copyright: (C) 2000 Joseph Carter (C) 1996-1997 Id Software, Inc.
LOC: 892
Project Info
QuakeForge(quake)
Server: SourceForge
Type: cvs
...ake\quake\newtree32\source\
   .cvsignore
   .gdbinit
   .indent.pro
   buildnum.c
   cd_dos.c
   cd_linux.c
   cd_null.c
   cd_sdl.c
   cd_sgi.c
   cd_win.c
   checksum.c
   cl_cam.c
   cl_cmd.c
   cl_cvar.c
   cl_demo.c
   cl_ents.c
   cl_input.c
   cl_main.c
   cl_misc.c
   cl_parse.c
   cl_pred.c
   cl_slist.c
   cl_sys_sdl.c
   cl_sys_unix.c
   cl_sys_win.c
   cl_tent.c
   cmd.c
   com.c
   console.c
   context_x11.c
   crc.c
   cvar.c
   d_edge.c
   d_fill.c
   d_init.c
   d_modech.c
   d_part.c
   d_polyse.c
   d_scan.c
   d_sky.c
   d_sprite.c
   d_surf.c
   d_vars.c
   d_zpoint.c
   dga_check.c
   dirent.c
   draw.c
   fbset.c
   fbset_modes_y.y
   fnmatch.c
   fractalnoise.c
   gl_draw.c
   gl_dyn_fires.c
   gl_dyn_part.c
   gl_dyn_textures.c
   gl_mesh.c
   gl_model_alias.c
   gl_model_brush.c
   gl_model_fullbright.c
   gl_model_sprite.c
   gl_ngraph.c
   gl_rlight.c
   gl_rmain.c
   gl_rmisc.c
   gl_rsurf.c
   gl_screen.c
   gl_skin.c
   gl_sky.c
   gl_sky_clip.c
   gl_view.c
   gl_warp.c
   hash.c
   in_fbdev.c
   in_ggi.c
   in_null.c
   in_sdl.c
   in_svgalib.c
   in_win.c
   in_x11.c
   info.c
   joy_linux.c
   joy_null.c
   joy_win.c
   keys.c
   link.c
   locs.c
   Makefile.am
   makefile.mgw
   makefile.win
   mathlib.c
   mdfour.c
   menu.c
   model.c
   model_alias.c
   model_brush.c
   model_sprite.c
   msg.c
   net_chan.c
   net_com.c
   net_packetlog.c
   net_udp.c
   net_udp6.c
   nonintel.c
   pcx.c
   pmove.c
   pmovetst.c
   pr_edict.c
   pr_exec.c
   pr_offs.c
   qargs.c
   qendian.c
   qfgl_ext.c
   quakefs.c
   quakeio.c
   r_aclip.c
   r_alias.c
   r_bsp.c
   r_draw.c
   r_edge.c
   r_efrag.c
   r_light.c
   r_main.c
   r_misc.c
   r_part.c
   r_sky.c
   r_sprite.c
   r_surf.c
   r_vars.c
   r_view.c
   sbar.c
   screen.c
   sizebuf.c
   skin.c
   snd_alsa_0_5.c
   snd_alsa_0_6.c
   snd_disk.c
   snd_dma.c
   snd_mem.c
   snd_mix.c
   snd_null.c
   snd_oss.c
   snd_sdl.c
   snd_sgi.c
   snd_sun.c
   snd_win.c
   sv_ccmds.c
   sv_cvar.c
   sv_ents.c
   sv_init.c
   sv_main.c
   sv_misc.c
   sv_model.c
   sv_move.c
   sv_nchan.c
   sv_phys.c
   sv_pr_cmds.c
   sv_progs.c
   sv_send.c
   sv_sys_unix.c
   sv_sys_win.c
   sv_user.c
   sw_model_alias.c
   sw_model_brush.c
   sw_model_sprite.c
   sw_skin.c
   sw_view.c
   sys_null.c
   sys_unix.c
   sys_win.c
   teamplay.c
   tga.c
   va.c
   ver_check.c
   vid.c
   vid_3dfxsvga.c
   vid_common_gl.c
   vid_fbdev.c
   vid_ggi.c
   vid_glx.c
   vid_mgl.c
   vid_null.c
   vid_sdl.c
   vid_sgl.c
   vid_svgalib.c
   vid_wgl.c
   vid_win.c
   vid_x11.c
   wad.c
   world.c
   zone.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
/*
	gl_rsurf.c

	surface-related refresh code

	Copyright (C) 1996-1997  Id Software, Inc.
	Copyright (C) 2000       Joseph Carter <knghtbrd@debian.org>

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

	See the GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to:

		Free Software Foundation, Inc.
		59 Temple Place - Suite 330
		Boston, MA  02111-1307, USA

	$Id: gl_rsurf.c,v 1.1.1.1 2001/03/06 09:33:59 lordhavoc Exp $
*/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#ifdef HAVE_STRING_H
# include <string.h>
#endif
#ifdef HAVE_STRINGS_H
# include <strings.h>
#endif

#include <math.h>
#include <stdio.h>

#include "glquake.h"
#include "sys.h"

qboolean    r_cache_thrash;

extern double realtime;
int         skytexturenum;

extern vec3_t shadecolor;				// Ender (Extend) Colormod
int         lightmap_bytes;				// 1 or 3

int         lightmap_textures;

unsigned int blocklights[18 * 18 * 3];

cvar_t     *gl_colorlights;

#define	BLOCK_WIDTH		128
#define	BLOCK_HEIGHT	128

// LordHavoc: since lightmaps are now allocated only as needed, allow a ridiculous number :)
#define	MAX_LIGHTMAPS	1024
int         active_lightmaps;

typedef struct glRect_s {
	unsigned char l, t, w, h;
} glRect_t;

glpoly_t   *lightmap_polys[MAX_LIGHTMAPS];
glpoly_t   *fullbright_polys[MAX_GLTEXTURES];
qboolean    lightmap_modified[MAX_LIGHTMAPS];
glRect_t    lightmap_rectchange[MAX_LIGHTMAPS];

int         allocated[MAX_LIGHTMAPS][BLOCK_WIDTH];

// the lightmap texture data needs to be kept in
// main memory so texsubimage can update properly
// LordHavoc: changed to be allocated at runtime (typically lower memory usage)
byte       *lightmaps[MAX_LIGHTMAPS];

msurface_t *waterchain = NULL;
msurface_t *sky_chain;

extern qboolean lighthalf;

// LordHavoc: place for gl_rsurf setup code
void
glrsurf_init (void)
{
	memset (&lightmaps, 0, sizeof (lightmaps));
}

void
R_RecursiveLightUpdate (mnode_t *node)
{
	int         c;
	msurface_t *surf;

	if (node->children[0]->contents >= 0)
		R_RecursiveLightUpdate (node->children[0]);
	if (node->children[1]->contents >= 0)
		R_RecursiveLightUpdate (node->children[1]);
	if ((c = node->numsurfaces))
		for (surf = cl.worldmodel->surfaces + node->firstsurface; c;
			 c--, surf++) surf->cached_dlight = true;
}

// LordHavoc: function to force all lightmaps to be updated
void
R_ForceLightUpdate (void)
{
	if (cl.worldmodel && cl.worldmodel->nodes
		&& cl.worldmodel->nodes->contents >= 0)
		R_RecursiveLightUpdate (cl.worldmodel->nodes);
}

/*
	R_AddDynamicLights

	LordHavoc: completely rewrote this, relies on 64bit integer math...
*/
int         dlightdivtable[8192];
int         dlightdivtableinitialized = 0;

/*
	R_AddDynamicLights

	NOTE! LordHavoc was here, and it shows... (Mercury)
*/
void
R_AddDynamicLights (msurface_t *surf)
{
	int         sdtable[18], lnum, td, maxdist, maxdist2, maxdist3, i, s, t,
		smax, tmax, red, green, blue, j;
	unsigned int *bl;
	float       dist, f;
	vec3_t      impact, local;

	// use 64bit integer...  shame it's not very standardized...
#if _MSC_VER || __BORLANDC__
	__int64     k;
#else
	long long   k;
#endif

	if (!dlightdivtableinitialized) {
		dlightdivtable[0] = 1048576 >> 7;
		for (s = 1; s < 8192; s++)
			dlightdivtable[s] = 1048576 / (s << 7);
		dlightdivtableinitialized = 1;
	}

	smax = (surf->extents[0] >> 4) + 1;
	tmax = (surf->extents[1] >> 4) + 1;

	for (lnum = 0; lnum < MAX_DLIGHTS; lnum++) {
		if (!(surf->dlightbits & (1 << lnum)))
			continue;					// not lit by this light

		VectorSubtract (cl_dlights[lnum].origin, currententity->origin, local);
		dist = DotProduct (local, surf->plane->normal) - surf->plane->dist;
		for (i = 0; i < 3; i++)
			impact[i] =
				cl_dlights[lnum].origin[i] - surf->plane->normal[i] * dist;

		i = f =	DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0];

		// reduce calculations
		t = dist * dist;
		for (s = 0; s < smax; s++, i -= 16)
			sdtable[s] = i * i + t;

		i = f = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1];

		// for comparisons to minimum acceptable light
		maxdist = (int) ((cl_dlights[lnum].radius * cl_dlights[lnum].radius) * 0.75);

		// clamp radius to avoid exceeding 8192 entry division table
		if (maxdist > 1048576)
			maxdist = 1048576;
		maxdist3 = maxdist - (int) (dist * dist);

		// convert to 8.8 blocklights format
		red = f = cl_dlights[lnum].color[0] * maxdist;
		green = f = cl_dlights[lnum].color[1] * maxdist;
		blue = f = cl_dlights[lnum].color[2] * maxdist;
		bl = blocklights;
		for (t = 0; t < tmax; t++, i -= 16) {
			td = i * i;
			if (td < maxdist3) {	// make sure some part of it is visible on this line
				maxdist2 = maxdist - td;
				for (s = 0; s < smax; s++) {
					if (sdtable[s] < maxdist2) {
						j = dlightdivtable[(sdtable[s] + td) >> 7];
						bl[0] += (k = (red * j) >> 7);
						bl[1] += (k = (green * j) >> 7);
						bl[2] += (k = (blue * j) >> 7);
					}
					bl += 3;
				}
			} else
				bl += smax * 3;			// skip line
		}
	}
}

/*
	R_BuildLightMap

	Combine and scale multiple lightmaps
	After talking it over with LordHavoc, I've decided to switch to using
	 GL_RGB for colored lights and averaging them out for plain white
	 lighting if needed.  Much cleaner that way.  --KB
*/
void
R_BuildLightMap (msurface_t *surf, byte * dest, int stride)
{
	int         smax, tmax;
	int         t;
	int         i, j, size;
	byte       *lightmap;
	unsigned int scale;
	int         maps;
	float       t2;
	unsigned int *bl;

	surf->cached_dlight = (surf->dlightframe == r_framecount);

	smax = (surf->extents[0] >> 4) + 1;
	tmax = (surf->extents[1] >> 4) + 1;
	size = smax * tmax;
	lightmap = surf->samples;

	// set to full bright if no light data
	if (!cl.worldmodel->lightdata) {
		bl = blocklights;
		for (i = 0; i < size; i++) {
			*bl++ = 255 << 8;
			*bl++ = 255 << 8;
			*bl++ = 255 << 8;
		}
		goto store;
	}
	// clear to no light
	bl = blocklights;
	for (i = 0; i < size; i++) {
		*bl++ = 0;
		*bl++ = 0;
		*bl++ = 0;
	}
	bl = blocklights;

	// add all the lightmaps
	if (lightmap) {
		for (maps = 0; maps < MAXLIGHTMAPS && surf->styles[maps] != 255; maps++) {
			scale = d_lightstylevalue[surf->styles[maps]];
			surf->cached_light[maps] = scale;	// 8.8 fraction
			bl = blocklights;
			for (i = 0; i < size; i++) {
				*bl++ += *lightmap++ * scale;
				*bl++ += *lightmap++ * scale;
				*bl++ += *lightmap++ * scale;
			}
		}
	}
	// add all the dynamic lights
	if (surf->dlightframe == r_framecount)
		R_AddDynamicLights (surf);

  store:
	// bound and shift
	if (gl_colorlights->int_val) {
		stride -= smax * 3;
		bl = blocklights;
		if (lighthalf) {
			for (i = 0; i < tmax; i++, dest += stride) {
				for (j = 0; j < smax; j++) {
					t = (int) *bl++ >> 8;
					*dest++ = bound (0, t, 255);
					t = (int) *bl++ >> 8;
					*dest++ = bound (0, t, 255);
					t = (int) *bl++ >> 8;
					*dest++ = bound (0, t, 255);
				}
			}
		} else {
			for (i = 0; i < tmax; i++, dest += stride) {
				for (j = 0; j < smax; j++) {
					t = (int) *bl++ >> 7;
					*dest++ = bound (0, t, 255);
					t = (int) *bl++ >> 7;
					*dest++ = bound (0, t, 255);
					t = (int) *bl++ >> 7;
					*dest++ = bound (0, t, 255);
				}
			}
		}
	} else {
		stride -= smax;
		bl = blocklights;
		if (lighthalf) {
			for (i = 0; i < tmax; i++, dest += stride) {
				for (j = 0; j < smax; j++) {
					t = (int) *bl++ >> 8;
					t2 = bound (0, t, 255);
					t = (int) *bl++ >> 8;
					t2 += bound (0, t, 255);
					t = (int) *bl++ >> 8;
					t2 += bound (0, t, 255);
					t2 *= (1.0 / 3.0);
					*dest++ = t2;
				}
			}
		} else {
			for (i = 0; i < tmax; i++, dest += stride) {
				for (j = 0; j < smax; j++) {
					t = (int) *bl++ >> 7;
					t2 = bound (0, t, 255);
					t = (int) *bl++ >> 7;
					t2 += bound (0, t, 255);
					t = (int) *bl++ >> 7;
					t2 += bound (0, t, 255);
					t2 *= (1.0 / 3.0);
					*dest++ = t2;
				}
			}
		}
	}
}

/*
	R_TextureAnimation

	Returns the proper texture for a given time and base texture
*/
texture_t  *
R_TextureAnimation (texture_t *base)
{
	int         relative;
	int         count;

	if (currententity->frame) {
		if (base->alternate_anims)
			base = base->alternate_anims;
	}

	if (!base->anim_total)
		return base;

	relative = (int) (cl.time * 10) % base->anim_total;

	count = 0;
	while (base->anim_min > relative || base->anim_max <= relative) {
		base = base->anim_next;
		if (!base)
			Sys_Error ("R_TextureAnimation: broken cycle");
		if (++count > 100)
			Sys_Error ("R_TextureAnimation: infinite cycle");
	}

	return base;
}


/*
	BRUSH MODELS
*/


extern int  solidskytexture;
extern int  alphaskytexture;
extern float speedscale;				// for top sky and bottom sky

QF_glActiveTextureARB	qglActiveTexture = NULL;
QF_glMultiTexCoord2fARB qglMultiTexCoord2f = NULL;

void
GL_UploadLightmap (int i, int x, int y, int w, int h)
{
	glTexSubImage2D (GL_TEXTURE_2D, 0, 0, y, BLOCK_WIDTH, h, gl_lightmap_format,
					 GL_UNSIGNED_BYTE,
					 lightmaps[i] + (y * BLOCK_WIDTH) * lightmap_bytes);
}

/*
	R_DrawSequentialPoly

	Systems that have fast state and texture changes can
	just do everything as it passes with no need to sort
*/
void
R_DrawMultitexturePoly (msurface_t *s)
{
	int         maps;
	float      *v;
	int         i;
	texture_t  *texture = R_TextureAnimation (s->texinfo->texture);

	c_brush_polys++;

	i = s->lightmaptexturenum;

	glColor3f (1, 1, 1);
	// Binds world to texture env 0
	qglActiveTexture (gl_mtex_enum + 0);
	glBindTexture (GL_TEXTURE_2D, texture->gl_texturenum);
	glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
	glEnable (GL_TEXTURE_2D);
	// Binds lightmap to texenv 1
	qglActiveTexture (gl_mtex_enum + 1);
	glBindTexture (GL_TEXTURE_2D, lightmap_textures + i);
	glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glEnable (GL_TEXTURE_2D);

	// check for lightmap modification
	if (r_dynamic->int_val) {
		for (maps = 0; maps < MAXLIGHTMAPS && s->styles[maps] != 255; maps++)
			if (d_lightstylevalue[s->styles[maps]] != s->cached_light[maps])
				goto dynamic;

		if (s->dlightframe == r_framecount	// dynamic this frame
			|| s->cached_dlight)		// dynamic previously
		{
		  dynamic:
			R_BuildLightMap (s,
							 lightmaps[s->lightmaptexturenum] +
							 (s->light_t * BLOCK_WIDTH +
							  s->light_s) * lightmap_bytes,
							 BLOCK_WIDTH * lightmap_bytes);
			GL_UploadLightmap (i, s->light_s, s->light_t,
							   (s->extents[0] >> 4) + 1,
							   (s->extents[1] >> 4) + 1);
		}
	}

	glBegin (GL_POLYGON);
	v = s->polys->verts[0];
	for (i = 0; i < s->polys->numverts; i++, v += VERTEXSIZE) {
		qglMultiTexCoord2f (gl_mtex_enum + 0, v[3], v[4]);
		qglMultiTexCoord2f (gl_mtex_enum + 1, v[5], v[6]);
		glVertex3fv (v);
	}
	glEnd ();
	glDisable (GL_TEXTURE_2D);
	qglActiveTexture (gl_mtex_enum + 0);
	glEnable (GL_TEXTURE_2D);

	if (texture->gl_fb_texturenum > 0) {
		s->polys->fb_chain = fullbright_polys[texture->gl_fb_texturenum];
		fullbright_polys[texture->gl_fb_texturenum] = s->polys;
	}
	glColor3ubv (lighthalf_v);
	glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
}

/*
	R_BlendLightmaps
*/
void
R_BlendLightmaps (void)
{
	int         i, j;
	glpoly_t   *p;
	float      *v;

	glDepthMask (GL_FALSE);				// don't bother writing Z

	glBlendFunc (GL_ZERO, GL_SRC_COLOR);
	glColor3f (1, 1, 1);

	for (i = 0; i < MAX_LIGHTMAPS; i++) {
		p = lightmap_polys[i];
		if (!p)
			continue;
		glBindTexture (GL_TEXTURE_2D, lightmap_textures + i);
		if (lightmap_modified[i]) {
			GL_UploadLightmap (i, lightmap_rectchange[i].l,
							   lightmap_rectchange[i].t,
							   lightmap_rectchange[i].w,
							   lightmap_rectchange[i].h);
			lightmap_modified[i] = false;
		}
		for (; p; p = p->chain) {
			glBegin (GL_POLYGON);
			v = p->verts[0];
			for (j = 0; j < p->numverts; j++, v += VERTEXSIZE) {
				glTexCoord2fv (&v[5]);
				glVertex3fv (v);
			}
			glEnd ();
		}
	}

	// Return to normal blending  --KB
	glColor3ubv (lighthalf_v);
	glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glDepthMask (GL_TRUE);				// back to normal Z buffering
}

/*
	R_RenderFullbrights
*/

void
R_RenderFullbrights (void)
{
	int         i, j;
	glpoly_t   *p;
	float      *v;

	glBlendFunc (GL_ONE, GL_ONE);

	for (i = 1; i < MAX_GLTEXTURES; i++) {
		if (!fullbright_polys[i])
			continue;
		glBindTexture (GL_TEXTURE_2D, i);
		for (p = fullbright_polys[i]; p; p = p->fb_chain) {
			glBegin (GL_POLYGON);
			for (j = 0, v = p->verts[0]; j < p->numverts; j++, v += VERTEXSIZE) {
				glTexCoord2fv (&v[3]);
				glVertex3fv (v);
			}
			glEnd ();
		}
	}
	glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}

/*
	R_RenderBrushPoly
*/
void
R_RenderBrushPoly (msurface_t *fa)
{
	byte       *base;
	int         maps;
	glRect_t   *theRect;
	int         i;
	float      *v;
	int         smax, tmax;
	texture_t  *texture = R_TextureAnimation (fa->texinfo->texture);

	c_brush_polys++;

	glColor3f (1, 1, 1);
	glBindTexture (GL_TEXTURE_2D, texture->gl_texturenum);

	glBegin (GL_POLYGON);
	v = fa->polys->verts[0];
	for (i = 0; i < fa->polys->numverts; i++, v += VERTEXSIZE) {
		glTexCoord2fv (&v[3]);
		glVertex3fv (v);
	}
	glEnd ();

	// add the poly to the proper lightmap chain

	fa->polys->chain = lightmap_polys[fa->lightmaptexturenum];
	lightmap_polys[fa->lightmaptexturenum] = fa->polys;

	if (texture->gl_fb_texturenum > 0) {
		fa->polys->fb_chain = fullbright_polys[texture->gl_fb_texturenum];
		fullbright_polys[texture->gl_fb_texturenum] = fa->polys;
	}
	// check for lightmap modification
	for (maps = 0; maps < MAXLIGHTMAPS && fa->styles[maps] != 255; maps++)
		if (d_lightstylevalue[fa->styles[maps]] != fa->cached_light[maps])
			goto dynamic;

	if (fa->dlightframe == r_framecount	// dynamic this frame
		|| fa->cached_dlight)			// dynamic previously
	{
	  dynamic:
		if (r_dynamic->int_val) {
			lightmap_modified[fa->lightmaptexturenum] = true;
			theRect = &lightmap_rectchange[fa->lightmaptexturenum];
			if (fa->light_t < theRect->t) {
				if (theRect->h)
					theRect->h += theRect->t - fa->light_t;
				theRect->t = fa->light_t;
			}
			if (fa->light_s < theRect->l) {
				if (theRect->w)
					theRect->w += theRect->l - fa->light_s;
				theRect->l = fa->light_s;
			}
			smax = (fa->extents[0] >> 4) + 1;
			tmax = (fa->extents[1] >> 4) + 1;
			if ((theRect->w + theRect->l) < (fa->light_s + smax))
				theRect->w = (fa->light_s - theRect->l) + smax;
			if ((theRect->h + theRect->t) < (fa->light_t + tmax))
				theRect->h = (fa->light_t - theRect->t) + tmax;
			base =
				lightmaps[fa->lightmaptexturenum] + (fa->light_t * BLOCK_WIDTH +
													 fa->light_s) *
				lightmap_bytes;
			R_BuildLightMap (fa, base, BLOCK_WIDTH * lightmap_bytes);
		}
	}
	glColor3ubv (lighthalf_v);
}

void
GL_WaterSurface (msurface_t *s)
{
	int         i;

	i = s->texinfo->texture->gl_texturenum;
	glBindTexture (GL_TEXTURE_2D, i);
	if (r_wateralpha->value < 1.0) {
		glDepthMask (GL_FALSE);
		if (lighthalf) {
			glColor4f (0.5, 0.5, 0.5, r_wateralpha->value);
		} else {
			glColor4f (1, 1, 1, r_wateralpha->value);
		}
		EmitWaterPolys (s);
		glColor3ubv (lighthalf_v);
		glDepthMask (GL_TRUE);
	} else
		EmitWaterPolys (s);
}

/*
	R_DrawWaterSurfaces
*/
void
R_DrawWaterSurfaces (void)
{
	int         i;
	msurface_t *s;

	if (!waterchain)
		return;

	// go back to the world matrix

	glLoadMatrixf (r_world_matrix);

	if (r_wateralpha->value < 1.0) {
		glDepthMask (GL_FALSE);
		if (lighthalf) {
			glColor4f (0.5, 0.5, 0.5, r_wateralpha->value);
		} else {
			glColor4f (1, 1, 1, r_wateralpha->value);
		}
	}

	i = -1;
	for (s = waterchain; s; s = s->texturechain) {
		if (i != s->texinfo->texture->gl_texturenum) {
			i = s->texinfo->texture->gl_texturenum;
			glBindTexture (GL_TEXTURE_2D, i);
		}
		EmitWaterPolys (s);
	}

	waterchain = NULL;

	if (r_wateralpha->value < 1.0) {
		glDepthMask (GL_TRUE);
		glColor3ubv (lighthalf_v);
	}
}


/*
	DrawTextureChains
*/
void
DrawTextureChains (void)
{
	int         i;
	msurface_t *s;

	glDisable (GL_BLEND);

	for (i = 0; i < cl.worldmodel->numtextures; i++) {
		if (!cl.worldmodel->textures[i])
			continue;
		for (s = cl.worldmodel->textures[i]->texturechain; s;
			 s = s->texturechain) R_RenderBrushPoly (s);

		cl.worldmodel->textures[i]->texturechain = NULL;
	}

	glEnable (GL_BLEND);
}

/*
	R_DrawBrushModel
*/
void
R_DrawBrushModel (entity_t *e)
{
	int         i;
	int         k;
	vec3_t      mins, maxs;
	msurface_t *psurf;
	float       dot;
	mplane_t   *pplane;
	model_t    *clmodel;
	qboolean    rotated;

	currententity = e;

	clmodel = e->model;

	if (e->angles[0] || e->angles[1] || e->angles[2]) {
		rotated = true;
		for (i = 0; i < 3; i++) {
			mins[i] = e->origin[i] - clmodel->radius;
			maxs[i] = e->origin[i] + clmodel->radius;
		}
	} else {
		rotated = false;
		VectorAdd (e->origin, clmodel->mins, mins);
		VectorAdd (e->origin, clmodel->maxs, maxs);
	}

	if (R_CullBox (mins, maxs))
		return;

	memset (lightmap_polys, 0, sizeof (lightmap_polys));
	memset (fullbright_polys, 0, sizeof (fullbright_polys));
	if (gl_sky_clip->int_val) {
		sky_chain = 0;
	}

	VectorSubtract (r_refdef.vieworg, e->origin, modelorg);
	if (rotated) {
		vec3_t      temp;
		vec3_t      forward, right, up;

		VectorCopy (modelorg, temp);
		AngleVectors (e->angles, forward, right, up);
		modelorg[0] = DotProduct (temp, forward);
		modelorg[1] = -DotProduct (temp, right);
		modelorg[2] = DotProduct (temp, up);
	}

	psurf = &clmodel->surfaces[clmodel->firstmodelsurface];

	// calculate dynamic lighting for bmodel if it's not an instanced model
	if (clmodel->firstmodelsurface != 0 && gl_dlight_lightmap->int_val) {
		vec3_t      lightorigin;

		for (k = 0; k < MAX_DLIGHTS; k++) {
			if ((cl_dlights[k].die < cl.time) || (!cl_dlights[k].radius))
				continue;

			VectorSubtract (cl_dlights[k].origin, e->origin, lightorigin);
			R_MarkLights (lightorigin, &cl_dlights[k], 1 << k,
						  clmodel->nodes + clmodel->hulls[0].firstclipnode);
		}
	}

	glPushMatrix ();
	e->angles[0] = -e->angles[0];		// stupid quake bug
	R_RotateForEntity (e);
	e->angles[0] = -e->angles[0];		// stupid quake bug

	// draw texture
	for (i = 0; i < clmodel->nummodelsurfaces; i++, psurf++) {
		// find which side of the node we are on
		pplane = psurf->plane;

		dot = DotProduct (modelorg, pplane->normal) - pplane->dist;

		// draw the polygon
		if (((psurf->flags & SURF_PLANEBACK) && (dot < -BACKFACE_EPSILON)) ||
			(!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) {

			if (psurf->flags & SURF_DRAWTURB) {
				GL_WaterSurface (psurf);
			} else if (psurf->flags & SURF_DRAWSKY) {
				psurf->texturechain = sky_chain;
				sky_chain = psurf;
				return;
			} else if (gl_mtex_active) {
				R_DrawMultitexturePoly (psurf);
			} else {
				R_RenderBrushPoly (psurf);
			}
		}
	}

	if (!gl_mtex_active)
		R_BlendLightmaps ();

	if (gl_fb_bmodels->int_val)
		R_RenderFullbrights ();

	if (gl_sky_clip->int_val)
		R_DrawSkyChain (sky_chain);

	glPopMatrix ();
}

/*
	WORLD MODEL
*/

/*
	R_RecursiveWorldNode
*/
void
R_RecursiveWorldNode (mnode_t *node)
{
	int         c, side;
	mplane_t   *plane;
	msurface_t *surf, **mark;
	mleaf_t    *pleaf;
	double      dot;

	if (node->contents == CONTENTS_SOLID)	// solid
		return;

	if (node->visframe != r_visframecount)
		return;
	if (R_CullBox (node->minmaxs, node->minmaxs + 3))
		return;

	// if a leaf node, draw stuff
	if (node->contents < 0) {
		pleaf = (mleaf_t *) node;

		if ((c = pleaf->nummarksurfaces)) {
			mark = pleaf->firstmarksurface;
			do {
				(*mark)->visframe = r_framecount;
				mark++;
			} while (--c);
		}
		// deal with model fragments in this leaf
		if (pleaf->efrags)
			R_StoreEfrags (&pleaf->efrags);

		return;
	}
	// node is just a decision point, so go down the apropriate sides

	// find which side of the node we are on
	plane = node->plane;

	switch (plane->type) {
		case PLANE_X:
			dot = modelorg[0] - plane->dist;
			break;
		case PLANE_Y:
			dot = modelorg[1] - plane->dist;
			break;
		case PLANE_Z:
			dot = modelorg[2] - plane->dist;
			break;
		default:
			dot = DotProduct (modelorg, plane->normal) - plane->dist;
			break;
	}

	side = dot < 0;

	// recurse down the children, front side first
	// LordHavoc: save a stack frame by avoiding a call
	if (node->children[side]->contents != CONTENTS_SOLID
		&& node->children[side]->visframe == r_visframecount
		&& !R_CullBox (node->children[side]->minmaxs,
					   node->children[side]->minmaxs + 3))
		R_RecursiveWorldNode (node->children[side]);

	// draw stuff
	if ((c = node->numsurfaces)) {
		surf = cl.worldmodel->surfaces + node->firstsurface;

		if (dot < -BACKFACE_EPSILON)
			side = SURF_PLANEBACK;
		else if (dot > BACKFACE_EPSILON)
			side = 0;

		for (; c; c--, surf++) {
			if (surf->visframe != r_framecount)
				continue;

			if ((dot < 0) ^ !!(surf->flags & SURF_PLANEBACK))
				continue;				// wrong side


			if (surf->flags & SURF_DRAWTURB) {
				surf->texturechain = waterchain;
				waterchain = surf;
			} else if (surf->flags & SURF_DRAWSKY) {
				surf->texturechain = sky_chain;
				sky_chain = surf;
				continue;
			} else if (gl_mtex_active) {
				R_DrawMultitexturePoly (surf);
			} else {
				surf->texturechain = surf->texinfo->texture->texturechain;
				surf->texinfo->texture->texturechain = surf;
			}
		}
	}
	// recurse down the back side
	// LordHavoc: save a stack frame by avoiding a call
	side = !side;
	if (node->children[side]->contents != CONTENTS_SOLID
		&& node->children[side]->visframe == r_visframecount
		&& !R_CullBox (node->children[side]->minmaxs,
					   node->children[side]->minmaxs + 3))
		R_RecursiveWorldNode (node->children[side]);
}



/*
	R_DrawWorld
*/
void
R_DrawWorld (void)
{
	entity_t    ent;

	memset (&ent, 0, sizeof (ent));
	ent.model = cl.worldmodel;

	VectorCopy (r_refdef.vieworg, modelorg);

	currententity = &ent;

	memset (lightmap_polys, 0, sizeof (lightmap_polys));
	memset (fullbright_polys, 0, sizeof (fullbright_polys));
	if (gl_sky_clip->int_val) {
		sky_chain = 0;
	} else {
		// Be sure to clear the skybox --KB
		R_DrawSky ();
	}

	R_RecursiveWorldNode (cl.worldmodel->nodes);

	DrawTextureChains ();

	if (!gl_mtex_active)
		R_BlendLightmaps ();

	if (gl_fb_bmodels->int_val)
		R_RenderFullbrights ();

	if (gl_sky_clip->int_val)
		R_DrawSkyChain (sky_chain);
}


/*
	R_MarkLeaves
*/
void
R_MarkLeaves (void)
{
	byte       *vis;
	mnode_t    *node;
	int         i;
	byte        solid[4096];

	if (r_oldviewleaf == r_viewleaf && !r_novis->int_val)
		return;

	r_visframecount++;
	r_oldviewleaf = r_viewleaf;

	if (r_novis->int_val) {
		vis = solid;
		memset (solid, 0xff, (cl.worldmodel->numleafs + 7) >> 3);
	} else
		vis = Mod_LeafPVS (r_viewleaf, cl.worldmodel);

	for (i = 0; i < cl.worldmodel->numleafs; i++) {
		if (vis[i >> 3] & (1 << (i & 7))) {
			node = (mnode_t *) &cl.worldmodel->leafs[i + 1];
			do {
				if (node->visframe == r_visframecount)
					break;
				node->visframe = r_visframecount;
				node = node->parent;
			} while (node);
		}
	}
}



/*
	LIGHTMAP ALLOCATION
*/

// returns a texture number and the position inside it
int
AllocBlock (int w, int h, int *x, int *y)
{
	int         i, j;
	int         best, best2;
	int         texnum;

	for (texnum = 0; texnum < MAX_LIGHTMAPS; texnum++) {
		best = BLOCK_HEIGHT;

		for (i = 0; i < BLOCK_WIDTH - w; i++) {
			best2 = 0;

			for (j = 0; j < w; j++) {
				if (allocated[texnum][i + j] >= best)
					break;
				if (allocated[texnum][i + j] > best2)
					best2 = allocated[texnum][i + j];
			}
			if (j == w) {
				// this is a valid spot
				*x = i;
				*y = best = best2;
			}
		}

		if (best + h > BLOCK_HEIGHT)
			continue;

		// LordHavoc: allocate lightmaps only as needed
		if (!lightmaps[texnum])
			lightmaps[texnum] = calloc (BLOCK_WIDTH * BLOCK_HEIGHT, 3);

		for (i = 0; i < w; i++)
			allocated[texnum][*x + i] = best + h;

		return texnum;
	}

	Sys_Error ("AllocBlock: full");
	return 0;
}


mvertex_t  *r_pcurrentvertbase;
model_t    *currentmodel;

int         nColinElim;

/*
	BuildSurfaceDisplayList
*/
void
BuildSurfaceDisplayList (msurface_t *fa)
{
	int         i, lindex, lnumverts;
	medge_t    *pedges, *r_pedge;
	int         vertpage;
	float      *vec;
	float       s, t;
	glpoly_t   *poly;

	// reconstruct the polygon
	pedges = currentmodel->edges;
	lnumverts = fa->numedges;
	vertpage = 0;

	// draw texture
	poly = Hunk_Alloc (sizeof (glpoly_t) + (lnumverts - 4) * VERTEXSIZE * sizeof (float));
	poly->next = fa->polys;
	poly->flags = fa->flags;
	fa->polys = poly;
	poly->numverts = lnumverts;

	for (i = 0; i < lnumverts; i++) {
		lindex = currentmodel->surfedges[fa->firstedge + i];

		if (lindex > 0) {
			r_pedge = &pedges[lindex];
			vec = r_pcurrentvertbase[r_pedge->v[0]].position;
		} else {
			r_pedge = &pedges[-lindex];
			vec = r_pcurrentvertbase[r_pedge->v[1]].position;
		}
		s = DotProduct (vec, fa->texinfo->vecs[0]) + fa->texinfo->vecs[0][3];
		s /= fa->texinfo->texture->width;

		t = DotProduct (vec, fa->texinfo->vecs[1]) + fa->texinfo->vecs[1][3];
		t /= fa->texinfo->texture->height;

		VectorCopy (vec, poly->verts[i]);
		poly->verts[i][3] = s;
		poly->verts[i][4] = t;

		// lightmap texture coordinates
		s = DotProduct (vec, fa->texinfo->vecs[0]) + fa->texinfo->vecs[0][3];
		s -= fa->texturemins[0];
		s += fa->light_s * 16;
		s += 8;
		s /= BLOCK_WIDTH * 16;			// fa->texinfo->texture->width;

		t = DotProduct (vec, fa->texinfo->vecs[1]) + fa->texinfo->vecs[1][3];
		t -= fa->texturemins[1];
		t += fa->light_t * 16;
		t += 8;
		t /= BLOCK_HEIGHT * 16;			// fa->texinfo->texture->height;

		poly->verts[i][5] = s;
		poly->verts[i][6] = t;
	}

	// remove co-linear points - Ed
	if (!gl_keeptjunctions->int_val && !(fa->flags & SURF_UNDERWATER)) {
		for (i = 0; i < lnumverts; ++i) {
			vec3_t      v1, v2;
			float      *prev, *this, *next;

			prev = poly->verts[(i + lnumverts - 1) % lnumverts];
			this = poly->verts[i];
			next = poly->verts[(i + 1) % lnumverts];

			VectorSubtract (this, prev, v1);
			VectorNormalize (v1);
			VectorSubtract (next, prev, v2);
			VectorNormalize (v2);

			// skip co-linear points
#			define COLINEAR_EPSILON 0.001
			if ((fabs (v1[0] - v2[0]) <= COLINEAR_EPSILON) &&
				(fabs (v1[1] - v2[1]) <= COLINEAR_EPSILON) &&
				(fabs (v1[2] - v2[2]) <= COLINEAR_EPSILON)) {
				int         j;

				for (j = i + 1; j < lnumverts; ++j) {
					int         k;

					for (k = 0; k < VERTEXSIZE; ++k)
						poly->verts[j - 1][k] = poly->verts[j][k];
				}
				--lnumverts;
				++nColinElim;
				// retry next vertex next time, which is now current vertex
				--i;
			}
		}
	}
	poly->numverts = lnumverts;

}

/*
	GL_CreateSurfaceLightmap
*/
void
GL_CreateSurfaceLightmap (msurface_t *surf)
{
	int         smax, tmax;
	byte       *base;

	if (surf->flags & (SURF_DRAWSKY | SURF_DRAWTURB))
		return;

	smax = (surf->extents[0] >> 4) + 1;
	tmax = (surf->extents[1] >> 4) + 1;

	surf->lightmaptexturenum = AllocBlock (smax, tmax, &surf->light_s, &surf->light_t);
	base = lightmaps[surf->lightmaptexturenum] + (surf->light_t * BLOCK_WIDTH + surf->light_s) * lightmap_bytes;
	R_BuildLightMap (surf, base, BLOCK_WIDTH * lightmap_bytes);
}


/*
	GL_BuildLightmaps

	Builds the lightmap texture
	with all the surfaces from all brush models
*/
void
GL_BuildLightmaps (void)
{
	int         i, j;
	model_t    *m;

	memset (allocated, 0, sizeof (allocated));

	r_framecount = 1;					// no dlightcache

	if (!lightmap_textures) {
		lightmap_textures = texture_extension_number;
		texture_extension_number += MAX_LIGHTMAPS;
	}

	if (gl_colorlights->int_val) {
		gl_lightmap_format = GL_RGB;
		lightmap_bytes = 3;
	} else {
		gl_lightmap_format = GL_LUMINANCE;
		lightmap_bytes = 1;
	}

	for (j = 1; j < MAX_MODELS; j++) {
		m = cl.model_precache[j];
		if (!m)
			break;
		if (m->name[0] == '*')
			continue;
		r_pcurrentvertbase = m->vertexes;
		currentmodel = m;
		for (i = 0; i < m->numsurfaces; i++) {
			if (m->surfaces[i].flags & SURF_DRAWTURB)
				continue;
			if (gl_sky_divide->int_val && (m->surfaces[i].flags & SURF_DRAWSKY))
				continue;
			GL_CreateSurfaceLightmap (m->surfaces + i);
			BuildSurfaceDisplayList (m->surfaces + i);
		}
	}

	if (gl_mtex_active)
		qglActiveTexture (gl_mtex_enum + 1);

	// upload all lightmaps that were filled
	for (i = 0; i < MAX_LIGHTMAPS; i++) {
		if (!allocated[i][0])
			break;						// no more used
		lightmap_modified[i] = false;
		lightmap_rectchange[i].l = BLOCK_WIDTH;
		lightmap_rectchange[i].t = BLOCK_HEIGHT;
		lightmap_rectchange[i].w = 0;
		lightmap_rectchange[i].h = 0;
		glBindTexture (GL_TEXTURE_2D, lightmap_textures + i);
		glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexImage2D (GL_TEXTURE_2D, 0, lightmap_bytes, BLOCK_WIDTH,
					  BLOCK_HEIGHT, 0, gl_lightmap_format,
					  GL_UNSIGNED_BYTE, lightmaps[i]);
	}

	if (gl_mtex_active)
		qglActiveTexture (gl_mtex_enum + 0);
}

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us