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