Debian Codegraph @

similar/main/gameseg.cpp

raw
1 /*
2 * Portions of this file are copyright Rebirth contributors and licensed as
3 * described in COPYING.txt.
4 * Portions of this file are copyright Parallax Software and licensed
5 * according to the Parallax license below.
6 * See COPYING.txt for license details.
7
8 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
9 SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
10 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
11 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
12 IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
13 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
14 FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
15 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
16 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
17 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
18 */
19
20 /*
21 *
22 * Functions moved from segment.c to make editor separable from game.
23 *
24 */
25
26 #include <algorithm>
27 #include <cassert>
28 #include <numeric>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h> // for memset()
32
33 #include "u_mem.h"
34 #include "inferno.h"
35 #include "game.h"
36 #include "dxxerror.h"
37 #include "console.h"
38 #include "vecmat.h"
39 #include "gameseg.h"
40 #include "wall.h"
41 #include "textures.h"
42 #include "object.h"
43 #include "byteutil.h"
44 #include "lighting.h"
45 #include "mission.h"
46 #if DXX_USE_EDITOR
47 #include "editor/editor.h"
48 #endif
49
50 #include "compiler-range_for.h"
51 #include "d_array.h"
52 #include "d_construct.h"
53 #include "d_levelstate.h"
54 #include "d_range.h"
55 #include "d_zip.h"
56 #include "partial_range.h"
57
58 using std::min;
59
60 namespace dcx {
61 namespace {
62
63 class abs_vertex_lists_predicate
64 {
65 const enumerated_array<vertnum_t, MAX_VERTICES_PER_SEGMENT, segment_relative_vertnum> &m_vp;
66 const enumerated_array<segment_relative_vertnum, 4, side_relative_vertnum> &m_sv;
67 public:
68 abs_vertex_lists_predicate(const shared_segment &seg, const sidenum_t sidenum) :
69 m_vp(seg.verts), m_sv(Side_to_verts[sidenum])
70 {
71 }
72 vertnum_t operator()(const side_relative_vertnum vv) const
73 {
74 return m_vp[m_sv[vv]];
75 }
76 };
77
78 struct verts_for_normal
79 {
80 std::array<vertnum_t, 4> vsorted;
81 verts_for_normal(vertnum_t v0, vertnum_t v1, vertnum_t v2, vertnum_t v3) :
82 vsorted{{v0, v1, v2, v3}}
83 {
84 }
85 };
86
87 // How far a point can be from a plane, and still be "in" the plane
88 #define PLANE_DIST_TOLERANCE 250
89
90 static vms_vector compute_center_point_on_side(fvcvertptr &vcvertptr, const enumerated_array<vertnum_t, MAX_VERTICES_PER_SEGMENT, segment_relative_vertnum> &verts, const sidenum_t side)
91 {
92 vms_vector vp{};
93 range_for (auto &v, Side_to_verts[side])
94 vm_vec_add2(vp, vcvertptr(verts[v]));
95 vm_vec_scale(vp, F1_0 / 4);
96 return vp;
97 }
98
99 static vms_vector compute_segment_center(fvcvertptr &vcvertptr, const std::array<vertnum_t, MAX_VERTICES_PER_SEGMENT> &verts)
100 {
101 vms_vector vp{};
102 range_for (auto &v, verts)
103 vm_vec_add2(vp, vcvertptr(v));
104 vm_vec_scale(vp, F1_0 / 8);
105 return vp;
106 }
107
108 [[noreturn]]
109 dxx_compiler_attribute_cold
110 static void create_vertex_list_from_invalid_side(const shared_segment &segp, const shared_side &sidep)
111 {
112 throw shared_side::illegal_type(segp, sidep);
113 }
114
115 // Fill in array with four absolute point numbers for a given side
116 [[nodiscard]]
117 static side_vertnum_list_t get_side_verts(const enumerated_array<vertnum_t, MAX_VERTICES_PER_SEGMENT, segment_relative_vertnum> &vp, const sidenum_t sidenum)
118 {
119 side_vertnum_list_t vertlist;
120 auto &sv = Side_to_verts[sidenum];
121 for (auto &&[ovl, isv] : zip(vertlist, sv))
122 ovl = vp[isv];
123 return vertlist;
124 }
125
126 template <typename V>
127 [[nodiscard]]
128 static vertex_array_side_type create_vertex_lists_from_values(auto &va, const shared_segment &segp, const shared_side &sidep, const V &&f0, const V &&f1, const V &&f2, const V &&f3)
129 {
130 const auto type{sidep.type};
131 if (type == side_type::tri_13)
132 {
133 va[0] = va[5] = f3;
134 va[1] = f0;
135 va[2] = va[3] = f1;
136 va[4] = f2;
137 return vertex_array_side_type::triangle;
138 }
139 va[0] = f0;
140 va[1] = f1;
141 va[2] = f2;
142 switch (type)
143 {
144 case side_type::quad:
145 va[3] = f3;
146 /* Unused, but required to prevent bogus
147 * -Wmaybe-uninitialized in check_segment_connections
148 */
149 va[4] = va[5] = {};
150 DXX_MAKE_MEM_UNDEFINED(std::span(va).template subspan<4, 2>());
151 return vertex_array_side_type::quad;
152 case side_type::tri_02:
153 va[3] = f2;
154 va[4] = f3;
155 va[5] = f0;
156
157 //IMPORTANT: DON'T CHANGE THIS CODE WITHOUT CHANGING GET_SEG_MASKS()
158 //CREATE_ABS_VERTEX_LISTS(), CREATE_ALL_VERTEX_LISTS(), CREATE_ALL_VERTNUM_LISTS()
159 return vertex_array_side_type::triangle;
160 default:
161 create_vertex_list_from_invalid_side(segp, sidep);
162 }
163 }
164
165 static inline vertex_array_side_type create_vertex_lists_by_predicate(auto &&va, const shared_segment &segp, const shared_side &sidep, const auto &&f)
166 {
167 return create_vertex_lists_from_values(va, segp, sidep, f(side_relative_vertnum::_0), f(side_relative_vertnum::_1), f(side_relative_vertnum::_2), f(side_relative_vertnum::_3));
168 }
169
170 // ------------------------------------------------------------------------------------------
171 // Extract a vector from a segment. The vector goes from the start face to the end face.
172 // The point on each face is the average of the four points forming the face.
173 [[nodiscard]]
174 static vms_vector extract_vector_from_segment(fvcvertptr &vcvertptr, const shared_segment &sp, const sidenum_t istart, const sidenum_t iend)
175 {
176 vms_vector vp{};
177 auto &start = Side_to_verts[istart];
178 auto &end = Side_to_verts[iend];
179 auto &verts = sp.verts;
180 for (const auto &&[vs, ve] : zip(start, end))
181 {
182 vm_vec_sub2(vp, vcvertptr(verts[vs]));
183 vm_vec_add2(vp, vcvertptr(verts[ve]));
184 }
185 vm_vec_scale(vp,F1_0/4);
186 return vp;
187 }
188
189 //this was converted from get_seg_masks()...it fills in an array of 6
190 //elements for the distance behind each side, or zero if not behind
191 //only gets centermask, and assumes zero rad
192 [[nodiscard]]
193 static auto build_side_dists(fvcvertptr &vcvertptr, const vms_vector &checkp, const shared_segment &segnum)
194 {
195 struct
196 {
197 sidemask_t centermask;
198 per_side_array<fix> distances;
199 } result{};
200 //check point against each side of segment. return bitmask
201 for (const auto sn : MAX_SIDES_PER_SEGMENT)
202 {
203 const auto sidebit = build_sidemask(sn);
204 auto &s{segnum.sides[sn]};
205
206 // Get number of faces on this side, and at vertex_list, store vertices.
207 // If one face, then vertex_list indicates a quadrilateral.
208 // If two faces, then 0,1,2 define one triangle, 3,4,5 define the second.
209 const auto &&[num_faces, vertex_list] = create_abs_vertex_lists(segnum, s, sn);
210
211 //ok...this is important. If a side has 2 faces, we need to know if
212 //those faces form a concave or convex side. If the side pokes out,
213 //then a point is on the back of the side if it is behind BOTH faces,
214 //but if the side pokes in, a point is on the back if behind EITHER face.
215
216 if (num_faces!=vertex_array_side_type::quad) {
217
218 const auto vertnum = min(vertex_list[0],vertex_list[2]);
219 auto &mvert = *vcvertptr(vertnum);
220
221 auto a = vertex_list[4] < vertex_list[1]
222 ? std::make_pair(vertex_list[4], &s.normals[0])
223 : std::make_pair(vertex_list[1], &s.normals[1]);
224 const auto mdist = vm_dist_to_plane(vcvertptr(a.first), *a.second, mvert);
225
226 unsigned center_count{0};
227 fix rdist{};
228 for (int fn=0;fn<2;fn++) {
229 const auto dist = vm_dist_to_plane(checkp, s.normals[fn], mvert);
230 if (dist < -PLANE_DIST_TOLERANCE) { //in front of face
231 center_count++;
232 rdist += dist;
233 }
234 }
235 if (!(mdist > PLANE_DIST_TOLERANCE)) { //must be behind both faces
236 if (center_count==2) {
237 result.centermask |= sidebit;
238 rdist /= 2; //get average
239 }
240 else
241 continue;
242 }
243 else { //must be behind at least one face
244 if (center_count) {
245 result.centermask |= sidebit;
246 if (center_count==2)
247 rdist /= 2; //get average
248 }
249 else
250 continue;
251 }
252 result.distances[sn] = rdist;
253 }
254 else { //only one face on this side
255 //use lowest point number
256
257 auto b = begin(vertex_list);
258 auto vertnum = *std::min_element(b, std::next(b, 4));
259
260 const auto dist = vm_dist_to_plane(checkp, s.normals[0], vcvertptr(vertnum));
261
262 if (dist < -PLANE_DIST_TOLERANCE) {
263 result.centermask |= sidebit;
264 result.distances[sn] = dist;
265 }
266 }
267 }
268 return result;
269 }
270
271 #ifndef NDEBUG
272 //returns true if errors detected
273 static int check_norms(const shared_segment &segp, const sidenum_t sidenum, const unsigned facenum, const shared_segment &csegp, const sidenum_t csidenum, const unsigned cfacenum)
274 {
275 const auto &n0 = segp.sides[sidenum].normals[facenum];
276 const auto &n1 = csegp.sides[csidenum].normals[cfacenum];
277 if (n0.x != -n1.x || n0.y != -n1.y || n0.z != -n1.z)
278 return 1;
279 else
280 return 0;
281 }
282
283 static void invert_shared_side_triangle_type(shared_side &s)
284 {
285 side_type nt;
286 switch (s.type)
287 {
288 case side_type::tri_02:
289 nt = side_type::tri_13;
290 break;
291 case side_type::tri_13:
292 nt = side_type::tri_02;
293 break;
294 default:
295 return;
296 }
297 s.type = nt;
298 }
299 #endif
300
301 // figure out what seg the given point is in, tracing through segments
302 // returns segment number, or -1 if can't find segment
303 static icsegptridx_t trace_segs(const d_level_shared_segment_state &LevelSharedSegmentState, const vms_vector &p0, const vcsegptridx_t oldsegnum, const unsigned recursion_count, visited_segment_bitarray_t &visited)
304 {
305 if (recursion_count >= LevelSharedSegmentState.Num_segments) {
306 con_puts(CON_DEBUG, "trace_segs: Segment not found");
307 return segment_none;
308 }
309 if (auto &&vs = visited[oldsegnum])
310 return segment_none;
311 else
312 vs = true;
313
314 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
315 auto &Vertices = LevelSharedVertexState.get_vertices();
316 auto &&side_dists{build_side_dists(Vertices.vcptr, p0, oldsegnum)}; //check old segment
317 if (side_dists.centermask == sidemask_t{}) // we are in the old segment
318 return oldsegnum; //..say so
319
320 auto &children = oldsegnum->shared_segment::children;
321 for (;;) {
322 std::optional<sidenum_t> biggest_side;
323 fix biggest_val{0};
324 for (const auto sidenum : MAX_SIDES_PER_SEGMENT)
325 {
326 /* Any side for which `centermask` is unset also has
327 * `.distances[sidenum]` still set to its value-initialized default
328 * of 0, which will cause it to be not less than `biggest_val`.
329 * Therefore, there is no need to check `centermask` for each side.
330 */
331 if (side_dists.distances[sidenum] < biggest_val && IS_CHILD(children[sidenum]))
332 {
333 biggest_val = side_dists.distances[sidenum];
334 biggest_side = sidenum;
335 }
336 }
337
338 if (!biggest_side)
339 break;
340
341 /* Clear the distance, so that this side cannot be considered again later. */
342 side_dists.distances[*biggest_side] = 0;
343 // trace into adjacent segment:
344 const auto &&check = trace_segs(LevelSharedSegmentState, p0, oldsegnum.absolute_sibling(children[*biggest_side]), recursion_count + 1, visited);
345 if (check != segment_none) //we've found a segment
346 return check;
347 }
348 return segment_none; //we haven't found a segment
349 }
350
351 static sbyte convert_to_byte(fix f)
352 {
353 const uint8_t MATRIX_MAX = 0x7f; // This is based on MATRIX_PRECISION, 9 => 0x7f
354 if (f >= 0x00010000)
355 return MATRIX_MAX;
356 else if (f <= -0x00010000)
357 return -MATRIX_MAX;
358 else
359 return f >> MATRIX_PRECISION;
360 }
361
362 // -------------------------------------------------------------------------------
363 // Return v0, v1, v2 = 3 vertices with smallest numbers. If *negate_flag set, then negate normal after computation.
364 // Note, you cannot just compute the normal by treating the points in the opposite direction as this introduces
365 // small differences between normals which should merely be opposites of each other.
366 static bool get_verts_for_normal(verts_for_normal &r)
367 {
368 auto &v = r.vsorted;
369 std::array<uint8_t, 4> w;
370 // w is a list that shows how things got scrambled so we know if our normal is pointing backwards
371 std::iota(w.begin(), w.end(), 0);
372
373 range_for (const unsigned i, xrange(1u, 4u))
374 range_for (const unsigned j, xrange(i))
375 if (v[j] > v[i]) {
376 using std::swap;
377 swap(v[j], v[i]);
378 swap(w[j], w[i]);
379 }
380
381 if (!((v[0] < v[1]) && (v[1] < v[2]) && (v[2] < v[3])))
382 LevelError("Level contains malformed geometry.");
383
384 // Now, if for any w[i] & w[i+1]: w[i+1] = (w[i]+3)%4, then must swap
385 return ((w[0] + 3) % 4) == w[1] || ((w[1] + 3) % 4) == w[2];
386 }
387
388 [[nodiscard]]
389 static auto build_side_normal(fvcvertptr &vcvertptr, const vertnum_t v0, const vertnum_t v1, const vertnum_t v2)
390 {
391 verts_for_normal vfn{v0, v1, v2, vertnum_t{UINT32_MAX}};
392 const auto negate_flag = get_verts_for_normal(vfn);
393 auto n{vm_vec_normal(vcvertptr(vfn.vsorted[0]), vcvertptr(vfn.vsorted[1]), vcvertptr(vfn.vsorted[2]))};
394 if (negate_flag)
395 vm_vec_negate(n);
396 return n;
397 }
398
399 // -------------------------------------------------------------------------------
400 static void add_side_as_2_triangles(fvcvertptr &vcvertptr, shared_segment &sp, const sidenum_t sidenum)
401 {
402 auto &vs = Side_to_verts[sidenum];
403
404 const auto sidep = &sp.sides[sidenum];
405
406 // Choose how to triangulate.
407 // If a wall, then
408 // Always triangulate so segment is convex.
409 // Use Matt's formula: Na . AD > 0, where ABCD are vertices on side, a is face formed by A,B,C, Na is normal from face a.
410 // If not a wall, then triangulate so whatever is on the other side is triangulated the same (ie, between the same absoluate vertices)
411 if (!IS_CHILD(sp.children[sidenum]))
412 {
413 auto &verts = sp.verts;
414 auto &vvs0 = *vcvertptr(verts[vs[side_relative_vertnum::_0]]);
415 auto &vvs1 = *vcvertptr(verts[vs[side_relative_vertnum::_1]]);
416 auto &vvs2 = *vcvertptr(verts[vs[side_relative_vertnum::_2]]);
417 auto &vvs3 = *vcvertptr(verts[vs[side_relative_vertnum::_3]]);
418 const auto norm{vm_vec_normal(vvs0, vvs1, vvs2)};
419 const fix dot{vm_vec_build_dot(norm, vm_vec_build_sub(vvs3, vvs1))};
420
421 const vertex *n0v3, *n1v1;
422 // Now, signify whether to triangulate from 0:2 or 1:3
423 sidep->type = (dot >= 0 ? (n0v3 = &vvs2, n1v1 = &vvs0, side_type::tri_02) : (n0v3 = &vvs3, n1v1 = &vvs1, side_type::tri_13));
424
425 // Now, based on triangulation type, set the normals.
426 reconstruct_at(sidep->normals[0], vm_vec_normal, vvs0, vvs1, *n0v3);
427 reconstruct_at(sidep->normals[1], vm_vec_normal, *n1v1, vvs2, vvs3);
428 } else {
429 enumerated_array<vertnum_t, 4, side_relative_vertnum> v;
430
431 for (const auto i : MAX_VERTICES_PER_SIDE)
432 v[i] = sp.verts[vs[i]];
433
434 verts_for_normal vfn{v[side_relative_vertnum::_0], v[side_relative_vertnum::_1], v[side_relative_vertnum::_2], v[side_relative_vertnum::_3]};
435 get_verts_for_normal(vfn);
436
437 vertnum_t s0v2, s1v0;
438 if ((vfn.vsorted[0] == v[side_relative_vertnum::_0]) || (vfn.vsorted[0] == v[side_relative_vertnum::_2])) {
439 sidep->type = side_type::tri_02;
440 // Now, get vertices for normal for each triangle based on triangulation type.
441 s0v2 = v[side_relative_vertnum::_2];
442 s1v0 = v[side_relative_vertnum::_0];
443 } else {
444 sidep->type = side_type::tri_13;
445 // Now, get vertices for normal for each triangle based on triangulation type.
446 s0v2 = v[side_relative_vertnum::_3];
447 s1v0 = v[side_relative_vertnum::_1];
448 }
449 reconstruct_at(sidep->normals[0], build_side_normal, vcvertptr, v[side_relative_vertnum::_0], v[side_relative_vertnum::_1], s0v2);
450 reconstruct_at(sidep->normals[1], build_side_normal, vcvertptr, s1v0, v[side_relative_vertnum::_2], v[side_relative_vertnum::_3]);
451 }
452 }
453
454 static int sign(fix v)
455 {
456
457 if (v > PLANE_DIST_TOLERANCE)
458 return 1;
459 else if (v < -(PLANE_DIST_TOLERANCE+1)) //neg & pos round differently
460 return -1;
461 else
462 return 0;
463 }
464
465 #if DXX_USE_EDITOR
466 // ----
467 // A side is determined to be degenerate if the cross products of 3 consecutive points does not point outward.
468 [[nodiscard]]
469 static unsigned check_for_degenerate_side(fvcvertptr &vcvertptr, const shared_segment &sp, const sidenum_t sidenum)
470 {
471 auto &vp = Side_to_verts[sidenum];
472 vms_vector vec1, vec2;
473
474 const auto segc{compute_segment_center(vcvertptr, sp)};
475 const auto sidec{compute_center_point_on_side(vcvertptr, sp, sidenum)};
476 const auto vec_to_center{vm_vec_build_sub(segc, sidec)};
477
478 //vm_vec_sub(&vec1, &Vertices[sp->verts[vp[1]]], &Vertices[sp->verts[vp[0]]]);
479 //vm_vec_sub(&vec2, &Vertices[sp->verts[vp[2]]], &Vertices[sp->verts[vp[1]]]);
480 //vm_vec_normalize(&vec1);
481 //vm_vec_normalize(&vec2);
482 const auto vp1{vp[side_relative_vertnum::_1]};
483 const auto vp2{vp[side_relative_vertnum::_2]};
484 auto &vert1{*vcvertptr(sp.verts[vp1])};
485 auto &vert2{*vcvertptr(sp.verts[vp2])};
486 vm_vec_normalized_dir(vec1, vert1, vcvertptr(sp.verts[vp[side_relative_vertnum::_0]]));
487 vm_vec_normalized_dir(vec2, vert2, vert1);
488
489 if (vm_vec_build_dot(vec_to_center, vm_vec_cross(vec1, vec2)) <= 0)
490 return 1;
491
492 //vm_vec_sub(&vec1, &Vertices[sp->verts[vp[2]]], &Vertices[sp->verts[vp[1]]]);
493 //vm_vec_sub(&vec2, &Vertices[sp->verts[vp[3]]], &Vertices[sp->verts[vp[2]]]);
494 //vm_vec_normalize(&vec1);
495 //vm_vec_normalize(&vec2);
496 vm_vec_normalized_dir(vec1, vert2, vert1);
497 vm_vec_normalized_dir(vec2, vcvertptr(sp.verts[vp[side_relative_vertnum::_3]]), vert2);
498
499 if (vm_vec_build_dot(vec_to_center, vm_vec_cross(vec1, vec2)) <= 0)
500 return 1;
501 return 0;
502 }
503
504 // ----
505 // See if a segment has gotten turned inside out, or something.
506 // If so, set global Degenerate_segment_found and return 1, else return 0.
507 [[nodiscard]]
508 static unsigned check_for_degenerate_segment(fvcvertptr &vcvertptr, const shared_segment &sp)
509 {
510 if (vm_vec_build_dot(
511 vm_vec_cross(
512 vm_vec_normalized(extract_forward_vector_from_segment(vcvertptr, sp)),
513 vm_vec_normalized(extract_right_vector_from_segment(vcvertptr, sp))),
514 vm_vec_normalized(extract_up_vector_from_segment(vcvertptr, sp))
515 ) <= 0)
516 return 1;
517
518 // Now, see if degenerate because of any side.
519 for (const auto i : MAX_SIDES_PER_SEGMENT)
520 if (const auto r{check_for_degenerate_side(vcvertptr, sp, i)})
521 return r;
522 return 0;
523
524 }
525 #endif
526
527 }
528
529 // ------------------------------------------------------------------------------------------
530 // Compute the center point of a side of a segment.
531 // The center point is defined to be the average of the 4 points defining the side.
532 vms_vector compute_center_point_on_side(fvcvertptr &vcvertptr, const shared_segment &sp, const sidenum_t side)
533 {
534 return compute_center_point_on_side(vcvertptr, sp.verts, side);
535 }
536
537 // ------------------------------------------------------------------------------------------
538 // Compute segment center.
539 // The center point is defined to be the average of the 8 points defining the segment.
540 vms_vector compute_segment_center(fvcvertptr &vcvertptr, const shared_segment &sp)
541 {
542 return compute_segment_center(vcvertptr, sp.verts);
543 }
544
545 // -----------------------------------------------------------------------------
546 // Given two segments, return the side index in the connecting segment which connects to the base segment
547 // Optimized by MK on 4/21/94 because it is a 2% load.
548 sidenum_t find_connect_side(const vcsegidx_t base_seg, const shared_segment &con_seg)
549 {
550 auto &children = con_seg.children;
551 const auto &&b = begin(children);
552 return static_cast<sidenum_t>(std::distance(b, std::find(b, end(children), base_seg)));
553 }
554
555 // -----------------------------------------------------------------------------------
556 // Given a side, return the number of faces
557 bool get_side_is_quad(const shared_side &sidep)
558 {
559 switch (sidep.type)
560 {
561 case side_type::quad:
562 return true;
563 case side_type::tri_02:
564 case side_type::tri_13:
565 return false;
566 default:
567 throw shared_side::illegal_type(sidep);
568 }
569 }
570
571 side_vertnum_list_t get_side_verts(const shared_segment &segp, const sidenum_t sidenum)
572 {
573 return get_side_verts(segp.verts, sidenum);
574 }
575
576 #if DXX_USE_EDITOR
577 // -----------------------------------------------------------------------------------
578 // Create all vertex lists (1 or 2) for faces on a side.
579 // Sets:
580 // num_faces number of lists
581 // vertices vertices in all (1 or 2) faces
582 // If there is one face, it has 4 vertices.
583 // If there are two faces, they both have three vertices, so face #0 is stored in vertices 0,1,2,
584 // face #1 is stored in vertices 3,4,5.
585 // Note: these are not absolute vertex numbers, but are relative to the segment
586 // Note: for triagulated sides, the middle vertex of each trianle is the one NOT
587 // adjacent on the diagonal edge
588 vertex_array_list_t create_all_vertex_lists(const shared_segment &segp, const shared_side &sidep, const sidenum_t sidenum)
589 {
590 vertex_array_list_t vertices;
591 const auto valid_side{Side_to_verts.valid_index(sidenum)};
592 assert(valid_side);
593 auto &sv = Side_to_verts[*valid_side];
594 vertices.side_type = create_vertex_lists_by_predicate(vertices, segp, sidep, [&sv](const side_relative_vertnum vv) {
595 return sv[vv];
596 });
597 return vertices;
598 }
599 #endif
600
601 // -----------------------------------------------------------------------------------
602 // Like create all vertex lists, but returns the vertnums (relative to
603 // the side) for each of the faces that make up the side.
604 // If there is one face, it has 4 vertices.
605 // If there are two faces, they both have three vertices, so face #0 is stored in vertices 0,1,2,
606 // face #1 is stored in vertices 3,4,5.
607 vertex_vertnum_array_list create_all_vertnum_lists(const shared_segment &segp, const shared_side &sidep, const sidenum_t sidenum)
608 {
609 vertex_vertnum_array_list vertnums;
610 class predicate : abs_vertex_lists_predicate
611 {
612 public:
613 using abs_vertex_lists_predicate::abs_vertex_lists_predicate;
614 vertex_vertnum_pair operator()(const side_relative_vertnum vv) const
615 {
616 return {this->abs_vertex_lists_predicate::operator()(vv), vv};
617 }
618 };
619 create_vertex_lists_by_predicate(vertnums, segp, sidep, predicate{segp, sidenum});
620 return vertnums;
621 }
622
623 // -----
624 // like create_all_vertex_lists(), but generate absolute point numbers
625 abs_vertex_list_result create_abs_vertex_lists(const shared_segment &segp, const shared_side &sidep, const sidenum_t sidenum)
626 {
627 abs_vertex_list_result r;
628 r.num_faces = create_vertex_lists_by_predicate(r.vertex_list, segp, sidep, abs_vertex_lists_predicate{segp, sidenum});
629 return r;
630 }
631
632 //returns 3 different bitmasks with info telling if this sphere is in
633 //this segment. See segmasks structure for info on fields
634 segmasks get_seg_masks(fvcvertptr &vcvertptr, const vms_vector &checkp, const shared_segment &seg, const fix rad)
635 {
636 segmasks masks{};
637
638 //check point against each side of segment. return bitmask
639
640 int facebit{1};
641 for (const auto sn : MAX_SIDES_PER_SEGMENT)
642 {
643 const auto sidebit = build_sidemask(sn);
644 auto &s = seg.sides[sn];
645
646 // Get number of faces on this side, and at vertex_list, store vertices.
647 // If one face, then vertex_list indicates a quadrilateral.
648 // If two faces, then 0,1,2 define one triangle, 3,4,5 define the second.
649 const auto &&[num_faces, vertex_list] = create_abs_vertex_lists(seg, s, sn);
650
651 //ok...this is important. If a side has 2 faces, we need to know if
652 //those faces form a concave or convex side. If the side pokes out,
653 //then a point is on the back of the side if it is behind BOTH faces,
654 //but if the side pokes in, a point is on the back if behind EITHER face.
655
656 if (num_faces!=vertex_array_side_type::quad) {
657 int side_count,center_count;
658
659 const auto vertnum = min(vertex_list[0],vertex_list[2]);
660 const auto &&mvert = vcvertptr(vertnum);
661
662 auto a = vertex_list[4] < vertex_list[1]
663 ? std::make_pair(vertex_list[4], &s.normals[0])
664 : std::make_pair(vertex_list[1], &s.normals[1]);
665 const auto mdist = vm_dist_to_plane(vcvertptr(a.first), *a.second, mvert);
666
667 side_count = center_count = 0;
668
669 for (int fn=0;fn<2;fn++,facebit<<=1) {
670
671 const auto dist = vm_dist_to_plane(checkp, s.normals[fn], mvert);
672
673 if (dist-rad < -PLANE_DIST_TOLERANCE) {
674 if (dist < -PLANE_DIST_TOLERANCE) //in front of face
675 center_count++;
676
677 masks.facemask |= facebit;
678 side_count++;
679 }
680 }
681
682 if (!(mdist > PLANE_DIST_TOLERANCE)) { //must be behind both faces
683
684 if (side_count==2)
685 masks.sidemask |= sidebit;
686
687 if (center_count==2)
688 masks.centermask |= sidebit;
689
690 }
691 else { //must be behind at least one face
692
693 if (side_count)
694 masks.sidemask |= sidebit;
695
696 if (center_count)
697 masks.centermask |= sidebit;
698
699 }
700
701
702 }
703 else { //only one face on this side
704 //use lowest point number
705 auto b = begin(vertex_list);
706 const auto vertnum = *std::min_element(b, std::next(b, 4));
707 const auto &&mvert = vcvertptr(vertnum);
708
709 const auto dist = vm_dist_to_plane(checkp, s.normals[0], mvert);
710 if (dist-rad < -PLANE_DIST_TOLERANCE) {
711 if (dist < -PLANE_DIST_TOLERANCE)
712 masks.centermask |= sidebit;
713
714 masks.facemask |= facebit;
715 masks.sidemask |= sidebit;
716 }
717
718 facebit <<= 2;
719 }
720
721 }
722 return masks;
723 }
724
725 //heavy-duty error checking
726 int check_segment_connections()
727 {
728 int errors{0};
729
730 range_for (const auto &&seg, vmsegptridx)
731 {
732 for (const auto sidenum : MAX_SIDES_PER_SEGMENT)
733 {
734 #ifndef NDEBUG
735 const auto &&[num_faces, vertex_list]{create_abs_vertex_lists(seg, seg->shared_segment::sides[sidenum], sidenum)};
736 #endif
737 const auto csegnum = seg->shared_segment::children[sidenum];
738 if (!IS_CHILD(csegnum))
739 continue;
740 {
741 auto cseg = vcsegptr(csegnum);
742 auto csidenum = find_connect_side(seg,cseg);
743
744 if (csidenum == side_none)
745 {
746 shared_segment &rseg = *seg;
747 const shared_segment &rcseg = *cseg;
748 const auto segi = underlying_value(seg.get_unchecked_index());
749 const auto csegi = underlying_value(csegnum);
750 LevelError("Segment #%hu side %u has asymmetric link to segment %hu. Coercing to segment_none; Segments[%hu].children={%hu, %hu, %hu, %hu, %hu, %hu}, Segments[%u].children={%hu, %hu, %hu, %hu, %hu, %hu}.", segi, underlying_value(sidenum), csegi, segi, rseg.children[sidenum_t::WLEFT], rseg.children[sidenum_t::WTOP], rseg.children[sidenum_t::WRIGHT], rseg.children[sidenum_t::WBOTTOM], rseg.children[sidenum_t::WBACK], rseg.children[sidenum_t::WFRONT], csegi, rcseg.children[sidenum_t::WLEFT], rcseg.children[sidenum_t::WTOP], rcseg.children[sidenum_t::WRIGHT], rcseg.children[sidenum_t::WBOTTOM], rcseg.children[sidenum_t::WBACK], rcseg.children[sidenum_t::WFRONT]);
751 rseg.children[sidenum] = segment_none;
752 errors = 1;
753 continue;
754 }
755
756 #ifndef NDEBUG
757 const auto &&[con_num_faces, con_vertex_list]{create_abs_vertex_lists(cseg, cseg->shared_segment::sides[csidenum], csidenum)};
758
759 if (con_num_faces != num_faces) {
760 LevelError("Segment #%u side %u: wrong faces: con_num_faces=%" PRIuFAST32 " num_faces=%" PRIuFAST32 ".", seg.get_unchecked_index(), underlying_value(sidenum), static_cast<uint_fast32_t>(con_num_faces), static_cast<uint_fast32_t>(num_faces));
761 errors = 1;
762 }
763 else
764 if (num_faces == vertex_array_side_type::quad) {
765 int t;
766
767 for (t=0;t<4 && con_vertex_list[t]!=vertex_list[0];t++);
768
769 if (t==4 ||
770 vertex_list[0] != con_vertex_list[t] ||
771 vertex_list[1] != con_vertex_list[(t+3)%4] ||
772 vertex_list[2] != con_vertex_list[(t+2)%4] ||
773 vertex_list[3] != con_vertex_list[(t+1)%4]) {
774 LevelError("Segment #%u side %u: bad vertices.", seg.get_unchecked_index(), underlying_value(sidenum));
775 errors = 1;
776 }
777 else
778 errors |= check_norms(seg,sidenum,0,cseg,csidenum,0);
779
780 }
781 else {
782
783 if (vertex_list[1] == con_vertex_list[1]) {
784
785 if (vertex_list[4] != con_vertex_list[4] ||
786 vertex_list[0] != con_vertex_list[2] ||
787 vertex_list[2] != con_vertex_list[0] ||
788 vertex_list[3] != con_vertex_list[5] ||
789 vertex_list[5] != con_vertex_list[3]) {
790 auto &cside = vmsegptr(csegnum)->shared_segment::sides[csidenum];
791 invert_shared_side_triangle_type(cside);
792 } else {
793 errors |= check_norms(seg,sidenum,0,cseg,csidenum,0);
794 errors |= check_norms(seg,sidenum,1,cseg,csidenum,1);
795 }
796
797 } else {
798
799 if (vertex_list[1] != con_vertex_list[4] ||
800 vertex_list[4] != con_vertex_list[1] ||
801 vertex_list[0] != con_vertex_list[5] ||
802 vertex_list[5] != con_vertex_list[0] ||
803 vertex_list[2] != con_vertex_list[3] ||
804 vertex_list[3] != con_vertex_list[2]) {
805 auto &cside = vmsegptr(csegnum)->shared_segment::sides[csidenum];
806 invert_shared_side_triangle_type(cside);
807 } else {
808 errors |= check_norms(seg,sidenum,0,cseg,csidenum,1);
809 errors |= check_norms(seg,sidenum,1,cseg,csidenum,0);
810 }
811 }
812 }
813 #endif
814 }
815 }
816 }
817 return errors;
818 }
819
820 }
821
822 namespace dsx {
823 namespace {
824
825 constexpr vm_distance fcd_abort_cache_value{F1_0 * 1000};
826 constexpr vm_distance fcd_abort_return_value{-1};
827
828 }
829
830 // Used to become a constant based on editor, but I wanted to be able to set
831 // this for omega blob find_point_seg calls.
832 // Would be better to pass a paremeter to the routine...--MK, 01/17/96
833 #if DXX_internal_feature_lighting_hack
834 lighting_hack Doing_lighting_hack_flag{lighting_hack::normal};
835 #endif
836
837 imsegptridx_t find_point_seg(const d_level_shared_segment_state &LevelSharedSegmentState, d_level_unique_segment_state &, const vms_vector &p, const imsegptridx_t segnum)
838 {
839 return segnum.rebind_policy(find_point_seg(LevelSharedSegmentState, p, segnum));
840 }
841
842 //Tries to find a segment for a point, in the following way:
843 // 1. Check the given segment
844 // 2. Recursively trace through attached segments
845 // 3. Check all the segments
846 //Returns segnum if found, or -1
847 icsegptridx_t find_point_seg(const d_level_shared_segment_state &LevelSharedSegmentState, const vms_vector &p, const icsegptridx_t segnum)
848 {
849 //allow segnum==-1, meaning we have no idea what segment point is in
850 if (segnum != segment_none) {
851 visited_segment_bitarray_t visited;
852 const auto &&newseg = trace_segs(LevelSharedSegmentState, p, segnum, 0, visited);
853 if (newseg != segment_none) //we found a segment!
854 return newseg;
855 }
856
857 //couldn't find via attached segs, so search all segs
858
859 #if DXX_internal_feature_lighting_hack
860 // MK: 10/15/94
861 // This Doing_lighting_hack_flag thing added by mk because the hundreds of scrolling messages were
862 // slowing down lighting, and in about 98% of cases, it would just return -1 anyway.
863 // Matt: This really should be fixed, though. We're probably screwing up our lighting in a few places.
864 if (Doing_lighting_hack_flag == lighting_hack::normal)
865 #endif
866 {
867 auto &Segments = LevelSharedSegmentState.get_segments();
868 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
869 auto &Vertices = LevelSharedVertexState.get_vertices();
870 for (const auto &&segp : Segments.vmptridx)
871 {
872 if (get_seg_masks(Vertices.vcptr, p, segp, 0).centermask == sidemask_t{})
873 return segp;
874 }
875 }
876 return segment_none;
877 }
878
879
880 //--repair-- // ------------------------------------------------------------------------------
881 //--repair-- void clsd_repair_center(int segnum)
882 //--repair-- {
883 //--repair-- int sidenum;
884 //--repair--
885 //--repair-- // --- Set repair center bit for all repair center segments.
886 //--repair-- if (Segments[segnum].special == SEGMENT_IS_REPAIRCEN) {
887 //--repair-- Lsegments[segnum].special_type |= SS_REPAIR_CENTER;
888 //--repair-- Lsegments[segnum].special_segment = segnum;
889 //--repair-- }
890 //--repair--
891 //--repair-- // --- Set repair center bit for all segments adjacent to a repair center.
892 //--repair-- for (sidenum=0; sidenum < MAX_SIDES_PER_SEGMENT; sidenum++) {
893 //--repair-- int s = Segments[segnum].children[sidenum];
894 //--repair--
895 //--repair-- if ( (s != -1) && (Segments[s].special==SEGMENT_IS_REPAIRCEN) ) {
896 //--repair-- Lsegments[segnum].special_type |= SS_REPAIR_CENTER;
897 //--repair-- Lsegments[segnum].special_segment = s;
898 //--repair-- }
899 //--repair-- }
900 //--repair-- }
901
902 //--repair-- // ------------------------------------------------------------------------------
903 //--repair-- // --- Set destination points for all Materialization centers.
904 //--repair-- void clsd_materialization_center(int segnum)
905 //--repair-- {
906 //--repair-- if (Segments[segnum].special == SEGMENT_IS_ROBOTMAKER) {
907 //--repair--
908 //--repair-- }
909 //--repair-- }
910 //--repair--
911 //--repair-- int Lsegment_highest_segment_index, Lsegment_highest_vertex_index;
912 //--repair--
913 //--repair-- // ------------------------------------------------------------------------------
914 //--repair-- // Create data specific to mine which doesn't get written to disk.
915 //--repair-- // Highest_segment_index and Highest_object_index must be valid.
916 //--repair-- // 07/21: set repair center bit
917 //--repair-- void create_local_segment_data(void)
918 //--repair-- {
919 //--repair-- int segnum;
920 //--repair--
921 //--repair-- // --- Initialize all Lsegments.
922 //--repair-- for (segnum=0; segnum <= Highest_segment_index; segnum++) {
923 //--repair-- Lsegments[segnum].special_type = 0;
924 //--repair-- Lsegments[segnum].special_segment = -1;
925 //--repair-- }
926 //--repair--
927 //--repair-- for (segnum=0; segnum <= Highest_segment_index; segnum++) {
928 //--repair--
929 //--repair-- clsd_repair_center(segnum);
930 //--repair-- clsd_materialization_center(segnum);
931 //--repair--
932 //--repair-- }
933 //--repair--
934 //--repair-- // Set check variables.
935 //--repair-- // In main game loop, make sure these are valid, else Lsegments is not valid.
936 //--repair-- Lsegment_highest_segment_index = Highest_segment_index;
937 //--repair-- Lsegment_highest_vertex_index = Highest_vertex_index;
938 //--repair-- }
939 //--repair--
940 //--repair-- // ------------------------------------------------------------------------------------------
941 //--repair-- // Sort of makes sure create_local_segment_data has been called for the currently executing mine.
942 //--repair-- // It is not failsafe, as you will see if you look at the code.
943 //--repair-- // Returns 1 if Lsegments appears valid, 0 if not.
944 //--repair-- int check_lsegments_validity(void)
945 //--repair-- {
946 //--repair-- return ((Lsegment_highest_segment_index == Highest_segment_index) && (Lsegment_highest_vertex_index == Highest_vertex_index));
947 //--repair-- }
948
949 #if DXX_BUILD_DESCENT == 1
950 namespace {
951 static inline void add_to_fcd_cache(segnum_t seg0, segnum_t seg1, vm_distance dist)
952 {
953 (void)seg0;
954 (void)seg1;
955 (void)dist;
956 }
957 }
958 #elif DXX_BUILD_DESCENT == 2
959 #define MIN_CACHE_FCD_DIST (F1_0*80) // Must be this far apart for cache lookup to succeed. Recognizes small changes in distance matter at small distances.
960 namespace {
961
962 struct fcd_data
963 {
964 segnum_t seg0, seg1;
965 vm_distance dist;
966 };
967
968 #if DXX_BUILD_DESCENT == 2
969 static constexpr sidemask_t &operator&=(sidemask_t &a, const sidemask_t b)
970 {
971 return a = static_cast<sidemask_t>(static_cast<uint8_t>(a) & static_cast<uint8_t>(b));
972 }
973 #endif
974
975 fix64 Last_fcd_flush_time;
976 unsigned Fcd_index;
977 std::array<fcd_data, 8> Fcd_cache;
978
979 static void add_to_fcd_cache(const segnum_t seg0, const segnum_t seg1, const vm_distance dist)
980 {
981 if (dist > MIN_CACHE_FCD_DIST) {
982 if (Fcd_index >= Fcd_cache.size())
983 Fcd_index = 0;
984 auto &f = Fcd_cache[Fcd_index++];
985 f.seg0 = seg0;
986 f.seg1 = seg1;
987 f.dist = dist;
988 } else {
989 // If it's in the cache, remove it.
990 for (auto &f : Fcd_cache)
991 if (f.seg0 == seg0 && f.seg1 == seg1)
992 {
993 f.seg0 = segment_none;
994 break;
995 }
996 }
997 }
998
999 }
1000
1001 // ----------------------------------------------------------------------------------------------------------
1002 void flush_fcd_cache()
1003 {
1004 Fcd_index = 0;
1005 Last_fcd_flush_time = {GameTime64};
1006
1007 for (auto &f : Fcd_cache)
1008 f.seg0 = segment_none;
1009 }
1010 #endif
1011
1012 // ----------------------------------------------------------------------------------------------------------
1013 // Determine whether seg0 and seg1 are reachable in a way that allows sound to pass.
1014 // Search up to a maximum depth of max_depth.
1015 // Return the distance.
1016 vm_distance find_connected_distance(const vms_vector &p0, const vcsegptridx_t seg0, const vms_vector &p1, const vcsegptridx_t seg1, int max_depth, const wall_is_doorway_mask wid_flag)
1017 {
1018 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
1019 auto &Vertices = LevelSharedVertexState.get_vertices();
1020 segnum_t cur_seg;
1021 int qtail{0}, qhead = 0;
1022 std::array<seg_seg, MAX_SEGMENTS> seg_queue;
1023 int cur_depth;
1024 int num_points;
1025 struct point_seg
1026 {
1027 vms_vector point;
1028 };
1029 std::array<point_seg, 64> point_segs;
1030
1031 // If > this, will overrun point_segs buffer
1032 #ifdef WINDOWS
1033 if (max_depth == -1) max_depth = 200;
1034 #endif
1035
1036 if (const auto s = std::size(point_segs) - 2u; max_depth > s)
1037 max_depth = s;
1038
1039 auto &Walls = LevelUniqueWallSubsystemState.Walls;
1040 auto &vcwallptr = Walls.vcptr;
1041 if (seg0 == seg1) {
1042 return vm_vec_dist_quick(p0, p1);
1043 } else {
1044 auto conn_side = find_connect_side(seg0, seg1);
1045 if (conn_side != side_none)
1046 {
1047 #if DXX_BUILD_DESCENT == 2
1048 if (WALL_IS_DOORWAY(GameBitmaps, Textures, vcwallptr, seg1, conn_side) & wid_flag)
1049 #endif
1050 {
1051 return vm_vec_dist_quick(p0, p1);
1052 }
1053 }
1054 }
1055
1056 #if DXX_BUILD_DESCENT == 2
1057 // Periodically flush cache.
1058 if ((GameTime64 - Last_fcd_flush_time > F1_0*2) || (GameTime64 < Last_fcd_flush_time)) {
1059 flush_fcd_cache();
1060 }
1061
1062 else
1063 // Can't quickly get distance, so see if in Fcd_cache.
1064 range_for (auto &i, Fcd_cache)
1065 if (i.seg0 == seg0 && i.seg1 == seg1)
1066 {
1067 return i.dist;
1068 }
1069 #endif
1070
1071 num_points = 0;
1072
1073 std::array<uint16_t, MAX_SEGMENTS> depth{};
1074 visited_segment_bitarray_t visited;
1075
1076 cur_seg = seg0;
1077 visited[cur_seg] = true;
1078 cur_depth = 0;
1079
1080 while (cur_seg != seg1) {
1081 const cscusegment segp = *vmsegptr(cur_seg);
1082 for (const auto snum : MAX_SIDES_PER_SEGMENT)
1083 {
1084 const auto this_seg = segp.s.children[snum];
1085 if (!IS_CHILD(this_seg))
1086 continue;
1087 auto &&v = visited[this_seg];
1088 if (v)
1089 continue;
1090 if (wid_flag == wall_is_doorway_mask::None || (WALL_IS_DOORWAY(GameBitmaps, Textures, vcwallptr, segp, snum) & wid_flag))
1091 {
1092 v = true;
1093 seg_queue[qtail].start = cur_seg;
1094 seg_queue[qtail].end = this_seg;
1095 depth[qtail++] = cur_depth+1;
1096 if (max_depth != -1) {
1097 if (depth[qtail-1] == max_depth) {
1098 add_to_fcd_cache(seg0, seg1, fcd_abort_cache_value);
1099 return fcd_abort_return_value;
1100 }
1101 } else if (this_seg == seg1) {
1102 goto fcd_done1;
1103 }
1104 }
1105 } // for (sidenum...
1106
1107 if (qhead >= qtail) {
1108 add_to_fcd_cache(seg0, seg1, fcd_abort_cache_value);
1109 return fcd_abort_return_value;
1110 }
1111
1112 cur_seg = seg_queue[qhead].end;
1113 cur_depth = depth[qhead];
1114 qhead++;
1115
1116 fcd_done1: ;
1117 } // while (cur_seg ...
1118
1119 // Set qtail to the segment which ends at the goal.
1120 while (seg_queue[--qtail].end != seg1)
1121 if (qtail < 0) {
1122 add_to_fcd_cache(seg0, seg1, fcd_abort_cache_value);
1123 return fcd_abort_return_value;
1124 }
1125
1126 auto &vcvertptr = Vertices.vcptr;
1127 while (qtail >= 0) {
1128 segnum_t parent_seg, this_seg;
1129
1130 this_seg = seg_queue[qtail].end;
1131 parent_seg = seg_queue[qtail].start;
1132 point_segs[num_points].point = compute_segment_center(vcvertptr, vcsegptr(this_seg));
1133 num_points++;
1134
1135 if (parent_seg == seg0)
1136 break;
1137
1138 while (seg_queue[--qtail].end != parent_seg)
1139 Assert(qtail >= 0);
1140 }
1141
1142 point_segs[num_points].point = compute_segment_center(vcvertptr, seg0);
1143 num_points++;
1144
1145 if (num_points == 1) {
1146 return vm_vec_dist_quick(p0, p1);
1147 }
1148 auto dist = vm_vec_dist_quick(p1, point_segs[1].point);
1149 dist += vm_vec_dist_quick(p0, point_segs[num_points-2].point);
1150
1151 for (int i=1; i<num_points-2; i++) {
1152 dist += vm_vec_dist_quick(point_segs[i].point, point_segs[i+1].point);
1153 }
1154
1155 add_to_fcd_cache(seg0, seg1, dist);
1156
1157 return dist;
1158
1159 }
1160
1161 }
1162
1163 namespace dcx {
1164
1165 // create and extract quaternion structure from object data which greatly saves bytes by using quaternion instead of orientation matrix
1166 quaternionpos build_quaternionpos(const object_base &objp)
1167 {
1168 return quaternionpos{
1169 .orient = vms_quaternion_from_matrix(objp.orient),
1170 .pos = objp.pos,
1171 .segment = objp.segnum,
1172 .vel = objp.mtype.phys_info.velocity,
1173 .rotvel = objp.mtype.phys_info.rotvel
1174 };
1175 }
1176
1177 // Create a shortpos struct from an object.
1178 // Extract the matrix into byte values.
1179 // Create a position relative to vertex 0 with 1/256 normal "fix" precision.
1180 // Stuff segment in a short.
1181 shortpos create_shortpos_native(const d_level_shared_segment_state &LevelSharedSegmentState, const object_base &objp)
1182 {
1183 shortpos spp;
1184 auto &vcsegptr = LevelSharedSegmentState.get_segments().vcptr;
1185 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
1186 auto &Vertices = LevelSharedVertexState.get_vertices();
1187 auto &vcvertptr = Vertices.vcptr;
1188 spp.bytemat[0] = convert_to_byte(objp.orient.rvec.x);
1189 spp.bytemat[1] = convert_to_byte(objp.orient.uvec.x);
1190 spp.bytemat[2] = convert_to_byte(objp.orient.fvec.x);
1191 spp.bytemat[3] = convert_to_byte(objp.orient.rvec.y);
1192 spp.bytemat[4] = convert_to_byte(objp.orient.uvec.y);
1193 spp.bytemat[5] = convert_to_byte(objp.orient.fvec.y);
1194 spp.bytemat[6] = convert_to_byte(objp.orient.rvec.z);
1195 spp.bytemat[7] = convert_to_byte(objp.orient.uvec.z);
1196 spp.bytemat[8] = convert_to_byte(objp.orient.fvec.z);
1197
1198 spp.segment = objp.segnum;
1199 const shared_segment &segp = *vcsegptr(objp.segnum);
1200 auto &vert = *vcvertptr(segp.verts[segment_relative_vertnum::_0]);
1201 spp.xo = (objp.pos.x - vert.x) >> RELPOS_PRECISION;
1202 spp.yo = (objp.pos.y - vert.y) >> RELPOS_PRECISION;
1203 spp.zo = (objp.pos.z - vert.z) >> RELPOS_PRECISION;
1204
1205 spp.velx = (objp.mtype.phys_info.velocity.x) >> spp.velocity_precision_shift;
1206 spp.vely = (objp.mtype.phys_info.velocity.y) >> spp.velocity_precision_shift;
1207 spp.velz = (objp.mtype.phys_info.velocity.z) >> spp.velocity_precision_shift;
1208 return spp;
1209 }
1210
1211 // -----------------------------------------------------------------------------
1212 // Segment validation functions.
1213 // Moved from editor to game so we can compute surface normals at load time.
1214 // -------------------------------------------------------------------------------
1215
1216 //create a matrix that describes the orientation of the given segment
1217 vms_matrix extract_orient_from_segment(fvcvertptr &vcvertptr, const shared_segment &seg)
1218 {
1219 const auto fvec{extract_vector_from_segment(vcvertptr, seg, sidenum_t::WFRONT, sidenum_t::WBACK)};
1220 const auto uvec{extract_vector_from_segment(vcvertptr, seg, sidenum_t::WBOTTOM, sidenum_t::WTOP)};
1221 //vector to matrix does normalizations and orthogonalizations
1222 return vm_vector_to_matrix_u(fvec, uvec);
1223 }
1224
1225 #if DXX_USE_EDITOR
1226
1227 // ------------------------------------------------------------------------------------------
1228 // Extract the forward vector from segment *sp, return in *vp.
1229 // The forward vector is defined to be the vector from the the center of the front face of the segment
1230 // to the center of the back face of the segment.
1231 vms_vector extract_forward_vector_from_segment(fvcvertptr &vcvertptr, const shared_segment &sp)
1232 {
1233 return extract_vector_from_segment(vcvertptr, sp, sidenum_t::WFRONT, sidenum_t::WBACK);
1234 }
1235
1236 // ------------------------------------------------------------------------------------------
1237 // Extract the right vector from segment *sp, return in *vp.
1238 // The forward vector is defined to be the vector from the the center of the left face of the segment
1239 // to the center of the right face of the segment.
1240 vms_vector extract_right_vector_from_segment(fvcvertptr &vcvertptr, const shared_segment &sp)
1241 {
1242 return extract_vector_from_segment(vcvertptr, sp, sidenum_t::WLEFT, sidenum_t::WRIGHT);
1243 }
1244
1245 // ------------------------------------------------------------------------------------------
1246 // Extract the up vector from segment *sp, return in *vp.
1247 // The forward vector is defined to be the vector from the the center of the bottom face of the segment
1248 // to the center of the top face of the segment.
1249 vms_vector extract_up_vector_from_segment(fvcvertptr &vcvertptr, const shared_segment &sp)
1250 {
1251 return extract_vector_from_segment(vcvertptr, sp, sidenum_t::WBOTTOM, sidenum_t::WTOP);
1252 }
1253
1254 #endif
1255
1256 }
1257
1258 namespace dsx {
1259
1260 #if DXX_USE_MULTIPLAYER
1261 #if DXX_BUILD_DESCENT == 2
1262 void multi_object_warp_to_shortpos(const vmobjptridx_t objp, const shortpos &spp)
1263 {
1264 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
1265 auto &Objects = LevelUniqueObjectState.Objects;
1266 auto &Vertices = LevelSharedVertexState.get_vertices();
1267 auto &vmobjptr = Objects.vmptr;
1268 auto sp{spp.bytemat.data()};
1269
1270 objp->orient.rvec.x = *sp++ << MATRIX_PRECISION;
1271 objp->orient.uvec.x = *sp++ << MATRIX_PRECISION;
1272 objp->orient.fvec.x = *sp++ << MATRIX_PRECISION;
1273 objp->orient.rvec.y = *sp++ << MATRIX_PRECISION;
1274 objp->orient.uvec.y = *sp++ << MATRIX_PRECISION;
1275 objp->orient.fvec.y = *sp++ << MATRIX_PRECISION;
1276 objp->orient.rvec.z = *sp++ << MATRIX_PRECISION;
1277 objp->orient.uvec.z = *sp++ << MATRIX_PRECISION;
1278 objp->orient.fvec.z = *sp++ << MATRIX_PRECISION;
1279
1280 const auto segnum = segnum_t{INTEL_SHORT(underlying_value(spp.segment))};
1281
1282 Assert(segnum <= Highest_segment_index);
1283
1284 const auto &&segp = vmsegptridx(segnum);
1285 auto &vcvertptr = Vertices.vcptr;
1286 auto &vp = *vcvertptr(segp->verts[segment_relative_vertnum::_0]);
1287 objp->pos.x = (INTEL_SHORT(spp.xo) << RELPOS_PRECISION) + vp.x;
1288 objp->pos.y = (INTEL_SHORT(spp.yo) << RELPOS_PRECISION) + vp.y;
1289 objp->pos.z = (INTEL_SHORT(spp.zo) << RELPOS_PRECISION) + vp.z;
1290
1291 objp->mtype.phys_info.velocity.x = (INTEL_SHORT(spp.velx) << spp.velocity_precision_shift);
1292 objp->mtype.phys_info.velocity.y = (INTEL_SHORT(spp.vely) << spp.velocity_precision_shift);
1293 objp->mtype.phys_info.velocity.z = (INTEL_SHORT(spp.velz) << spp.velocity_precision_shift);
1294
1295 obj_relink(vmobjptr, vmsegptr, objp, segp);
1296 }
1297 #endif
1298
1299 void extract_quaternionpos(fvmobjptr &vmobjptr, fvmsegptr &vmsegptr, const vmobjptridx_t objp, quaternionpos &qpp)
1300 {
1301 reconstruct_at(objp->orient, vms_matrix_from_quaternion, qpp.orient);
1302
1303 objp->pos = qpp.pos;
1304 objp->mtype.phys_info.velocity = qpp.vel;
1305 objp->mtype.phys_info.rotvel = qpp.rotvel;
1306
1307 const auto segnum{qpp.segment};
1308 Assert(segnum <= Highest_segment_index);
1309 obj_relink(vmobjptr, vmsegptr, objp, vmsegptridx(segnum));
1310 }
1311 #endif
1312
1313 }
1314
1315 namespace dcx {
1316
1317 #if !DXX_USE_EDITOR
1318 namespace {
1319 #endif
1320
1321 // -------------------------------------------------------------------------------
1322 void create_walls_on_side(fvcvertptr &vcvertptr, shared_segment &sp, const sidenum_t sidenum)
1323 {
1324 auto &vs = Side_to_verts[sidenum];
1325 const auto v0 = sp.verts[vs[side_relative_vertnum::_0]];
1326 const auto v1 = sp.verts[vs[side_relative_vertnum::_1]];
1327 const auto v2 = sp.verts[vs[side_relative_vertnum::_2]];
1328 const auto v3 = sp.verts[vs[side_relative_vertnum::_3]];
1329
1330 verts_for_normal vfn{v0, v1, v2, v3};
1331 const auto negate_flag = get_verts_for_normal(vfn);
1332 auto &vvm0 = *vcvertptr(vfn.vsorted[0]);
1333 auto vn{vm_vec_normal(vvm0, vcvertptr(vfn.vsorted[1]), vcvertptr(vfn.vsorted[2]))};
1334 const fix dist_to_plane = abs(vm_dist_to_plane(vcvertptr(vfn.vsorted[3]), vn, vvm0));
1335
1336 if (negate_flag)
1337 vm_vec_negate(vn);
1338
1339 auto &s = sp.sides[sidenum];
1340 if (dist_to_plane > PLANE_DIST_TOLERANCE)
1341 {
1342 add_side_as_2_triangles(vcvertptr, sp, sidenum);
1343
1344 //this code checks to see if we really should be triangulated, and
1345 //de-triangulates if we shouldn't be.
1346
1347 int s0,s1;
1348
1349 const auto &&[num_faces, vertex_list] = create_abs_vertex_lists(sp, s, sidenum);
1350 assert(num_faces != vertex_array_side_type::quad);
1351 (void)num_faces;
1352
1353 auto &vvn = *vcvertptr(min(vertex_list[0],vertex_list[2]));
1354
1355 const fix dist0 = vm_dist_to_plane(vcvertptr(vertex_list[1]), s.normals[1], vvn);
1356 const fix dist1 = vm_dist_to_plane(vcvertptr(vertex_list[4]), s.normals[0], vvn);
1357
1358 s0 = sign(dist0);
1359 s1 = sign(dist1);
1360
1361 if (!(s0 == 0 || s1 == 0 || s0 != s1))
1362 return;
1363 //detriangulate!
1364 }
1365 s.type = side_type::quad;
1366 s.normals[0] = vn;
1367 s.normals[1] = vn;
1368 }
1369
1370 // -------------------------------------------------------------------------------
1371 // Make a just-modified segment side valid.
1372 void validate_segment_side(fvcvertptr &vcvertptr, const vmsegptridx_t sp, const sidenum_t sidenum)
1373 {
1374 auto &sside = sp->shared_segment::sides[sidenum];
1375 auto &uside = sp->unique_segment::sides[sidenum];
1376 create_walls_on_side(vcvertptr, sp, sidenum);
1377 /*
1378 * If the texture was wrong, then fix it and log a diagnostic. For
1379 * builtin missions, log the diagnostic at level CON_VERBOSE, since
1380 * retail levels trigger this during normal play. For external
1381 * missions, log the diagnostic at level CON_URGENT. External
1382 * levels might be fixable by contacting the author, but the retail
1383 * levels can only be fixed by using a Rebirth level patch file (not
1384 * supported yet). When fixing the texture, change it to 0 for
1385 * walls and 1 for non-walls. This should make walls transparent
1386 * for their primary texture; transparent non-walls usually generate
1387 * ugly visual artifacts, so choose a non-zero texture for them.
1388 *
1389 * Known affected retail levels (incomplete list):
1390
1391 Descent 2: Counterstrike
1392 sha256: f1abf516512739c97b43e2e93611a2398fc9f8bc7a014095ebc2b6b2fd21b703 descent2.hog
1393 Levels 1-3: clean
1394
1395 Level #4
1396 segment #170 side #4 has invalid tmap 910 (NumTextures=910)
1397 segment #171 side #5 has invalid tmap 910 (NumTextures=910)
1398 segment #184 side #2 has invalid tmap 910 (NumTextures=910)
1399 segment #188 side #5 has invalid tmap 910 (NumTextures=910)
1400
1401 Level #5
1402 segment #141 side #4 has invalid tmap 910 (NumTextures=910)
1403
1404 Level #6
1405 segment #128 side #4 has invalid tmap 910 (NumTextures=910)
1406
1407 Level #7
1408 segment #26 side #5 has invalid tmap 910 (NumTextures=910)
1409 segment #28 side #5 has invalid tmap 910 (NumTextures=910)
1410 segment #60 side #5 has invalid tmap 910 (NumTextures=910)
1411 segment #63 side #5 has invalid tmap 910 (NumTextures=910)
1412 segment #161 side #4 has invalid tmap 910 (NumTextures=910)
1413 segment #305 side #4 has invalid tmap 910 (NumTextures=910)
1414 segment #427 side #4 has invalid tmap 910 (NumTextures=910)
1415 segment #533 side #5 has invalid tmap 910 (NumTextures=910)
1416 segment #536 side #4 has invalid tmap 910 (NumTextures=910)
1417 segment #647 side #4 has invalid tmap 910 (NumTextures=910)
1418 segment #648 side #5 has invalid tmap 910 (NumTextures=910)
1419
1420 Level #8
1421 segment #0 side #4 has invalid tmap 910 (NumTextures=910)
1422 segment #92 side #0 has invalid tmap 910 (NumTextures=910)
1423 segment #92 side #5 has invalid tmap 910 (NumTextures=910)
1424 segment #94 side #1 has invalid tmap 910 (NumTextures=910)
1425 segment #94 side #2 has invalid tmap 910 (NumTextures=910)
1426 segment #95 side #0 has invalid tmap 910 (NumTextures=910)
1427 segment #95 side #1 has invalid tmap 910 (NumTextures=910)
1428 segment #97 side #5 has invalid tmap 910 (NumTextures=910)
1429 segment #98 side #3 has invalid tmap 910 (NumTextures=910)
1430 segment #100 side #1 has invalid tmap 910 (NumTextures=910)
1431 segment #102 side #1 has invalid tmap 910 (NumTextures=910)
1432 segment #104 side #3 has invalid tmap 910 (NumTextures=910)
1433
1434 Levels 9-end: unchecked
1435
1436 */
1437 const auto old_tmap_num = uside.tmap_num;
1438 if (const auto old_tmap_idx = get_texture_index(old_tmap_num); old_tmap_idx >= NumTextures)
1439 uside.tmap_num = build_texture1_value((
1440 LevelErrorV(PLAYING_BUILTIN_MISSION ? CON_VERBOSE : CON_URGENT, "segment #%hu side #%i has invalid tmap %u (NumTextures=%u).", sp.get_unchecked_index(), underlying_value(sidenum), old_tmap_idx, NumTextures),
1441 (sside.wall_num == wall_none)
1442 ));
1443
1444 // Set render_flag.
1445 // If side doesn't have a child, then render wall. If it does have a child, but there is a temporary
1446 // wall there, then do render wall.
1447 // if (sp->children[sidenum] == -1)
1448 // sp->sides[sidenum].render_flag = 1;
1449 // else if (sp->sides[sidenum].wall_num != -1)
1450 // sp->sides[sidenum].render_flag = 1;
1451 // else
1452 // sp->sides[sidenum].render_flag = 0;
1453 }
1454
1455 // -------------------------------------------------------------------------------
1456 // Make a just-modified segment valid.
1457 // check all sides to see how many faces they each should have (0,1,2)
1458 // create new vector normals
1459 void validate_segment(fvcvertptr &vcvertptr, const vmsegptridx_t sp)
1460 {
1461 #if DXX_USE_EDITOR
1462 Degenerate_segment_found |= check_for_degenerate_segment(vcvertptr, sp);
1463 #endif
1464
1465 for (const auto side : MAX_SIDES_PER_SEGMENT)
1466 validate_segment_side(vcvertptr, sp, side);
1467 }
1468
1469 #if !DXX_USE_EDITOR
1470 }
1471 #endif
1472
1473 // -------------------------------------------------------------------------------
1474 // Validate all segments.
1475 // Highest_segment_index must be set.
1476 // For all used segments (number <= Highest_segment_index), segnum field must be != -1.
1477 void validate_segment_all(d_level_shared_segment_state &LevelSharedSegmentState)
1478 {
1479 auto &Segments = LevelSharedSegmentState.get_segments();
1480 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
1481 auto &Vertices = LevelSharedVertexState.get_vertices();
1482 for (const auto &&segp : Segments.vmptridx)
1483 {
1484 #if DXX_USE_EDITOR
1485 if (segp->shared_segment::segnum != segment_none)
1486 #endif
1487 validate_segment(Vertices.vcptr, segp);
1488 }
1489
1490 #if DXX_USE_EDITOR
1491 for (shared_segment &s : partial_range(Segments, Segments.get_count(), Segments.size()))
1492 s.segnum = segment_none;
1493 #endif
1494 }
1495
1496 // ------------------------------------------------------------------------------------------------------
1497 // Picks a random point in a segment like so:
1498 // From center, go up to 50% of way towards any of the 8 vertices.
1499 vms_vector pick_random_point_in_seg(fvcvertptr &vcvertptr, const shared_segment &sp, std::minstd_rand r)
1500 {
1501 auto new_pos{compute_segment_center(vcvertptr, sp)};
1502 const auto vnum = segment_relative_vertnum{std::uniform_int_distribution<uint8_t>(0, MAX_VERTICES_PER_SEGMENT - 1)(r)};
1503 auto &&vec2{vm_vec_build_sub(vcvertptr(sp.verts[vnum]), new_pos)};
1504 vm_vec_scale(vec2, std::uniform_int_distribution<fix>(0, f0_5 - 1)(r)); // always in 0..1/2 fix
1505 vm_vec_add2(new_pos, vec2);
1506 return new_pos;
1507 }
1508
1509 }
1510
1511 namespace dsx {
1512
1513 #if DXX_BUILD_DESCENT == 2
1514 //these constants should match the ones in seguvs
1515 #define LIGHT_DISTANCE_THRESHOLD (F1_0*80)
1516 #define Magical_light_constant (F1_0*16)
1517
1518 namespace {
1519
1520 /* The array can be of any type that can hold values in the range
1521 * [0, AMBIENT_SEGMENT_DEPTH].
1522 */
1523 struct segment_lava_depth_array : enumerated_array<uint8_t, MAX_SEGMENTS, segnum_t> {};
1524 struct segment_water_depth_array : enumerated_array<uint8_t, MAX_SEGMENTS, segnum_t> {};
1525
1526 // ------------------------------------------------------------------------------------------
1527 //cast static light from a segment to nearby segments
1528 static void apply_light_to_segment(visited_segment_bitarray_t &visited, const vmsegptridx_t segp, const vms_vector &segment_center, const fix light_intensity, const unsigned recursion_depth)
1529 {
1530 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
1531 auto &Vertices = LevelSharedVertexState.get_vertices();
1532 fix dist_to_rseg;
1533 if (auto &&visited_ref = visited[segp])
1534 {
1535 }
1536 else
1537 {
1538 visited_ref = true;
1539 auto &vcvertptr = Vertices.vcptr;
1540 const auto r_segment_center{compute_segment_center(vcvertptr, segp)};
1541 dist_to_rseg = vm_vec_dist_quick(r_segment_center, segment_center);
1542
1543 if (dist_to_rseg <= LIGHT_DISTANCE_THRESHOLD) {
1544 fix light_at_point;
1545 if (dist_to_rseg > F1_0)
1546 light_at_point = fixdiv(Magical_light_constant, dist_to_rseg);
1547 else
1548 light_at_point = Magical_light_constant;
1549
1550 if (light_at_point >= 0) {
1551 light_at_point = fixmul(light_at_point, light_intensity);
1552 #if 0 // don't see the point, static_light can be greater than F1_0
1553 if (light_at_point >= F1_0)
1554 light_at_point = F1_0-1;
1555 if (light_at_point <= -F1_0)
1556 light_at_point = -(F1_0-1);
1557 #endif
1558 unique_segment &useg = segp;
1559 auto &static_light = useg.static_light;
1560 static_light += light_at_point;
1561 if (static_light < 0) // if it went negative, saturate
1562 static_light = 0;
1563 } // end if (light_at_point...
1564 } // end if (dist_to_rseg...
1565 }
1566
1567 if (recursion_depth < 2)
1568 {
1569 auto &Walls = LevelUniqueWallSubsystemState.Walls;
1570 auto &vcwallptr = Walls.vcptr;
1571 for (const auto sidenum : MAX_SIDES_PER_SEGMENT)
1572 {
1573 if (WALL_IS_DOORWAY(GameBitmaps, Textures, vcwallptr, segp, sidenum) & WALL_IS_DOORWAY_FLAG::rendpast)
1574 apply_light_to_segment(visited, segp.absolute_sibling(segp->children[sidenum]), segment_center, light_intensity, recursion_depth+1);
1575 }
1576 }
1577 }
1578
1579
1580 //update the static_light field in a segment, which is used for object lighting
1581 //this code is copied from the editor routine calim_process_all_lights()
1582 static void change_segment_light(const vmsegptridx_t segp, const sidenum_t sidenum, const unsigned dir)
1583 {
1584 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
1585 auto &TmapInfo = LevelUniqueTmapInfoState.TmapInfo;
1586 auto &Vertices = LevelSharedVertexState.get_vertices();
1587 auto &Walls = LevelUniqueWallSubsystemState.Walls;
1588 auto &vcwallptr = Walls.vcptr;
1589 if (WALL_IS_DOORWAY(GameBitmaps, Textures, vcwallptr, segp, sidenum) & WALL_IS_DOORWAY_FLAG::render)
1590 {
1591 auto &sidep = segp->unique_segment::sides[sidenum];
1592 const auto light_intensity = TmapInfo[get_texture_index(sidep.tmap_num)].lighting + TmapInfo[get_texture_index(sidep.tmap_num2)].lighting;
1593 if (light_intensity) {
1594 auto &vcvertptr = Vertices.vcptr;
1595 const auto segment_center{compute_segment_center(vcvertptr, segp)};
1596 visited_segment_bitarray_t visited;
1597 apply_light_to_segment(visited, segp, segment_center, light_intensity * dir, 0);
1598 }
1599 }
1600
1601 //this is a horrible hack to get around the horrible hack used to
1602 //smooth lighting values when an object moves between segments
1603 old_viewer = NULL;
1604
1605 }
1606
1607 // ------------------------------------------------------------------------------------------
1608 // dir = +1 -> add light
1609 // dir = -1 -> subtract light
1610 // dir = 17 -> add 17x light
1611 // dir = 0 -> you are dumb
1612 static void change_light(const d_level_shared_destructible_light_state &LevelSharedDestructibleLightState, const vmsegptridx_t segnum, const sidenum_t sidenum, const int dir)
1613 {
1614 const fix ds = dir * DL_SCALE;
1615 auto &Dl_indices = LevelSharedDestructibleLightState.Dl_indices;
1616 auto &Delta_lights = LevelSharedDestructibleLightState.Delta_lights;
1617 for (const dl_index &i : std::ranges::equal_range(Dl_indices.vcptr, dl_index{segnum.get_unchecked_index(), sidenum, {}, {}}))
1618 {
1619 const std::size_t idx = underlying_value(i.index);
1620 for (auto &j : partial_const_range(Delta_lights, idx, idx + i.count))
1621 {
1622 assert(j.sidenum < MAX_SIDES_PER_SEGMENT);
1623 const auto &&segp = vmsegptr(j.segnum);
1624 auto &uvls = segp->unique_segment::sides[j.sidenum].uvls;
1625 for (const auto k : MAX_VERTICES_PER_SIDE)
1626 {
1627 auto &l = uvls[k].l;
1628 const fix dl = ds * j.vert_light[k];
1629 if ((l += dl) < 0)
1630 l = 0;
1631 }
1632 }
1633 }
1634
1635 //recompute static light for segment
1636 change_segment_light(segnum,sidenum,dir);
1637 }
1638
1639 static inline sound_ambient_flags &operator|=(sound_ambient_flags &l, const sound_ambient_flags r)
1640 {
1641 return l = static_cast<sound_ambient_flags>(static_cast<uint8_t>(l) | static_cast<uint8_t>(r));
1642 }
1643
1644 /* On entry, `segdepth_lava` or `segdepth_water` may be nullptr if the
1645 * corresponding type is not tracked. `s2f_bit` tracks what flags the initial
1646 * caller is tallying, which may be both types even if one of the tracking
1647 * arrays was reset to nullptr during an inner iteration.
1648 */
1649 static void ambient_mark_bfs(const vmsegptridx_t segp, segment_lava_depth_array *segdepth_lava, segment_water_depth_array *segdepth_water, const unsigned depth, const sound_ambient_flags s2f_bit)
1650 {
1651 segp->s2_flags |= s2f_bit;
1652 /* For each of lava and water, check whether the segment was previously
1653 * visited by an iteration of ambient_mark_bfs that had a higher (more
1654 * permissive) depth count.
1655 *
1656 * If no, record the current depth count in the array.
1657 * If yes, then do not visit it again now, because any work that would be
1658 * done now would already have been done by the prior visit. Track this by
1659 * setting the corresponding array pointer to nullptr, which serves
1660 * multiple purposes:
1661 * - If one array pointer is null, no further tracking is done for that
1662 * type, because every subsequent iteration would also find that no
1663 * further recursion is needed for that type.
1664 * - Once both array pointers are null, every child segment that this call
1665 * could visit would be skipped by both lava and water, so return early
1666 * without visiting them.
1667 */
1668 if (segdepth_lava)
1669 {
1670 auto &d = (*segdepth_lava)[segp];
1671 if (d < depth)
1672 d = depth;
1673 else
1674 segdepth_lava = nullptr;
1675 }
1676 if (segdepth_water)
1677 {
1678 auto &d = (*segdepth_water)[segp];
1679 if (d < depth)
1680 d = depth;
1681 else
1682 segdepth_water = nullptr;
1683 }
1684 if (!segdepth_lava && !segdepth_water)
1685 return;
1686
1687 auto &Walls = LevelUniqueWallSubsystemState.Walls;
1688 auto &vcwallptr = Walls.vcptr;
1689 for (const auto i : MAX_SIDES_PER_SEGMENT)
1690 {
1691 const auto child = segp->children[i];
1692
1693 /*
1694 * No explicit check for IS_CHILD. If !IS_CHILD, then
1695 * WALL_IS_DOORWAY never sets WALL_IS_DOORWAY_FLAG::rendpast.
1696 */
1697 if (!(WALL_IS_DOORWAY(GameBitmaps, Textures, vcwallptr, segp, i) & WALL_IS_DOORWAY_FLAG::rendpast))
1698 continue;
1699 ambient_mark_bfs(segp.absolute_sibling(child), segdepth_lava, segdepth_water, depth - 1, s2f_bit);
1700 }
1701 }
1702
1703 }
1704
1705 // Subtract light cast by a light source from all surfaces to which it applies light.
1706 // This is precomputed data, stored at static light application time in the editor (the slow lighting function).
1707 // returns 1 if lights actually subtracted, else 0
1708 int subtract_light(const d_level_shared_destructible_light_state &LevelSharedDestructibleLightState, const vmsegptridx_t segnum, const sidenum_t sidenum)
1709 {
1710 unique_segment &useg = segnum;
1711 auto &light_subtracted = useg.light_subtracted;
1712 const auto mask = build_sidemask(sidenum);
1713 if (light_subtracted & mask)
1714 return 0;
1715 light_subtracted |= mask;
1716 change_light(LevelSharedDestructibleLightState, segnum, sidenum, -1);
1717 return 1;
1718 }
1719
1720 // Add light cast by a light source from all surfaces to which it applies light.
1721 // This is precomputed data, stored at static light application time in the editor (the slow lighting function).
1722 // You probably only want to call this after light has been subtracted.
1723 // returns 1 if lights actually added, else 0
1724 int add_light(const d_level_shared_destructible_light_state &LevelSharedDestructibleLightState, const vmsegptridx_t segnum, sidenum_t sidenum)
1725 {
1726 const auto mask = build_sidemask(sidenum);
1727 unique_segment &useg = segnum;
1728 auto &light_subtracted = useg.light_subtracted;
1729 if (!(light_subtracted & mask))
1730 return 0;
1731 light_subtracted &= ~mask;
1732 change_light(LevelSharedDestructibleLightState, segnum, sidenum, 1);
1733 return 1;
1734 }
1735
1736 // Parse the Light_subtracted array, turning on or off all lights.
1737 void apply_all_changed_light(const d_level_shared_destructible_light_state &LevelSharedDestructibleLightState, fvmsegptridx &vmsegptridx)
1738 {
1739 range_for (const auto &&segp, vmsegptridx)
1740 {
1741 for (const auto j : MAX_SIDES_PER_SEGMENT)
1742 {
1743 unique_segment &useg = segp;
1744 if (useg.light_subtracted & build_sidemask(j))
1745 change_light(LevelSharedDestructibleLightState, segp, j, -1);
1746 }
1747 }
1748 }
1749
1750 // Should call this whenever a new mine gets loaded.
1751 // More specifically, should call this whenever something global happens
1752 // to change the status of static light in the mine.
1753 void clear_light_subtracted(void)
1754 {
1755 for (unique_segment &useg : vmsegptr)
1756 useg.light_subtracted = {};
1757 }
1758
1759 #define AMBIENT_SEGMENT_DEPTH 5
1760
1761 // -----------------------------------------------------------------------------
1762 // Indicate all segments which are within audible range of falling water or lava,
1763 // and so should hear ambient gurgles.
1764 void set_ambient_sound_flags()
1765 {
1766 auto &TmapInfo = LevelUniqueTmapInfoState.TmapInfo;
1767 for (auto &seg : vmsegptr)
1768 seg.s2_flags = {};
1769 // Now, all segments containing ambient lava or water sound makers are flagged.
1770 // Additionally flag all segments which are within range of them.
1771 // Mark all segments which are sources of the sound.
1772 segment_lava_depth_array segdepth_lava{};
1773 segment_water_depth_array segdepth_water{};
1774
1775 range_for (const auto &&segp, vmsegptridx)
1776 {
1777 for (const auto j : MAX_SIDES_PER_SEGMENT)
1778 {
1779 const auto &sside = segp->shared_segment::sides[j];
1780 const auto &uside = segp->unique_segment::sides[j];
1781 if (IS_CHILD(segp->children[j]) && sside.wall_num == wall_none)
1782 /* If this side is open and there is no wall defined,
1783 * then the texture is never visible to the player.
1784 * This happens normally in some level editors if the
1785 * texture is not cleared when the child segment is
1786 * added. Skip this side.
1787 */
1788 continue;
1789 /* No other call site needs to combine two sets of
1790 * tmapinfo_flags, so there is no overloaded operator to
1791 * handle this. Use the casts to allow it here.
1792 */
1793 const auto texture_flags = static_cast<tmapinfo_flags>(underlying_value(TmapInfo[get_texture_index(uside.tmap_num)].flags) | underlying_value(TmapInfo[get_texture_index(uside.tmap_num2)].flags));
1794 /* These variables do not need to be named, but naming them
1795 * is the easiest way to establish sequence points, so that
1796 * `sound_flag` is passed to `ambient_mark_bfs` only after
1797 * both ternary expressions have finished.
1798 */
1799 sound_ambient_flags sound_flag{};
1800 const auto pl = (texture_flags & tmapinfo_flag::lava) ? (sound_flag |= sound_ambient_flags::lava, &segdepth_lava) : nullptr;
1801 const auto pw = (texture_flags & tmapinfo_flag::water) ? (sound_flag |= sound_ambient_flags::water, &segdepth_water) : nullptr;
1802 if (sound_flag != sound_ambient_flags::None)
1803 ambient_mark_bfs(segp, pl, pw, AMBIENT_SEGMENT_DEPTH, sound_flag);
1804 }
1805 }
1806 }
1807 #endif
1808 }