]> icculus.org git repositories - btb/d2x.git/blob - main/editor/seguvs.c
Move old logs to ChangeLog-old
[btb/d2x.git] / main / editor / seguvs.c
1 /* $Id: seguvs.c,v 1.2 2004-12-19 14:52:48 btb 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-1998 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
13 */
14
15 /*
16  *
17  * u,v coordinate computation for segment faces
18  *
19  */
20
21
22 #ifdef RCS
23 static char rcsid[] = "$Id: seguvs.c,v 1.2 2004-12-19 14:52:48 btb Exp $";
24 #endif
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <math.h>
30 #include <string.h>
31
32 #include "inferno.h"
33 #include "segment.h"
34 #include "editor/editor.h"
35
36 #include "gameseg.h"
37
38 #include "fix.h"
39 #include "mono.h"
40 #include "error.h"
41
42 #include "wall.h"
43 #include "editor/kdefs.h"
44 #include "bm.h"         //      Needed for TmapInfo
45 #include        "effects.h"     //      Needed for effects_bm_num
46 #include "fvi.h"
47
48 void cast_all_light_in_mine(int quick_flag);
49 //--rotate_uvs-- vms_vector Rightvec;
50
51 //      ---------------------------------------------------------------------------------------------
52 //      Returns approximate area of a side
53 fix area_on_side(side *sidep)
54 {
55         fix     du,dv,width,height;
56
57         du = sidep->uvls[1].u - sidep->uvls[0].u;
58         dv = sidep->uvls[1].v - sidep->uvls[0].v;
59
60         width = fix_sqrt(fixmul(du,du) + fixmul(dv,dv));
61
62         du = sidep->uvls[3].u - sidep->uvls[0].u;
63         dv = sidep->uvls[3].v - sidep->uvls[0].v;
64
65         height = fix_sqrt(fixmul(du,du) + fixmul(dv,dv));
66
67         return fixmul(width, height);
68 }
69
70 //      -------------------------------------------------------------------------------------------
71 //      DEBUG function -- callable from debugger.
72 //      Returns approximate area of all sides which get mapped (ie, are not a connection).
73 //      I wrote this because I was curious how much memory would be required to texture map all
74 //      sides individually with custom artwork.  For demo1.min on 2/18/94, it would be about 5 meg.
75 int area_on_all_sides(void)
76 {
77         int     i,s;
78         int     total_area = 0;
79
80         for (i=0; i<=Highest_segment_index; i++) {
81                 segment *segp = &Segments[i];
82
83                 for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
84                         if (!IS_CHILD(segp->children[s]))
85                                 total_area += f2i(area_on_side(&segp->sides[s]));
86         }
87
88         return total_area;
89 }
90
91 fix average_connectivity(void)
92 {
93         int     i,s;
94         int     total_sides = 0, total_mapped_sides = 0;
95
96         for (i=0; i<=Highest_segment_index; i++) {
97                 segment *segp = &Segments[i];
98
99                 for (s=0; s<MAX_SIDES_PER_SEGMENT; s++) {
100                         if (!IS_CHILD(segp->children[s]))
101                                 total_mapped_sides++;
102                         total_sides++;
103                 }
104         }
105
106         return 6 * fixdiv(total_mapped_sides, total_sides);
107 }
108
109 #define MAX_LIGHT_SEGS 16
110
111 //      ---------------------------------------------------------------------------------------------
112 //      Scan all polys in all segments, return average light value for vnum.
113 //      segs = output array for segments containing vertex, terminated by -1.
114 fix get_average_light_at_vertex(int vnum, short *segs)
115 {
116         int     segnum, relvnum, sidenum;
117         fix     total_light;
118         int     num_occurrences;
119 //      #ifndef NDEBUG //Removed this ifdef because the version of Assert that I used to get it to compile doesn't work without this symbol. -KRB
120         short   *original_segs;
121
122         original_segs = segs;
123 //      #endif
124
125
126         num_occurrences = 0;
127         total_light = 0;
128
129         for (segnum=0; segnum<=Highest_segment_index; segnum++) {
130                 segment *segp = &Segments[segnum];
131                 short *vp = segp->verts;
132
133                 for (relvnum=0; relvnum<MAX_VERTICES_PER_SEGMENT; relvnum++)
134                         if (*vp++ == vnum)
135                                 break;
136
137                 if (relvnum < MAX_VERTICES_PER_SEGMENT) {
138
139                         *segs++ = segnum;
140                         Assert(segs - original_segs < MAX_LIGHT_SEGS);
141
142                         for (sidenum=0; sidenum < MAX_SIDES_PER_SEGMENT; sidenum++) {
143                                 if (!IS_CHILD(segp->children[sidenum])) {
144                                         side    *sidep = &segp->sides[sidenum];
145                                         sbyte   *vp = Side_to_verts[sidenum];
146                                         int     v;
147
148                                         for (v=0; v<4; v++)
149                                                 if (*vp++ == relvnum) {
150                                                         total_light += sidep->uvls[v].l;
151                                                         num_occurrences++;
152                                                 }
153                                 }       // end if
154                         }       // end sidenum
155                 }
156         }       // end segnum
157
158         *segs = -1;
159
160         if (num_occurrences)
161                 return total_light/num_occurrences;
162         else
163                 return 0;
164
165 }
166
167 void set_average_light_at_vertex(int vnum)
168 {
169         int     relvnum, sidenum;
170         short   Segment_indices[MAX_LIGHT_SEGS];
171         int     segind;
172
173         fix average_light;
174
175         average_light = get_average_light_at_vertex(vnum, Segment_indices);
176
177         if (!average_light)
178                 return;
179
180         segind = 0;
181         while (Segment_indices[segind] != -1) {
182                 int segnum = Segment_indices[segind++];
183
184                 segment *segp = &Segments[segnum];
185
186                 for (relvnum=0; relvnum<MAX_VERTICES_PER_SEGMENT; relvnum++)
187                         if (segp->verts[relvnum] == vnum)
188                                 break;
189
190                 if (relvnum < MAX_VERTICES_PER_SEGMENT) {
191                         for (sidenum=0; sidenum < MAX_SIDES_PER_SEGMENT; sidenum++) {
192                                 if (!IS_CHILD(segp->children[sidenum])) {
193                                         side *sidep = &segp->sides[sidenum];
194                                         sbyte   *vp = Side_to_verts[sidenum];
195                                         int     v;
196
197                                         for (v=0; v<4; v++)
198                                                 if (*vp++ == relvnum)
199                                                         sidep->uvls[v].l = average_light;
200                                 }       // end if
201                         }       // end sidenum
202                 }       // end if
203         }       // end while
204
205         Update_flags |= UF_WORLD_CHANGED;
206 }
207
208 void set_average_light_on_side(segment *segp, int sidenum)
209 {
210         int     v;
211
212         if (!IS_CHILD(segp->children[sidenum]))
213                 for (v=0; v<4; v++) {
214 //                      mprintf((0,"Vertex %i\n", segp->verts[Side_to_verts[side][v]]));
215                         set_average_light_at_vertex(segp->verts[Side_to_verts[sidenum][v]]);
216                 }
217
218 }
219
220 int set_average_light_on_curside(void)
221 {
222         set_average_light_on_side(Cursegp, Curside);
223         return 0;
224 }
225
226 //      -----------------------------------------------------------------------------------------
227 void set_average_light_on_all_fast(void)
228 {
229         int     s,v,relvnum;
230         fix     al;
231         int     alc;
232         int     seglist[MAX_LIGHT_SEGS];
233         int     *segptr;
234
235         set_vertex_counts();
236
237         //      Set total light value for all vertices in array average_light.
238         for (v=0; v<=Highest_vertex_index; v++) {
239                 al = 0;
240                 alc = 0;
241
242                 if (Vertex_active[v]) {
243                         segptr = seglist;
244
245                         for (s=0; s<=Highest_segment_index; s++) {
246                                 segment *segp = &Segments[s];
247                                 for (relvnum=0; relvnum<MAX_VERTICES_PER_SEGMENT; relvnum++)
248                                         if (segp->verts[relvnum] == v)
249                                                 break;
250
251                                         if (relvnum != MAX_VERTICES_PER_SEGMENT) {
252                                                 int             si;
253
254                                                 *segptr++ = s;                  // Note this segment in list, so we can process it below.
255                                                 Assert(segptr - seglist < MAX_LIGHT_SEGS);
256
257                                                 for (si=0; si<MAX_SIDES_PER_SEGMENT; si++) {
258                                                         if (!IS_CHILD(segp->children[si])) {
259                                                                 side    *sidep = &segp->sides[si];
260                                                                 sbyte   *vp = Side_to_verts[si];
261                                                                 int     vv;
262
263                                                                 for (vv=0; vv<4; vv++)
264                                                                         if (*vp++ == relvnum) {
265                                                                                 al += sidep->uvls[vv].l;
266                                                                                 alc++;
267                                                                         }
268                                                         }       // if (segp->children[si == -1) {
269                                                 }       // for (si=0...
270                                         }       // if (relvnum != ...
271                         }       // for (s=0; ...
272
273                         *segptr = -1;
274
275                         //      Now, divide average_light by number of number of occurrences for each vertex
276                         if (alc)
277                                 al /= alc;
278                         else
279                                 al = 0;
280
281                         segptr = seglist;
282                         while (*segptr != -1) {
283                                 int             segnum = *segptr++;
284                                 segment *segp = &Segments[segnum];
285                                 int             sidenum;
286
287                                 for (relvnum=0; relvnum<MAX_VERTICES_PER_SEGMENT; relvnum++)
288                                         if (segp->verts[relvnum] == v)
289                                                 break;
290
291                                 Assert(relvnum < MAX_VERTICES_PER_SEGMENT);     // IMPOSSIBLE! This segment is in seglist, but vertex v does not occur!
292                                 for (sidenum=0; sidenum < MAX_SIDES_PER_SEGMENT; sidenum++) {
293                                         int     wid_result;
294                                         wid_result = WALL_IS_DOORWAY(segp, sidenum);
295                                         if ((wid_result != WID_FLY_FLAG) && (wid_result != WID_NO_WALL)) {
296                                                 side *sidep = &segp->sides[sidenum];
297                                                 sbyte   *vp = Side_to_verts[sidenum];
298                                                 int     v;
299
300                                                 for (v=0; v<4; v++)
301                                                         if (*vp++ == relvnum)
302                                                                 sidep->uvls[v].l = al;
303                                         }       // end if
304                                 }       // end sidenum
305                         }       // end while
306
307                 }       // if (Vertex_active[v]...
308
309         }       // for (v=0...
310
311 }
312
313 extern int Doing_lighting_hack_flag;    //      If set, don't mprintf warning messages in gameseg.c/find_point_seg
314 int set_average_light_on_all(void)
315 {
316 //      set_average_light_on_all_fast();
317
318         Doing_lighting_hack_flag = 1;
319         cast_all_light_in_mine(0);
320         Doing_lighting_hack_flag = 0;
321         Update_flags |= UF_WORLD_CHANGED;
322
323 //      int seg, side;
324
325 //      for (seg=0; seg<=Highest_segment_index; seg++)
326 //              for (side=0; side<MAX_SIDES_PER_SEGMENT; side++)
327 //                      if (Segments[seg].segnum != -1)
328 //                              set_average_light_on_side(&Segments[seg], side);
329         return 0;
330 }
331
332 int set_average_light_on_all_quick(void)
333 {
334         cast_all_light_in_mine(1);
335         Update_flags |= UF_WORLD_CHANGED;
336
337         return 0;
338 }
339
340 //      ---------------------------------------------------------------------------------------------
341 fix compute_uv_dist(uvl *uv0, uvl *uv1)
342 {
343         vms_vector      v0,v1;
344
345         v0.x = uv0->u;
346         v0.y = 0;
347         v0.z = uv0->v;
348
349         v1.x = uv1->u;
350         v1.y = 0;
351         v1.z = uv1->v;
352
353         return vm_vec_dist(&v0,&v1);
354 }
355
356 //      ---------------------------------------------------------------------------------------------
357 //      Given a polygon, compress the uv coordinates so that they are as close to 0 as possible.
358 //      Do this by adding a constant u and v to each uv pair.
359 void compress_uv_coordinates(side *sidep)
360 {
361         int     v;
362         fix     uc, vc;
363
364         uc = 0;
365         vc = 0;
366
367         for (v=0; v<4; v++) {
368                 uc += sidep->uvls[v].u;
369                 vc += sidep->uvls[v].v;
370         }
371
372         uc /= 4;
373         vc /= 4;
374         uc = uc & 0xffff0000;
375         vc = vc & 0xffff0000;
376
377         for (v=0; v<4; v++) {
378                 sidep->uvls[v].u -= uc;
379                 sidep->uvls[v].v -= vc;
380         }
381
382 }
383
384 //      ---------------------------------------------------------------------------------------------
385 void compress_uv_coordinates_on_side(side *sidep)
386 {
387         compress_uv_coordinates(sidep);
388 }
389
390 //      ---------------------------------------------------------------------------------------------
391 void validate_uv_coordinates_on_side(segment *segp, int sidenum)
392 {
393 //      int                     v;
394 //      fix                     uv_dist,threed_dist;
395 //      vms_vector      tvec;
396 //      fix                     dist_ratios[MAX_VERTICES_PER_POLY];
397         side                    *sidep = &segp->sides[sidenum];
398 //      sbyte                   *vp = Side_to_verts[sidenum];
399
400 //      This next hunk doesn't seem to affect anything. @mk, 02/13/94
401 //      for (v=1; v<4; v++) {
402 //              uv_dist = compute_uv_dist(&sidep->uvls[v],&sidep->uvls[0]);
403 //              threed_dist = vm_vec_mag(vm_vec_sub(&tvec,&Vertices[segp->verts[vp[v]],&Vertices[vp[0]]));
404 //              dist_ratios[v-1] = fixdiv(uv_dist,threed_dist);
405 //      }
406
407         compress_uv_coordinates_on_side(sidep);
408 }
409
410 void compress_uv_coordinates_in_segment(segment *segp)
411 {
412         int     side;
413
414         for (side=0; side<MAX_SIDES_PER_SEGMENT; side++)
415                 compress_uv_coordinates_on_side(&segp->sides[side]);
416 }
417
418 void compress_uv_coordinates_all(void)
419 {
420         int     seg;
421
422         for (seg=0; seg<=Highest_segment_index; seg++)
423                 if (Segments[seg].segnum != -1)
424                         compress_uv_coordinates_in_segment(&Segments[seg]);
425 }
426
427 void check_lighting_side(segment *sp, int sidenum)
428 {
429         int     v;
430         side    *sidep = &sp->sides[sidenum];
431
432         for (v=0; v<4; v++)
433                 if ((sidep->uvls[v].l > F1_0*16) || (sidep->uvls[v].l < 0))
434                         Int3(); //mprintf(0,"Bogus lighting value in segment %i, side %i, vert %i = %x\n",sp-Segments, side, v, sidep->uvls[v].l);
435 }
436
437 void check_lighting_segment(segment *segp)
438 {
439         int     side;
440
441         for (side=0; side<MAX_SIDES_PER_SEGMENT; side++)
442                 check_lighting_side(segp, side);
443 }
444
445 //      Flag bogus lighting values.
446 void check_lighting_all(void)
447 {
448         int     seg;
449
450         for (seg=0; seg<=Highest_segment_index; seg++)
451                 if (Segments[seg].segnum != -1)
452                         check_lighting_segment(&Segments[seg]);
453 }
454
455 void assign_default_lighting_on_side(segment *segp, int sidenum)
456 {
457         int     v;
458         side    *sidep = &segp->sides[sidenum];
459
460         for (v=0; v<4; v++)
461                 sidep->uvls[v].l = DEFAULT_LIGHTING;
462 }
463
464 void assign_default_lighting(segment *segp)
465 {
466         int     sidenum;
467
468         for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++)
469                 assign_default_lighting_on_side(segp, sidenum);
470 }
471
472 void assign_default_lighting_all(void)
473 {
474         int     seg;
475
476         for (seg=0; seg<=Highest_segment_index; seg++)
477                 if (Segments[seg].segnum != -1)
478                         assign_default_lighting(&Segments[seg]);
479 }
480
481 //      ---------------------------------------------------------------------------------------------
482 void validate_uv_coordinates(segment *segp)
483 {
484         int     s;
485
486         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
487                 validate_uv_coordinates_on_side(segp,s);
488
489 }
490
491 //      ---------------------------------------------------------------------------------------------
492 //      For all faces in side, copy uv coordinates from uvs array to face.
493 void copy_uvs_from_side_to_faces(segment *segp, int sidenum, uvl uvls[])
494 {
495         int     v;
496         side    *sidep = &segp->sides[sidenum];
497
498         for (v=0; v<4; v++)
499                 sidep->uvls[v] = uvls[v];
500
501 }
502
503 #ifdef __WATCOMC__
504 fix zhypot(fix a,fix b);
505 #pragma aux zhypot parm [eax] [ebx] value [eax] modify [eax ebx ecx edx] = \
506         "imul   eax" \
507         "xchg eax,ebx" \
508         "mov    ecx,edx" \
509         "imul eax" \
510         "add    eax,ebx" \
511         "adc    edx,ecx" \
512         "call   quad_sqrt";
513 #else
514 fix zhypot(fix a,fix b) {
515         double x = (double)a / 65536;
516         double y = (double)b / 65536;
517         return (long)(sqrt(x * x + y * y) * 65536);
518 }
519 #endif
520
521 //      ---------------------------------------------------------------------------------------------
522 //      Assign lighting value to side, a function of the normal vector.
523 void assign_light_to_side(segment *sp, int sidenum)
524 {
525         int     v;
526         side    *sidep = &sp->sides[sidenum];
527
528         for (v=0; v<4; v++)
529                 sidep->uvls[v].l = DEFAULT_LIGHTING;
530 }
531
532 fix     Stretch_scale_x = F1_0;
533 fix     Stretch_scale_y = F1_0;
534
535 //      ---------------------------------------------------------------------------------------------
536 //      Given u,v coordinates at two vertices, assign u,v coordinates to other two vertices on a side.
537 //      (Actually, assign them to the coordinates in the faces.)
538 //      va, vb = face-relative vertex indices corresponding to uva, uvb.  Ie, they are always in 0..3 and should be looked up in
539 //      Side_to_verts[side] to get the segment relative index.
540 void assign_uvs_to_side(segment *segp, int sidenum, uvl *uva, uvl *uvb, int va, int vb)
541 {
542         int                     vlo,vhi,v0,v1,v2,v3;
543         vms_vector      fvec,rvec,tvec;
544         vms_matrix      rotmat;
545         uvl                     uvls[4],ruvmag,fuvmag,uvlo,uvhi;
546         fix                     fmag,mag01;
547         sbyte                   *vp;
548
549         Assert( (va<4) && (vb<4) );
550         Assert((abs(va - vb) == 1) || (abs(va - vb) == 3));             // make sure the verticies specify an edge
551
552         vp = (sbyte *)&Side_to_verts[sidenum];
553
554         // We want vlo precedes vhi, ie vlo < vhi, or vlo = 3, vhi = 0
555         if (va == ((vb + 1) % 4)) {             // va = vb + 1
556                 vlo = vb;
557                 vhi = va;
558                 uvlo = *uvb;
559                 uvhi = *uva;
560         } else {
561                 vlo = va;
562                 vhi = vb;
563                 uvlo = *uva;
564                 uvhi = *uvb;
565         }
566
567         Assert(((vlo+1) % 4) == vhi);   // If we are on an edge, then uvhi is one more than uvlo (mod 4)
568         uvls[vlo] = uvlo;
569         uvls[vhi] = uvhi;
570
571         // Now we have vlo precedes vhi, compute vertices ((vhi+1) % 4) and ((vhi+2) % 4)
572
573         // Assign u,v scale to a unit length right vector.
574         fmag = zhypot(uvhi.v - uvlo.v,uvhi.u - uvlo.u);
575         if (fmag < 64) {                // this is a fix, so 64 = 1/1024
576                 mprintf((0,"Warning: fmag = %7.3f, using approximate u,v values\n",f2fl(fmag)));
577                 ruvmag.u = F1_0*256;
578                 ruvmag.v = F1_0*256;
579                 fuvmag.u = F1_0*256;
580                 fuvmag.v = F1_0*256;
581         } else {
582                 ruvmag.u = uvhi.v - uvlo.v;
583                 ruvmag.v = uvlo.u - uvhi.u;
584
585                 fuvmag.u = uvhi.u - uvlo.u;
586                 fuvmag.v = uvhi.v - uvlo.v;
587         }
588
589         v0 = segp->verts[vp[vlo]];
590         v1 = segp->verts[vp[vhi]];
591         v2 = segp->verts[vp[(vhi+1)%4]];
592         v3 = segp->verts[vp[(vhi+2)%4]];
593
594         //      Compute right vector by computing orientation matrix from:
595         //              forward vector = vlo:vhi
596         //                right vector = vlo:(vhi+2) % 4
597         vm_vec_sub(&fvec,&Vertices[v1],&Vertices[v0]);
598         vm_vec_sub(&rvec,&Vertices[v3],&Vertices[v0]);
599
600         if (((fvec.x == 0) && (fvec.y == 0) && (fvec.z == 0)) || ((rvec.x == 0) && (rvec.y == 0) && (rvec.z == 0))) {
601                 mprintf((1, "Trapped null vector in assign_uvs_to_side, using identity matrix.\n"));
602                 rotmat = vmd_identity_matrix;
603         } else
604                 vm_vector_2_matrix(&rotmat,&fvec,0,&rvec);
605
606         rvec = rotmat.rvec; vm_vec_negate(&rvec);
607         fvec = rotmat.fvec;
608
609         // mprintf((0, "va = %i, vb = %i\n", va, vb));
610         mag01 = vm_vec_dist(&Vertices[v1],&Vertices[v0]);
611         if ((va == 0) || (va == 2))
612                 mag01 = fixmul(mag01, Stretch_scale_x);
613         else
614                 mag01 = fixmul(mag01, Stretch_scale_y);
615
616         if (mag01 < F1_0/1024 )
617                 editor_status("U, V bogosity in segment #%i, probably on side #%i.  CLEAN UP YOUR MESS!", segp-Segments, sidenum);
618         else {
619                 vm_vec_sub(&tvec,&Vertices[v2],&Vertices[v1]);
620                 uvls[(vhi+1)%4].u = uvhi.u + 
621                         fixdiv(fixmul(ruvmag.u,vm_vec_dotprod(&rvec,&tvec)),mag01) +
622                         fixdiv(fixmul(fuvmag.u,vm_vec_dotprod(&fvec,&tvec)),mag01);
623
624                 uvls[(vhi+1)%4].v = uvhi.v + 
625                         fixdiv(fixmul(ruvmag.v,vm_vec_dotprod(&rvec,&tvec)),mag01) +
626                         fixdiv(fixmul(fuvmag.v,vm_vec_dotprod(&fvec,&tvec)),mag01);
627
628
629                 vm_vec_sub(&tvec,&Vertices[v3],&Vertices[v0]);
630                 uvls[(vhi+2)%4].u = uvlo.u + 
631                         fixdiv(fixmul(ruvmag.u,vm_vec_dotprod(&rvec,&tvec)),mag01) +
632                         fixdiv(fixmul(fuvmag.u,vm_vec_dotprod(&fvec,&tvec)),mag01);
633
634                 uvls[(vhi+2)%4].v = uvlo.v + 
635                         fixdiv(fixmul(ruvmag.v,vm_vec_dotprod(&rvec,&tvec)),mag01) +
636                         fixdiv(fixmul(fuvmag.v,vm_vec_dotprod(&fvec,&tvec)),mag01);
637
638                 uvls[(vhi+1)%4].l = uvhi.l;
639                 uvls[(vhi+2)%4].l = uvlo.l;
640
641                 copy_uvs_from_side_to_faces(segp, sidenum, uvls);
642         }
643 }
644
645
646 int Vmag = VMAG;
647
648 // -----------------------------------------------------------------------------------------------------------
649 //      Assign default uvs to side.
650 //      This means:
651 //              v0 = 0,0
652 //              v1 = k,0 where k is 3d size dependent
653 //      v2, v3 assigned by assign_uvs_to_side
654 void assign_default_uvs_to_side(segment *segp,int side)
655 {
656         uvl                     uv0,uv1;
657         sbyte                   *vp;
658
659         uv0.u = 0;
660         uv0.v = 0;
661
662         vp = Side_to_verts[side];
663
664         uv1.u = 0;
665         uv1.v = Num_tilings * fixmul(Vmag, vm_vec_dist(&Vertices[segp->verts[vp[1]]],&Vertices[segp->verts[vp[0]]]));
666
667         assign_uvs_to_side(segp, side, &uv0, &uv1, 0, 1);
668 }
669
670 // -----------------------------------------------------------------------------------------------------------
671 //      Assign default uvs to side.
672 //      This means:
673 //              v0 = 0,0
674 //              v1 = k,0 where k is 3d size dependent
675 //      v2, v3 assigned by assign_uvs_to_side
676 void stretch_uvs_from_curedge(segment *segp, int side)
677 {
678         uvl                     uv0,uv1;
679         int                     v0, v1;
680
681         v0 = Curedge;
682         v1 = (v0 + 1) % 4;
683
684         uv0.u = segp->sides[side].uvls[v0].u;
685         uv0.v = segp->sides[side].uvls[v0].v;
686
687         uv1.u = segp->sides[side].uvls[v1].u;
688         uv1.v = segp->sides[side].uvls[v1].v;
689
690         assign_uvs_to_side(segp, side, &uv0, &uv1, v0, v1);
691 }
692
693 // --------------------------------------------------------------------------------------------------------------
694 //      Assign default uvs to a segment.
695 void assign_default_uvs_to_segment(segment *segp)
696 {
697         int     s;
698
699         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++) {
700                 assign_default_uvs_to_side(segp,s);
701                 assign_light_to_side(segp, s);
702         }
703 }
704
705
706 // -- mk021394 -- // --------------------------------------------------------------------------------------------------------------
707 // -- mk021394 -- //    Find the face:poly:vertex index in base_seg:base_common_side which is segment relative vertex v1
708 // -- mk021394 -- //    This very specific routine is subsidiary to med_assign_uvs_to_side.
709 // -- mk021394 -- void get_face_and_vert(segment *base_seg, int base_common_side, int v1, int *ff, int *vv, int *pi)
710 // -- mk021394 -- {
711 // -- mk021394 --       int     p,f,v;
712 // -- mk021394 -- 
713 // -- mk021394 --       for (f=0; f<base_seg->sides[base_common_side].num_faces; f++) {
714 // -- mk021394 --               face *fp = &base_seg->sides[base_common_side].faces[f];
715 // -- mk021394 --               for (p=0; p<fp->num_polys; p++) {
716 // -- mk021394 --                       poly *pp = &fp->polys[p];
717 // -- mk021394 --                       for (v=0; v<pp->num_vertices; v++)
718 // -- mk021394 --                               if (pp->verts[v] == v1) {
719 // -- mk021394 --                                       *ff = f;
720 // -- mk021394 --                                       *vv = v;
721 // -- mk021394 --                                       *pi = p;
722 // -- mk021394 --                                       return;
723 // -- mk021394 --                               }
724 // -- mk021394 --               }
725 // -- mk021394 --       }
726 // -- mk021394 -- 
727 // -- mk021394 --       Assert(0);      // Error -- Couldn't find face:vertex which matched vertex v1 on base_seg:base_common_side
728 // -- mk021394 -- }
729
730 // -- mk021394 -- // --------------------------------------------------------------------------------------------------------------
731 // -- mk021394 -- //    Find the vertex index in base_seg:base_common_side which is segment relative vertex v1
732 // -- mk021394 -- //    This very specific routine is subsidiary to med_assign_uvs_to_side.
733 // -- mk021394 -- void get_side_vert(segment *base_seg,int base_common_side,int v1,int *vv)
734 // -- mk021394 -- {
735 // -- mk021394 --       int     p,f,v;
736 // -- mk021394 -- 
737 // -- mk021394 --       Assert((base_seg->sides[base_common_side].tri_edge == 0) || (base_seg->sides[base_common_side].tri_edge == 1));
738 // -- mk021394 --       Assert(base_seg->sides[base_common_side].num_faces <= 2);
739 // -- mk021394 -- 
740 // -- mk021394 --       for (f=0; f<base_seg->sides[base_common_side].num_faces; f++) {
741 // -- mk021394 --               face *fp = &base_seg->sides[base_common_side].faces[f];
742 // -- mk021394 --               for (p=0; p<fp->num_polys; p++) {
743 // -- mk021394 --                       poly    *pp = &fp->polys[p];
744 // -- mk021394 --                       for (v=0; v<pp->num_vertices; v++)
745 // -- mk021394 --                               if (pp->verts[v] == v1) {
746 // -- mk021394 --                                       if (pp->num_vertices == 4) {
747 // -- mk021394 --                                               *vv = v;
748 // -- mk021394 --                                               return;
749 // -- mk021394 --                                       }
750 // -- mk021394 -- 
751 // -- mk021394 --                                       if (base_seg->sides[base_common_side].tri_edge == 0) {  // triangulated 012, 023, so if f==0, *vv = v, if f==1, *vv = v if v=0, else v+1
752 // -- mk021394 --                                               if ((f == 1) && (v > 0))
753 // -- mk021394 --                                                       v++;
754 // -- mk021394 --                                               *vv = v;
755 // -- mk021394 --                                               return;
756 // -- mk021394 --                                       } else {                                                                // triangulated 013, 123
757 // -- mk021394 --                                               if (f == 0) {
758 // -- mk021394 --                                                       if (v == 2)
759 // -- mk021394 --                                                               v++;
760 // -- mk021394 --                                               } else
761 // -- mk021394 --                                                       v++;
762 // -- mk021394 --                                               *vv = v;
763 // -- mk021394 --                                               return;
764 // -- mk021394 --                                       }
765 // -- mk021394 --                               }
766 // -- mk021394 --               }
767 // -- mk021394 --       }
768 // -- mk021394 -- 
769 // -- mk021394 --       Assert(0);      // Error -- Couldn't find face:vertex which matched vertex v1 on base_seg:base_common_side
770 // -- mk021394 -- }
771
772 //--rotate_uvs-- // --------------------------------------------------------------------------------------------------------------
773 //--rotate_uvs-- //     Rotate uvl coordinates uva, uvb about their center point by heading
774 //--rotate_uvs-- void rotate_uvs(uvl *uva, uvl *uvb, vms_vector *rvec)
775 //--rotate_uvs-- {
776 //--rotate_uvs--        uvl     uvc, uva1, uvb1;
777 //--rotate_uvs-- 
778 //--rotate_uvs--        uvc.u = (uva->u + uvb->u)/2;
779 //--rotate_uvs--        uvc.v = (uva->v + uvb->v)/2;
780 //--rotate_uvs-- 
781 //--rotate_uvs--        uva1.u = fixmul(uva->u - uvc.u, rvec->x) - fixmul(uva->v - uvc.v, rvec->z);
782 //--rotate_uvs--        uva1.v = fixmul(uva->u - uvc.u, rvec->z) + fixmul(uva->v - uvc.v, rvec->x);
783 //--rotate_uvs-- 
784 //--rotate_uvs--        uva->u = uva1.u + uvc.u;
785 //--rotate_uvs--        uva->v = uva1.v + uvc.v;
786 //--rotate_uvs-- 
787 //--rotate_uvs--        uvb1.u = fixmul(uvb->u - uvc.u, rvec->x) - fixmul(uvb->v - uvc.v, rvec->z);
788 //--rotate_uvs--        uvb1.v = fixmul(uvb->u - uvc.u, rvec->z) + fixmul(uvb->v - uvc.v, rvec->x);
789 //--rotate_uvs-- 
790 //--rotate_uvs--        uvb->u = uvb1.u + uvc.u;
791 //--rotate_uvs--        uvb->v = uvb1.v + uvc.v;
792 //--rotate_uvs-- }
793
794
795 // --------------------------------------------------------------------------------------------------------------
796 void med_assign_uvs_to_side(segment *con_seg, int con_common_side, segment *base_seg, int base_common_side, int abs_id1, int abs_id2)
797 {
798         uvl             uv1,uv2;
799         int             v,bv1,bv2, vv1, vv2;
800         int             cv1=0, cv2=0;
801
802         bv1 = -1;       bv2 = -1;
803
804         // Find which vertices in segment match abs_id1, abs_id2
805         for (v=0; v<MAX_VERTICES_PER_SEGMENT; v++) {
806                 if (base_seg->verts[v] == abs_id1)
807                         bv1 = v;
808                 if (base_seg->verts[v] == abs_id2)
809                         bv2 = v;
810                 if (con_seg->verts[v] == abs_id1)
811                         cv1 = v;
812                 if (con_seg->verts[v] == abs_id2)
813                         cv2 = v;
814         }
815
816         //      Now, bv1, bv2 are segment relative vertices in base segment which are the same as absolute vertices abs_id1, abs_id2
817         //           cv1, cv2 are segment relative vertices in conn segment which are the same as absolute vertices abs_id1, abs_id2
818
819         Assert((bv1 != -1) && (bv2 != -1) && (cv1 != -1) && (cv2 != -1));
820         Assert((uv1.u != uv2.u) || (uv1.v != uv2.v));
821
822         //      Now, scan 4 vertices in base side and 4 vertices in connected side.
823         //      Set uv1, uv2 to uv coordinates from base side which correspond to vertices bv1, bv2.
824         //      Set vv1, vv2 to relative vertex ids (in 0..3) in connecting side which correspond to cv1, cv2
825         vv1 = -1;       vv2 = -1;
826         for (v=0; v<4; v++) {
827                 if (bv1 == Side_to_verts[base_common_side][v])
828                         uv1 = base_seg->sides[base_common_side].uvls[v];
829
830                 if (bv2 == Side_to_verts[base_common_side][v])
831                         uv2 = base_seg->sides[base_common_side].uvls[v];
832
833                 if (cv1 == Side_to_verts[con_common_side][v])
834                         vv1 = v;
835
836                 if (cv2 == Side_to_verts[con_common_side][v])
837                         vv2 = v;
838         }
839
840         Assert( (vv1 != -1) && (vv2 != -1) );
841         assign_uvs_to_side(con_seg, con_common_side, &uv1, &uv2, vv1, vv2);
842 }
843
844
845 // -----------------------------------------------------------------------------
846 //      Given a base and a connecting segment, a side on each of those segments and two global vertex ids,
847 //      determine which side in each of the segments shares those two vertices.
848 //      This is used to propagate a texture map id to a connecting segment in an expected and desired way.
849 //      Since we can attach any side of a segment to any side of another segment, and do so in each case in
850 //      four different rotations (for a total of 6*6*4 = 144 ways), not having this nifty function will cause
851 //      great confusion.
852 void get_side_ids(segment *base_seg, segment *con_seg, int base_side, int con_side, int abs_id1, int abs_id2, int *base_common_side, int *con_common_side)
853 {
854         char            *base_vp,*con_vp;
855         int             v0,side;
856
857         *base_common_side = -1;
858
859         //      Find side in base segment which contains the two global vertex ids.
860         for (side=0; side<MAX_SIDES_PER_SEGMENT; side++) {
861                 if (side != base_side) {
862                         base_vp = Side_to_verts[side];
863                         for (v0=0; v0<4; v0++)
864                                 if (((base_seg->verts[(int) base_vp[v0]] == abs_id1) && (base_seg->verts[(int) base_vp[(v0+1) % 4]] == abs_id2)) || ((base_seg->verts[(int) base_vp[v0]] == abs_id2) && (base_seg->verts[(int)base_vp[ (v0+1) % 4]] == abs_id1))) {
865                                         Assert(*base_common_side == -1);                // This means two different sides shared the same edge with base_side == impossible!
866                                         *base_common_side = side;
867                                 }
868                 }
869         }
870
871         // Note: For connecting segment, process vertices in reversed order.
872         *con_common_side = -1;
873
874         //      Find side in connecting segment which contains the two global vertex ids.
875         for (side=0; side<MAX_SIDES_PER_SEGMENT; side++) {
876                 if (side != con_side) {
877                         con_vp = Side_to_verts[side];
878                         for (v0=0; v0<4; v0++)
879                                 if (((con_seg->verts[(int) con_vp[(v0 + 1) % 4]] == abs_id1) && (con_seg->verts[(int) con_vp[v0]] == abs_id2)) || ((con_seg->verts[(int) con_vp[(v0 + 1) % 4]] == abs_id2) && (con_seg->verts[(int) con_vp[v0]] == abs_id1))) {
880                                         Assert(*con_common_side == -1);         // This means two different sides shared the same edge with con_side == impossible!
881                                         *con_common_side = side;
882                                 }
883                 }
884         }
885
886 // mprintf((0,"side %3i adjacent to side %3i\n",*base_common_side,*con_common_side));
887
888         Assert((*base_common_side != -1) && (*con_common_side != -1));
889 }
890
891 // -----------------------------------------------------------------------------
892 //      Propagate texture map u,v coordinates from base_seg:base_side to con_seg:con_side.
893 //      The two vertices abs_id1 and abs_id2 are the only two vertices common to the two sides.
894 //      If uv_only_flag is 1, then don't assign texture map ids, only update the uv coordinates
895 //      If uv_only_flag is -1, then ONLY assign texture map ids, don't update the uv coordinates
896 void propagate_tmaps_to_segment_side(segment *base_seg, int base_side, segment *con_seg, int con_side, int abs_id1, int abs_id2, int uv_only_flag)
897 {
898         int             base_common_side,con_common_side;
899         int             tmap_num;
900
901         Assert ((uv_only_flag == -1) || (uv_only_flag == 0) || (uv_only_flag == 1));
902
903         // Set base_common_side = side in base_seg which contains edge abs_id1:abs_id2
904         // Set con_common_side = side in con_seg which contains edge abs_id1:abs_id2
905         if (base_seg != con_seg)
906                 get_side_ids(base_seg, con_seg, base_side, con_side, abs_id1, abs_id2, &base_common_side, &con_common_side);
907         else {
908                 base_common_side = base_side;
909                 con_common_side = con_side;
910         }
911
912         // Now, all faces in con_seg which are on side con_common_side get their tmap_num set to whatever tmap is assigned
913         // to whatever face I find which is on side base_common_side.
914         // First, find tmap_num for base_common_side.  If it doesn't exist (ie, there is a connection there), look at the segment
915         // that is connected through it.
916         if (!IS_CHILD(con_seg->children[con_common_side])) {
917                 if (!IS_CHILD(base_seg->children[base_common_side])) {
918                         // There is at least one face here, so get the tmap_num from there.
919                         tmap_num = base_seg->sides[base_common_side].tmap_num;
920
921                         // Now assign all faces in the connecting segment on side con_common_side to tmap_num.
922                         if ((uv_only_flag == -1) || (uv_only_flag == 0))
923                                 con_seg->sides[con_common_side].tmap_num = tmap_num;
924
925                         if (uv_only_flag != -1)
926                                 med_assign_uvs_to_side(con_seg, con_common_side, base_seg, base_common_side, abs_id1, abs_id2);
927
928                 } else {                        // There are no faces here, there is a connection, trace through the connection.
929                         int     cside;
930
931                         cside = find_connect_side(base_seg, &Segments[base_seg->children[base_common_side]]);
932                         propagate_tmaps_to_segment_side(&Segments[base_seg->children[base_common_side]], cside, con_seg, con_side, abs_id1, abs_id2, uv_only_flag);
933                 }
934         }
935
936 }
937
938 sbyte   Edge_between_sides[MAX_SIDES_PER_SEGMENT][MAX_SIDES_PER_SEGMENT][2] = {
939 //              left            top             right           bottom  back            front
940         { {-1,-1}, { 3, 7}, {-1,-1}, { 2, 6}, { 6, 7}, { 2, 3} },       // left
941         { { 3, 7}, {-1,-1}, { 0, 4}, {-1,-1}, { 4, 7}, { 0, 3} },       // top
942         { {-1,-1}, { 0, 4}, {-1,-1}, { 1, 5}, { 4, 5}, { 0, 1} },       // right
943         { { 2, 6}, {-1,-1}, { 1, 5}, {-1,-1}, { 5, 6}, { 1, 2} },       // bottom
944         { { 6, 7}, { 4, 7}, { 4, 5}, { 5, 6}, {-1,-1}, {-1,-1} },       // back
945         { { 2, 3}, { 0, 3}, { 0, 1}, { 1, 2}, {-1,-1}, {-1,-1} }};      // front
946
947 // -----------------------------------------------------------------------------
948 //      Propagate texture map u,v coordinates to base_seg:back_side from base_seg:some-other-side
949 //      There is no easy way to figure out which side is adjacent to another side along some edge, so we do a bit of searching.
950 void med_propagate_tmaps_to_back_side(segment *base_seg, int back_side, int uv_only_flag)
951 {
952         int     v1=0,v2=0;
953         int     s,ss,tmap_num,back_side_tmap;
954
955         if (IS_CHILD(base_seg->children[back_side]))
956                 return;         // connection, so no sides here.
957
958         //      Scan all sides, look for an occupied side which is not back_side or Side_opposite[back_side]
959         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
960                 if ((s != back_side) && (s != Side_opposite[back_side])) {
961                         v1 = Edge_between_sides[s][back_side][0];
962                         v2 = Edge_between_sides[s][back_side][1];
963                         goto found1;
964                 }
965         Assert(0);              // Error -- couldn't find edge != back_side and Side_opposite[back_side]
966 found1: ;
967         Assert( (v1 != -1) && (v2 != -1));              // This means there was no shared edge between the two sides.
968
969         propagate_tmaps_to_segment_side(base_seg, s, base_seg, back_side, base_seg->verts[v1], base_seg->verts[v2], uv_only_flag);
970
971         //      Assign an unused tmap id to the back side.
972         //      Note that this can get undone by the caller if this was not part of a new attach, but a rotation or a scale (which
973         //      both do attaches).
974         //      First see if tmap on back side is anywhere else.
975         if (!uv_only_flag) {
976                 back_side_tmap = base_seg->sides[back_side].tmap_num;
977                 for (s=0; s<MAX_SIDES_PER_SEGMENT; s++) {
978                         if (s != back_side)
979                                 if (base_seg->sides[s].tmap_num == back_side_tmap) {
980                                         for (tmap_num=0; tmap_num < MAX_SIDES_PER_SEGMENT; tmap_num++) {
981                                                 for (ss=0; ss<MAX_SIDES_PER_SEGMENT; ss++)
982                                                         if (ss != back_side)
983                                                                 if (base_seg->sides[ss].tmap_num == New_segment.sides[tmap_num].tmap_num)
984                                                                         goto found2;            // current texture map (tmap_num) is used on current (ss) side, so try next one
985                                                 // Current texture map (tmap_num) has not been used, assign to all faces on back_side.
986                                                 base_seg->sides[back_side].tmap_num = New_segment.sides[tmap_num].tmap_num;
987                                                 goto done1;
988                                         found2: ;
989                                         }
990                                 }
991                 }
992         done1: ;
993         }
994
995 }
996
997 int fix_bogus_uvs_on_side(void)
998 {
999         med_propagate_tmaps_to_back_side(Cursegp, Curside, 1);
1000         return 0;
1001 }
1002
1003 void fix_bogus_uvs_on_side1(segment *sp, int sidenum, int uvonly_flag)
1004 {
1005         side    *sidep = &sp->sides[sidenum];
1006
1007         if ((sidep->uvls[0].u == 0) && (sidep->uvls[1].u == 0) && (sidep->uvls[2].u == 0)) {
1008                 mprintf((0,"Found bogus segment %i, side %i\n", sp-Segments, sidenum));
1009                 med_propagate_tmaps_to_back_side(sp, sidenum, uvonly_flag);
1010         }
1011 }
1012
1013 void fix_bogus_uvs_seg(segment *segp)
1014 {
1015         int     s;
1016
1017         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++) {
1018                 if (!IS_CHILD(segp->children[s]))
1019                         fix_bogus_uvs_on_side1(segp, s, 1);
1020         }
1021 }
1022
1023 int fix_bogus_uvs_all(void)
1024 {
1025         int     seg;
1026
1027         for (seg=0; seg<=Highest_segment_index; seg++)
1028                 if (Segments[seg].segnum != -1)
1029                         fix_bogus_uvs_seg(&Segments[seg]);
1030         return 0;
1031 }
1032
1033 // -----------------------------------------------------------------------------
1034 //      Propagate texture map u,v coordinates to base_seg:back_side from base_seg:some-other-side
1035 //      There is no easy way to figure out which side is adjacent to another side along some edge, so we do a bit of searching.
1036 void med_propagate_tmaps_to_any_side(segment *base_seg, int back_side, int tmap_num, int uv_only_flag)
1037 {
1038         int     v1=0,v2=0;
1039         int     s;
1040
1041         //      Scan all sides, look for an occupied side which is not back_side or Side_opposite[back_side]
1042         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
1043                 if ((s != back_side) && (s != Side_opposite[back_side])) {
1044                         v1 = Edge_between_sides[s][back_side][0];
1045                         v2 = Edge_between_sides[s][back_side][1];
1046                         goto found1;
1047                 }
1048         Assert(0);              // Error -- couldn't find edge != back_side and Side_opposite[back_side]
1049 found1: ;
1050         Assert( (v1 != -1) && (v2 != -1));              // This means there was no shared edge between the two sides.
1051
1052         propagate_tmaps_to_segment_side(base_seg, s, base_seg, back_side, base_seg->verts[v1], base_seg->verts[v2], uv_only_flag);
1053
1054         base_seg->sides[back_side].tmap_num = tmap_num;
1055
1056 }
1057
1058 // -----------------------------------------------------------------------------
1059 //      Segment base_seg is connected through side base_side to segment con_seg on con_side.
1060 //      For all walls in con_seg, find the wall in base_seg which shares an edge.  Copy tmap_num
1061 //      from that side in base_seg to the wall in con_seg.  If the wall in base_seg is not present
1062 //      (ie, there is another segment connected through it), follow the connection through that
1063 //      segment to get the wall in the connected segment which shares the edge, and get tmap_num from there.
1064 void propagate_tmaps_to_segment_sides(segment *base_seg, int base_side, segment *con_seg, int con_side, int uv_only_flag)
1065 {
1066         char            *base_vp,*con_vp;
1067         short           abs_id1,abs_id2;
1068         int             v;
1069
1070         base_vp = Side_to_verts[base_side];
1071         con_vp = Side_to_verts[con_side];
1072
1073         // Do for each edge on connecting face.
1074         for (v=0; v<4; v++) {
1075                 abs_id1 = base_seg->verts[(int) base_vp[v]];
1076                 abs_id2 = base_seg->verts[(int) base_vp[(v+1) % 4]];
1077                 propagate_tmaps_to_segment_side(base_seg, base_side, con_seg, con_side, abs_id1, abs_id2, uv_only_flag);
1078         }
1079
1080 }
1081
1082 // -----------------------------------------------------------------------------
1083 //      Propagate texture maps in base_seg to con_seg.
1084 //      For each wall in con_seg, find the wall in base_seg which shared an edge.  Copy tmap_num from that
1085 //      wall in base_seg to the wall in con_seg.  If the wall in base_seg is not present, then look at the
1086 //      segment connected through base_seg through the wall.  The wall with a common edge is the new wall
1087 //      of interest.  Continue searching in this way until a wall of interest is present.
1088 void med_propagate_tmaps_to_segments(segment *base_seg,segment *con_seg, int uv_only_flag)
1089 {
1090         int             s;
1091
1092 // mprintf((0,"Propagating segments from %i to %i\n",base_seg-Segments,con_seg-Segments));
1093         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
1094                 if (base_seg->children[s] == con_seg-Segments)
1095                         propagate_tmaps_to_segment_sides(base_seg, s, con_seg, find_connect_side(base_seg, con_seg), uv_only_flag);
1096
1097         con_seg->static_light = base_seg->static_light;
1098
1099         validate_uv_coordinates(con_seg);
1100 }
1101
1102
1103 // -------------------------------------------------------------------------------
1104 //      Copy texture map uvs from srcseg to destseg.
1105 //      If two segments have different face structure (eg, destseg has two faces on side 3, srcseg has only 1)
1106 //      then assign uvs according to side vertex id, not face vertex id.
1107 void copy_uvs_seg_to_seg(segment *destseg,segment *srcseg)
1108 {
1109         int     s;
1110
1111         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++) {
1112                 destseg->sides[s].tmap_num = srcseg->sides[s].tmap_num;
1113                 destseg->sides[s].tmap_num2 = srcseg->sides[s].tmap_num2;
1114         }
1115
1116         destseg->static_light = srcseg->static_light;
1117 }
1118
1119 //      _________________________________________________________________________________________________________________________
1120 //      Maximum distance between a segment containing light to a segment to receive light.
1121 #define LIGHT_DISTANCE_THRESHOLD        (F1_0*80)
1122 fix     Magical_light_constant = (F1_0*16);
1123
1124 // int  Seg0, Seg1;
1125
1126 //int   Bugseg = 27;
1127
1128 typedef struct {
1129         sbyte                   flag, hit_type;
1130         vms_vector      vector;
1131 } hash_info;
1132
1133 #define FVI_HASH_SIZE 8
1134 #define FVI_HASH_AND_MASK (FVI_HASH_SIZE - 1)
1135
1136 //      Note: This should be malloced.
1137 //                      Also, the vector should not be 12 bytes, you should only care about some smaller portion of it.
1138 hash_info       fvi_cache[FVI_HASH_SIZE];
1139 int     Hash_hits=0, Hash_retries=0, Hash_calcs=0;
1140
1141 //      -----------------------------------------------------------------------------------------
1142 //      Set light from a light source.
1143 //      Light incident on a surface is defined by the light incident at its points.
1144 //      Light at a point = K * (V . N) / d
1145 //      where:
1146 //              K = some magical constant to make everything look good
1147 //              V = normalized vector from light source to point
1148 //              N = surface normal at point
1149 //              d = distance from light source to point
1150 //      (Note that the above equation can be simplified to K * (VV . N) / d^2 where VV = non-normalized V)
1151 //      Light intensity emitted from a light source is defined to be cast from four points.
1152 //      These four points are 1/64 of the way from the corners of the light source to the center
1153 //      of its segment.  By assuming light is cast from these points, rather than from on the
1154 //      light surface itself, light will be properly cast on the light surface.  Otherwise, the
1155 //      vector V would be the null vector.
1156 //      If quick_light set, then don't use find_vector_intersection
1157 void cast_light_from_side(segment *segp, int light_side, fix light_intensity, int quick_light)
1158 {
1159         vms_vector      segment_center;
1160         int                     segnum,sidenum,vertnum, lightnum;
1161
1162         compute_segment_center(&segment_center, segp);
1163
1164 //mprintf((0, "From [%i %i %7.3f]:  ", segp-Segments, light_side, f2fl(light_intensity)));
1165
1166         //      Do for four lights, one just inside each corner of side containing light.
1167         for (lightnum=0; lightnum<4; lightnum++) {
1168                 int                     light_vertex_num, i;
1169                 vms_vector      vector_to_center;
1170                 vms_vector      light_location;
1171                 // fix                  inverse_segment_magnitude;
1172
1173                 light_vertex_num = segp->verts[Side_to_verts[light_side][lightnum]];
1174                 light_location = Vertices[light_vertex_num];
1175
1176
1177         //      New way, 5/8/95: Move towards center irrespective of size of segment.
1178         vm_vec_sub(&vector_to_center, &segment_center, &light_location);
1179         vm_vec_normalize_quick(&vector_to_center);
1180         vm_vec_add2(&light_location, &vector_to_center);
1181
1182 // -- Old way, before 5/8/95 --         // -- This way was kind of dumb.  In larger segments, you move LESS towards the center.
1183 // -- Old way, before 5/8/95 --         //    Main problem, though, is vertices don't illuminate themselves well in oblong segments because the dot product is small.
1184 // -- Old way, before 5/8/95 --         vm_vec_sub(&vector_to_center, &segment_center, &light_location);
1185 // -- Old way, before 5/8/95 --         inverse_segment_magnitude = fixdiv(F1_0/5, vm_vec_mag(&vector_to_center));
1186 // -- Old way, before 5/8/95 --         vm_vec_scale_add(&light_location, &light_location, &vector_to_center, inverse_segment_magnitude);
1187
1188                 for (segnum=0; segnum<=Highest_segment_index; segnum++) {
1189                         segment         *rsegp = &Segments[segnum];
1190                         vms_vector      r_segment_center;
1191                         fix                     dist_to_rseg;
1192
1193                         for (i=0; i<FVI_HASH_SIZE; i++)
1194                                 fvi_cache[i].flag = 0;
1195
1196                         //      efficiency hack (I hope!), for faraway segments, don't check each point.
1197                         compute_segment_center(&r_segment_center, rsegp);
1198                         dist_to_rseg = vm_vec_dist_quick(&r_segment_center, &segment_center);
1199
1200                         if (dist_to_rseg <= LIGHT_DISTANCE_THRESHOLD) {
1201                                 for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++) {
1202                                         if (WALL_IS_DOORWAY(rsegp, sidenum) != WID_NO_WALL) {
1203                                                 side                    *rsidep = &rsegp->sides[sidenum];
1204                                                 vms_vector      *side_normalp = &rsidep->normals[0];    //      kinda stupid? always use vector 0.
1205
1206 //mprintf((0, "[%i %i], ", rsegp-Segments, sidenum));
1207                                                 for (vertnum=0; vertnum<4; vertnum++) {
1208                                                         fix                     distance_to_point, light_at_point, light_dot;
1209                                                         vms_vector      vert_location, vector_to_light;
1210                                                         int                     abs_vertnum;
1211
1212                                                         abs_vertnum = rsegp->verts[Side_to_verts[sidenum][vertnum]];
1213                                                         vert_location = Vertices[abs_vertnum];
1214                                                         distance_to_point = vm_vec_dist_quick(&vert_location, &light_location);
1215                                                         vm_vec_sub(&vector_to_light, &light_location, &vert_location);
1216                                                         vm_vec_normalize(&vector_to_light);
1217
1218                                                         //      Hack: In oblong segments, it's possible to get a very small dot product
1219                                                         //      but the light source is very nearby (eg, illuminating light itself!).
1220                                                         light_dot = vm_vec_dot(&vector_to_light, side_normalp);
1221                                                         if (distance_to_point < F1_0)
1222                                                                 if (light_dot > 0)
1223                                                                         light_dot = (light_dot + F1_0)/2;
1224
1225                                                         if (light_dot > 0) {
1226                                                                 light_at_point = fixdiv(fixmul(light_dot, light_dot), distance_to_point);
1227                                                                 light_at_point = fixmul(light_at_point, Magical_light_constant);
1228                                                                 if (light_at_point >= 0) {
1229                                                                         fvi_info        hit_data;
1230                                                                         int             hit_type;
1231                                                                         vms_vector      vert_location_1, r_vector_to_center;
1232                                                                         fix             inverse_segment_magnitude;
1233
1234                                                                         vm_vec_sub(&r_vector_to_center, &r_segment_center, &vert_location);
1235                                                                         inverse_segment_magnitude = fixdiv(F1_0/3, vm_vec_mag(&r_vector_to_center));
1236                                                                         vm_vec_scale_add(&vert_location_1, &vert_location, &r_vector_to_center, inverse_segment_magnitude);
1237                                                                         vert_location = vert_location_1;
1238
1239 //if ((segp-Segments == 199) && (rsegp-Segments==199))
1240 //      Int3();
1241 // Seg0 = segp-Segments;
1242 // Seg1 = rsegp-Segments;
1243                                                                         if (!quick_light) {
1244                                                                                 int hash_value = Side_to_verts[sidenum][vertnum];
1245                                                                                 hash_info       *hashp = &fvi_cache[hash_value];
1246                                                                                 while (1) {
1247                                                                                         if (hashp->flag) {
1248                                                                                                 if ((hashp->vector.x == vector_to_light.x) && (hashp->vector.y == vector_to_light.y) && (hashp->vector.z == vector_to_light.z)) {
1249 //mprintf((0, "{CACHE %4x} ", hash_value));
1250                                                                                                         hit_type = hashp->hit_type;
1251                                                                                                         Hash_hits++;
1252                                                                                                         break;
1253                                                                                                 } else {
1254                                                                                                         Int3(); // How is this possible?  Should be no hits!
1255                                                                                                         Hash_retries++;
1256                                                                                                         hash_value = (hash_value+1) & FVI_HASH_AND_MASK;
1257                                                                                                         hashp = &fvi_cache[hash_value];
1258                                                                                                 }
1259                                                                                         } else {
1260 //mprintf((0, "\nH:%04x ", hash_value));
1261                                                                                                 fvi_query fq;
1262
1263                                                                                                 Hash_calcs++;
1264                                                                                                 hashp->vector = vector_to_light;
1265                                                                                                 hashp->flag = 1;
1266
1267                                                                                                 fq.p0                                           = &light_location;
1268                                                                                                 fq.startseg                             = segp-Segments;
1269                                                                                                 fq.p1                                           = &vert_location;
1270                                                                                                 fq.rad                                  = 0;
1271                                                                                                 fq.thisobjnum                   = -1;
1272                                                                                                 fq.ignore_obj_list      = NULL;
1273                                                                                                 fq.flags                                        = 0;
1274
1275                                                                                                 hit_type = find_vector_intersection(&fq,&hit_data);
1276                                                                                                 hashp->hit_type = hit_type;
1277                                                                                                 break;
1278                                                                                         }
1279                                                                                 }
1280                                                                         } else
1281                                                                                 hit_type = HIT_NONE;
1282 //mprintf((0, "hit=%i ", hit_type));
1283                                                                         switch (hit_type) {
1284                                                                                 case HIT_NONE:
1285                                                                                         light_at_point = fixmul(light_at_point, light_intensity);
1286                                                                                         rsidep->uvls[vertnum].l += light_at_point;
1287 //mprintf((0, "(%5.2f) ", f2fl(light_at_point)));
1288                                                                                         if (rsidep->uvls[vertnum].l > F1_0)
1289                                                                                                 rsidep->uvls[vertnum].l = F1_0;
1290                                                                                         break;
1291                                                                                 case HIT_WALL:
1292                                                                                         break;
1293                                                                                 case HIT_OBJECT:
1294                                                                                         Int3(); // Hit object, should be ignoring objects!
1295                                                                                         break;
1296                                                                                 case HIT_BAD_P0:
1297                                                                                         Int3(); //      Ugh, this thing again, what happened, what does it mean?
1298                                                                                         break;
1299                                                                         }
1300                                                                 }       //      end if (light_at_point...
1301                                                         }       // end if (light_dot >...
1302                                                 }       //      end for (vertnum=0...
1303                                         }       //      end if (rsegp...
1304                                 }       //      end for (sidenum=0...
1305                         }       //      end if (dist_to_rseg...
1306
1307                 }       //      end for (segnum=0...
1308
1309         }       //      end for (lightnum=0...
1310
1311 //mprintf((0, "\n"));
1312 }
1313
1314
1315 //      ------------------------------------------------------------------------------------------
1316 //      Zero all lighting values.
1317 void calim_zero_light_values(void)
1318 {
1319         int     segnum, sidenum, vertnum;
1320
1321         for (segnum=0; segnum<=Highest_segment_index; segnum++) {
1322                 segment *segp = &Segments[segnum];
1323                 for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++) {
1324                         side    *sidep = &segp->sides[sidenum];
1325                         for (vertnum=0; vertnum<4; vertnum++)
1326                                 sidep->uvls[vertnum].l = F1_0/64;       // Put a tiny bit of light here.
1327                 }
1328                 Segments[segnum].static_light = F1_0/64;
1329         }
1330 }
1331
1332
1333 //      ------------------------------------------------------------------------------------------
1334 //      Used in setting average light value in a segment, cast light from a side to the center
1335 //      of all segments.
1336 void cast_light_from_side_to_center(segment *segp, int light_side, fix light_intensity, int quick_light)
1337 {
1338         vms_vector      segment_center;
1339         int                     segnum, lightnum;
1340
1341         compute_segment_center(&segment_center, segp);
1342
1343         //      Do for four lights, one just inside each corner of side containing light.
1344         for (lightnum=0; lightnum<4; lightnum++) {
1345                 int                     light_vertex_num;
1346                 vms_vector      vector_to_center;
1347                 vms_vector      light_location;
1348
1349                 light_vertex_num = segp->verts[Side_to_verts[light_side][lightnum]];
1350                 light_location = Vertices[light_vertex_num];
1351                 vm_vec_sub(&vector_to_center, &segment_center, &light_location);
1352                 vm_vec_scale_add(&light_location, &light_location, &vector_to_center, F1_0/64);
1353
1354                 for (segnum=0; segnum<=Highest_segment_index; segnum++) {
1355                         segment         *rsegp = &Segments[segnum];
1356                         vms_vector      r_segment_center;
1357                         fix                     dist_to_rseg;
1358 //if ((segp == &Segments[Bugseg]) && (rsegp == &Segments[Bugseg]))
1359 //      Int3();
1360                         compute_segment_center(&r_segment_center, rsegp);
1361                         dist_to_rseg = vm_vec_dist_quick(&r_segment_center, &segment_center);
1362
1363                         if (dist_to_rseg <= LIGHT_DISTANCE_THRESHOLD) {
1364                                 fix     light_at_point;
1365                                 if (dist_to_rseg > F1_0)
1366                                         light_at_point = fixdiv(Magical_light_constant, dist_to_rseg);
1367                                 else
1368                                         light_at_point = Magical_light_constant;
1369
1370                                 if (light_at_point >= 0) {
1371                                         int             hit_type;
1372
1373                                         if (!quick_light) {
1374                                                 fvi_query fq;
1375                                                 fvi_info        hit_data;
1376
1377                                                 fq.p0                                           = &light_location;
1378                                                 fq.startseg                             = segp-Segments;
1379                                                 fq.p1                                           = &r_segment_center;
1380                                                 fq.rad                                  = 0;
1381                                                 fq.thisobjnum                   = -1;
1382                                                 fq.ignore_obj_list      = NULL;
1383                                                 fq.flags                                        = 0;
1384
1385                                                 hit_type = find_vector_intersection(&fq,&hit_data);
1386                                         }
1387                                         else
1388                                                 hit_type = HIT_NONE;
1389
1390                                         switch (hit_type) {
1391                                                 case HIT_NONE:
1392                                                         light_at_point = fixmul(light_at_point, light_intensity);
1393                                                         if (light_at_point >= F1_0)
1394                                                                 light_at_point = F1_0-1;
1395                                                         rsegp->static_light += light_at_point;
1396                                                         if (segp->static_light < 0)     // if it went negative, saturate
1397                                                                 segp->static_light = 0;
1398                                                         break;
1399                                                 case HIT_WALL:
1400                                                         break;
1401                                                 case HIT_OBJECT:
1402                                                         Int3(); // Hit object, should be ignoring objects!
1403                                                         break;
1404                                                 case HIT_BAD_P0:
1405                                                         Int3(); //      Ugh, this thing again, what happened, what does it mean?
1406                                                         break;
1407                                         }
1408                                 }       //      end if (light_at_point...
1409                         }       //      end if (dist_to_rseg...
1410
1411                 }       //      end for (segnum=0...
1412
1413         }       //      end for (lightnum=0...
1414
1415 }
1416
1417 //      ------------------------------------------------------------------------------------------
1418 //      Process all lights.
1419 void calim_process_all_lights(int quick_light)
1420 {
1421         int     segnum, sidenum;
1422
1423         for (segnum=0; segnum<=Highest_segment_index; segnum++) {
1424                 segment *segp = &Segments[segnum];
1425                 mprintf((0, "."));
1426                 for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++) {
1427                         // if (!IS_CHILD(segp->children[sidenum])) {
1428                         if (WALL_IS_DOORWAY(segp, sidenum) != WID_NO_WALL) {
1429                                 side    *sidep = &segp->sides[sidenum];
1430                                 fix     light_intensity;
1431
1432                                 light_intensity = TmapInfo[sidep->tmap_num].lighting + TmapInfo[sidep->tmap_num2 & 0x3fff].lighting;
1433
1434 //                              if (segp->sides[sidenum].wall_num != -1) {
1435 //                                      int     wall_num, bitmap_num, effect_num;
1436 //                                      wall_num = segp->sides[sidenum].wall_num;
1437 //                                      effect_num = Walls[wall_num].type;
1438 //                                      bitmap_num = effects_bm_num[effect_num];
1439 //
1440 //                                      light_intensity += TmapInfo[bitmap_num].lighting;
1441 //                              }
1442
1443                                 if (light_intensity) {
1444                                         light_intensity /= 4;                   // casting light from four spots, so divide by 4.
1445                                         cast_light_from_side(segp, sidenum, light_intensity, quick_light);
1446                                         cast_light_from_side_to_center(segp, sidenum, light_intensity, quick_light);
1447                                 }
1448                         }
1449                 }
1450         }
1451 }
1452
1453 //      ------------------------------------------------------------------------------------------
1454 //      Apply static light in mine.
1455 //      First, zero all light values.
1456 //      Then, for all light sources, cast their light.
1457 void cast_all_light_in_mine(int quick_flag)
1458 {
1459
1460         validate_segment_all();
1461
1462         calim_zero_light_values();
1463
1464         calim_process_all_lights(quick_flag);
1465
1466 }
1467
1468 // int  Fvit_num = 1000;
1469 // 
1470 // fix find_vector_intersection_test(void)
1471 // {
1472 //      int             i;
1473 //      fvi_info        hit_data;
1474 //      int             p0_seg, p1_seg, this_objnum, ignore_obj, check_obj_flag;
1475 //      fix             rad;
1476 //      int             start_time = timer_get_milliseconds();;
1477 //      vms_vector      p0,p1;
1478 // 
1479 //      ignore_obj = 1;
1480 //      check_obj_flag = 0;
1481 //      this_objnum = -1;
1482 //      rad = F1_0/4;
1483 // 
1484 //      for (i=0; i<Fvit_num; i++) {
1485 //              p0_seg = d_rand()*(Highest_segment_index+1)/32768;
1486 //              compute_segment_center(&p0, &Segments[p0_seg]);
1487 // 
1488 //              p1_seg = d_rand()*(Highest_segment_index+1)/32768;
1489 //              compute_segment_center(&p1, &Segments[p1_seg]);
1490 // 
1491 //              find_vector_intersection(&hit_data, &p0, p0_seg, &p1, rad, this_objnum, ignore_obj, check_obj_flag);
1492 //      }
1493 // 
1494 //      return timer_get_milliseconds() - start_time;
1495 // }
1496
1497 vms_vector      Normals[MAX_SEGMENTS*12];
1498
1499 int     Normal_nearness = 4;
1500
1501 int normal_near(vms_vector *v1, vms_vector *v2)
1502 {
1503         if (abs(v1->x - v2->x) < Normal_nearness)
1504                 if (abs(v1->y - v2->y) < Normal_nearness)
1505                         if (abs(v1->z - v2->z) < Normal_nearness)
1506                                 return 1;
1507         return 0;
1508 }
1509
1510 int     Total_normals=0;
1511 int     Diff_normals=0;
1512
1513 void print_normals(void)
1514 {
1515         int                     i,j,s,n,nn;
1516         // vms_vector   *normal;
1517         int                     num_normals=0;
1518
1519         Total_normals = 0;
1520         Diff_normals = 0;
1521
1522         for (i=0; i<=Highest_segment_index; i++)
1523                 for (s=0; s<6; s++) {
1524                         if (Segments[i].sides[s].type == SIDE_IS_QUAD)
1525                                 nn=1;
1526                         else
1527                                 nn=2;
1528                         for (n=0; n<nn; n++) {
1529                                 for (j=0; j<num_normals; j++)
1530                                         if (normal_near(&Segments[i].sides[s].normals[n],&Normals[j]))
1531                                                 break;
1532                                 if (j == num_normals) {
1533                                         Normals[num_normals++] = Segments[i].sides[s].normals[n];
1534                                         Diff_normals++;
1535                                 }
1536                                 Total_normals++;
1537                         }
1538                 }
1539
1540 }
1541