From 49bfdbef9f0643e495c80734762822f429586df5 Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Sun, 4 Nov 2018 16:47:45 +0100 Subject: [PATCH 01/16] - create an intermediate structure between sectors and subsectors. A section is a continuous part of a sector or in some case of several nearby continuous parts. For sectors with far away parts multiple sections will be created, especially when they lie in disjoint parts of the map. This is mainly supposed to cut down on time for linking dynamic lights. Since they need to traverse subsectors to find all touching sidedefs a more coarse data structure that only contains the info needed for this is more suitable. In particular, this does not contain any intra-sector lines, i.e. those with both sides in the same sector. --- src/CMakeLists.txt | 1 + src/am_map.cpp | 2 +- src/hwrenderer/data/hw_sections.cpp | 764 +++++++++++++++++++++++++ src/hwrenderer/data/hw_sections.h | 126 +++++ src/p_setup.cpp | 2 + src/p_setup.h | 3 + src/r_data/renderinfo.cpp | 244 +++++++- src/r_defs.h | 1 + src/tarray.h | 141 +++++ unused/gl_sections.cpp | 845 ---------------------------- unused/gl_sections.h | 57 -- 11 files changed, 1282 insertions(+), 904 deletions(-) create mode 100644 src/hwrenderer/data/hw_sections.cpp create mode 100644 src/hwrenderer/data/hw_sections.h delete mode 100644 unused/gl_sections.cpp delete mode 100644 unused/gl_sections.h diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index d5ebda5b1..559379a6d 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1049,6 +1049,7 @@ set (PCH_SOURCES gl/system/gl_buffers.cpp gl/textures/gl_hwtexture.cpp gl/textures/gl_samplers.cpp + hwrenderer/data/hw_sections.cpp hwrenderer/data/flatvertices.cpp hwrenderer/data/hw_viewpointbuffer.cpp hwrenderer/dynlights/hw_aabbtree.cpp diff --git a/src/am_map.cpp b/src/am_map.cpp index e0296e797..58ac47085 100644 --- a/src/am_map.cpp +++ b/src/am_map.cpp @@ -2072,7 +2072,7 @@ void AM_drawSubsectors() continue; } - if ((!(subsectors[i].flags & SSECMF_DRAWN) || (subsectors[i].render_sector->MoreFlags & SECMF_HIDDEN)) && am_cheat == 0) + if ((!(subsectors[i].flags & SSECMF_DRAWN) || (subsectors[i].flags & SSECF_HOLE) || (subsectors[i].render_sector->MoreFlags & SECMF_HIDDEN)) && am_cheat == 0) { continue; } diff --git a/src/hwrenderer/data/hw_sections.cpp b/src/hwrenderer/data/hw_sections.cpp new file mode 100644 index 000000000..9364b9712 --- /dev/null +++ b/src/hwrenderer/data/hw_sections.cpp @@ -0,0 +1,764 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2008-2018 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + + + +#include +#include "i_system.h" +#include "p_local.h" +#include "c_dispatch.h" +#include "r_defs.h" +#include "g_levellocals.h" +#include "hw_sections.h" +#include "earcut.hpp" +#include "stats.h" +#include "p_setup.h" +#include "c_dispatch.h" +#include "memarena.h" + +using DoublePoint = std::pair; + +template<> struct THashTraits +{ + // Use all bits when hashing doubles instead of converting them to ints. + hash_t Hash(const DoublePoint &key) + { + return (hash_t)SuperFastHash((const char*)(const void*)&key, sizeof(key)); + } + int Compare(const DoublePoint &left, const DoublePoint &right) { return left != right; } +}; + + +struct WorkSectionLine +{ + vertex_t *start; + vertex_t *end; + side_t *sidedef; + seg_t *refseg; + int tempindex; + int mygroup; + WorkSectionLine *partner; + bool flagged; +}; + + +struct WorkSection +{ + int sectorindex; + int mapsection; + bool hasminisegs; + TArraysegments; + TArray originalSides; // The segs will lose some of these while working on them. +}; + +struct TriangleWorkData +{ + BoundingRect boundingBox; + unsigned boundingLoopStart; +}; + +struct GroupWork +{ + WorkSection *section; + TriangleWorkData *work; + int index; +}; + +struct Group +{ + TArray groupedSections; + TMap sideMap; + TArray segments; +}; + +class FSectionCreator +{ + FMemArena allocator; + TArrayAllAllocatedLines; + + bool verbose = false; + TMap> subsectormap; + TArray> rawsections; // list of unprocessed subsectors. Sector and mapsection can be retrieved from the elements so aren't stored. + TArray sections; + + TArray triangles; + + TArray groups; + TArray groupForSection; + +public: + + FSectionCreator() + { + // These must be manually destroyed but not deleted. + for (auto line : AllAllocatedLines) + { + line->~WorkSectionLine(); + } + } + + // Allocate these from a static allocator so that they remain fixed in memory and avoid excessive small allocations. + WorkSectionLine *NewLine() + { + void *mem = allocator.Alloc(sizeof(WorkSectionLine)); + auto line = new(mem) WorkSectionLine; + AllAllocatedLines.Push(line); + return line; + } + + int IndexOf(WorkSectionLine *line) + { + return AllAllocatedLines.Find(line); // slow, but only used for debugging. + } + + int MakeKey(int sector, int mapsection) + { + return sector + (mapsection << 16); + } + + int MakeKey(const subsector_t &sub) + { + return MakeKey(sub.render_sector->Index(), sub.mapsection); + } + + int SectorFromKey(int key) + { + return key & 65535; + } + + int MapsectionFromKey(int key) + { + return key >> 16; + } + + //========================================================================== + // + // Groups subsectors by both sectors and mapsection + // The parts of a sector in a single map section is the upper boundary + // for what a sector section may contain. + // + //========================================================================== + + void GroupSubsectors() + { + for (auto &sub : level.subsectors) + { + int key = MakeKey(sub); + auto &array = subsectormap[key]; + array.Push(sub.Index()); + } + } + + //========================================================================== + // + // Go through the list and split each element further into + // connected groups of subsectors. + // + //========================================================================== + + void CompileSections() + { + TMap>::Pair *pair; + TMap>::Iterator it(subsectormap); + + while (it.NextPair(pair)) + { + CompileSections(pair->Value); + } + subsectormap.Clear(); + } + + //========================================================================== + // + // Find all groups of connected subsectors and put them into the group list + // + //========================================================================== + + void CompileSections(TArray &list) + { + TArray sublist; + TArray seglist; + while (list.Size() > 0) + { + sublist.Clear(); + seglist.Clear(); + int index; + list.Pop(index); + auto sub = &level.subsectors[index]; + + auto collect = [&](subsector_t *sub) + { + sublist.Push(sub->Index()); + for (unsigned i = 0; i < sub->numlines; i++) + { + if (sub->firstline[i].PartnerSeg && sub->firstline[i].Subsector->render_sector == sub->firstline[i].PartnerSeg->Subsector->render_sector) + { + seglist.Push(sub->firstline[i].PartnerSeg); + } + } + }; + + collect(sub); + + for (unsigned i = 0; i < seglist.Size(); i++) + { + auto subi = seglist[i]->Subsector->Index(); + + for (unsigned j = 0; j < list.Size(); j++) + { + if (subi == list[j]) + { + collect(&level.subsectors[subi]); + list.Delete(j); + j--; + } + } + } + rawsections.Push(std::move(sublist)); + } + } + + + //========================================================================== + // + // + //========================================================================== + + void MakeOutlines() + { + TArray lineForSeg(level.segs.Size(), true); + memset(lineForSeg.Data(), 0, sizeof(WorkSectionLine*) * level.segs.Size()); + for (auto &list : rawsections) + { + MakeOutline(list, lineForSeg); + } + + // Assign partners after everything has been collected + for (auto §ion : sections) + { + for (auto seg : section.segments) + { + if (seg->refseg && seg->refseg->PartnerSeg) + { + seg->partner = lineForSeg[seg->refseg->PartnerSeg->Index()]; + } + } + } + } + + //========================================================================== + // + // Creates an outline for a given section + // + //========================================================================== + + void MakeOutline(TArray &rawsection, TArray &lineForSeg) + { + TArray foundsides; + TArray outersegs; + TArray loopedsegs; + bool hasminisegs = false; + + // Collect all the segs that make up the outline of this section. + for (auto j : rawsection) + { + auto sub = &level.subsectors[j]; + + for (unsigned i = 0; i < sub->numlines; i++) + { + if (!sub->firstline[i].PartnerSeg || sub->firstline[i].Subsector->render_sector != sub->firstline[i].PartnerSeg->Subsector->render_sector) + { + outersegs.Push(&sub->firstline[i]); + if (sub->firstline[i].sidedef == nullptr) hasminisegs = true; + } + if (sub->firstline[i].sidedef) + { + foundsides.Push(sub->firstline[i].sidedef); // This may contain duplicate. Let's deal with those later. + } + } + } + + // Loop until all segs have been used. + seg_t *seg = nullptr; + unsigned startindex = 0; + while (outersegs.Size() > 0) + { + if (seg == nullptr) + { + for (unsigned i = 0; i < outersegs.Size(); i++) + { + if (outersegs[i]->sidedef != nullptr && outersegs[i]->sidedef->V1() == outersegs[i]->v1) + { + seg = outersegs[i]; + outersegs.Delete(i); + break; + } + } + if (seg == nullptr) + { + // There's only minisegs left. Most likely this is just node garbage. + // Todo: Need to check. + seg = outersegs[0]; + outersegs.Delete(0); + } + startindex = loopedsegs.Push(seg); + } + + // Find the next seg in the loop. + + auto segangle = VecToAngle(seg->v2->fPos() - seg->v1->fPos()); + + seg_t *pick = nullptr; + int pickindex = -1; + for (unsigned i = 0; i < outersegs.Size(); i++) + { + auto secondseg = outersegs[i]; + if (secondseg->v1->fPos() == seg->v2->fPos()) + { + // This should never choose a miniseg over a real sidedef. + if (pick == nullptr || (pick->sidedef == nullptr && secondseg->sidedef != nullptr)) + { + pick = secondseg; + pickindex = i; + } + else if (pick->sidedef == nullptr || secondseg->sidedef != nullptr) + { + // If there's more than one pick the one with the smallest angle. + auto pickangle = deltaangle(segangle, VecToAngle(pick->v2->fPos() - pick->v1->fPos())); + auto secondangle = deltaangle(segangle, VecToAngle(secondseg->v2->fPos() - secondseg->v1->fPos())); + + if (secondangle < pickangle) + { + pick = secondseg; + pickindex = i; + } + } + } + } + if (pick) + { + loopedsegs.Push(pick); + outersegs.Delete(pickindex); + seg = pick; + } + else + { + // There was no more seg connecting to the last one. We should have reached the beginning of the loop again. + if (loopedsegs.Last() == nullptr || loopedsegs[startindex]->v1->fPos() != loopedsegs.Last()->v2->fPos()) + { + // Did not find another one but have an unclosed loop. This should never happen and would indicate broken nodes. + // Error out and let the calling code deal with it. + I_Error("Unclosed loop in sector %d at position (%d, %d)\n", loopedsegs[0]->Subsector->render_sector->Index(), (int)loopedsegs[0]->v1->fX(), (int)loopedsegs[0]->v1->fY()); + } + seg = nullptr; + loopedsegs.Push(nullptr); // A separator is not really needed but useful for debugging. + } + } + if (loopedsegs.Size() > 0) + { + auto sector = loopedsegs[0]->Subsector->render_sector->Index(); + auto mapsec = loopedsegs[0]->Subsector->mapsection; + + TArray sectionlines(loopedsegs.Size(), true); + for (unsigned i = 0; i < loopedsegs.Size(); i++) + { + if (loopedsegs[i]) + { + sectionlines[i] = NewLine(); + *sectionlines[i] = { loopedsegs[i]->v1, loopedsegs[i]->v2, loopedsegs[i]->sidedef, loopedsegs[i], -1, (int)sections.Size(), nullptr }; + lineForSeg[loopedsegs[i]->Index()] = sectionlines[i]; + } + else + { + sectionlines[i] = NewLine(); + *sectionlines[i] = { nullptr, nullptr, nullptr, nullptr, -1, (int)sections.Size(), nullptr }; + } + } + + sections.Push({ sector, mapsec, hasminisegs, std::move(sectionlines), std::move(foundsides) }); + } + } + + + //============================================================================= + // + // Tries to merge continuous segs on the same sidedef + // + //============================================================================= + void MergeLines() + { + for (auto &build : sections) + { + for (int i = (int)build.segments.Size() - 1; i > 0; i--) + { + auto ln1 = build.segments[i]; + auto ln2 = build.segments[i - 1]; + + if (ln1->sidedef && ln2->sidedef && ln1->sidedef == ln2->sidedef) + { + if (ln1->partner == nullptr && ln2->partner == nullptr) + { + // identical references. These 2 lines can be merged. + ln2->end = ln1->end; + build.segments.Delete(i); + } + else if (ln1->partner && ln2->partner && ln1->partner->mygroup == ln2->partner->mygroup) + { + auto §ion = sections[ln1->partner->mygroup]; + auto index1 = section.segments.Find(ln1->partner); // note that ln1 and ln2 are ordered backward, so the partners are ordered forward. + auto index2 = section.segments.Find(ln2->partner); + if (index2 == index1 + 1 && index2 < section.segments.Size()) + { + // Merge both sides at once to ensure the data remains consistent. + ln2->partner->start = ln1->partner->start; + section.segments.Delete(index1); + ln2->end = ln1->end; + build.segments.Delete(i); + } + } + } + } + } + } + + + //============================================================================= + // + // + // + //============================================================================= + + void FindOuterLoops() + { + triangles.Resize(sections.Size()); + for (unsigned int i = 0; i < sections.Size(); i++) + { + auto §ion = sections[i]; + auto &work = triangles[i]; + + BoundingRect bounds = { 1e32, 1e32, -1e32, -1e32 }; + BoundingRect loopBounds = { 1e32, 1e32, -1e32, -1e32 }; + BoundingRect outermostBounds = { 1e32, 1e32, -1e32, -1e32 }; + unsigned outermoststart = ~0u; + unsigned loopstart = 0; + bool ispolyorg = false; + for (unsigned i = 0; i <= section.segments.Size(); i++) + { + if (i < section.segments.Size() && section.segments[i]->refseg) + { + ispolyorg |= !!(section.segments[i]->refseg->Subsector->flags & SSECF_POLYORG); + loopBounds.addVertex(section.segments[i]->start->fX(), section.segments[i]->start->fY()); + loopBounds.addVertex(section.segments[i]->end->fX(), section.segments[i]->end->fY()); + bounds.addVertex(section.segments[i]->start->fX(), section.segments[i]->start->fY()); + bounds.addVertex(section.segments[i]->end->fX(), section.segments[i]->end->fY()); + } + else + { + if (outermostBounds.left == 1e32 || loopBounds.contains(outermostBounds)) + { + outermostBounds = loopBounds; + outermoststart = loopstart; + loopstart = i + 1; + } + loopBounds = { 1e32, 1e32, -1e32, -1e32 }; + } + } + work.boundingLoopStart = outermoststart; + work.boundingBox = outermostBounds; + } + } + + //============================================================================= + // + // + // + //============================================================================= + + void GroupSections() + { + TArray workingSet; + + GroupWork first = { §ions[0], &triangles[0], 0 }; + workingSet.Push(first); + groupForSection.Resize(sections.Size()); + for (auto &i : groupForSection) i = -1; + + for (unsigned i = 1; i < sections.Size(); i++) + { + auto sect = §ions[i]; + if (sect->segments.Size() == 0) continue; + if (sect->sectorindex == first.section->sectorindex && sect->mapsection == first.section->mapsection) + { + workingSet.Push({ sect, &triangles[i], (int)i }); + } + else + { + GroupWorkingSet(workingSet); + workingSet.Clear(); + first = { §ions[i], &triangles[i], (int)i }; + workingSet.Push(first); + } + } + GroupWorkingSet(workingSet); + } + + //============================================================================= + // + // + // + //============================================================================= + + void GroupWorkingSet(TArray &workingSet) + { + const double MAX_GROUP_DIST = 256; + TArray build; + + if (workingSet.Size() == 1) + { + groupForSection[workingSet[0].index] = groups.Size(); + Group g; + g.groupedSections = std::move(workingSet); + groups.Push(std::move(g)); + return; + } + + while (workingSet.Size() > 0) + { + build.Clear(); + build.Push(workingSet[0]); + groupForSection[workingSet[0].index] = groups.Size(); + workingSet.Delete(0); + + // Don't use iterators here. These arrays are modified inside. + for (unsigned j = 0; j < build.Size(); j++) + { + auto ¤t = build[j]; + for (int i = 0; i < (int)workingSet.Size(); i++) + { + // Are both sections close together? + double dist = current.work->boundingBox.distanceTo(workingSet[i].work->boundingBox); + if (dist < MAX_GROUP_DIST) + { + build.Push(workingSet[i]); + groupForSection[workingSet[i].index] = groups.Size(); + workingSet.Delete(i); + i--; + continue; + } + // Also put in the same group if they share a sidedef. + bool sharing_sd = CheckForSharedSidedef(*current.section, *workingSet[i].section); + if (sharing_sd) + { + build.Push(workingSet[i]); + groupForSection[workingSet[i].index] = groups.Size(); + workingSet.Delete(i); + i--; + continue; + } + } + } + Group g; + g.groupedSections = std::move(build); + groups.Push(std::move(g)); + } + } + + //============================================================================= + // + // + // + //============================================================================= + + bool CheckForSharedSidedef(WorkSection &set1, WorkSection &set2) + { + for (auto seg : set1.segments) + { + if (seg->sidedef != nullptr) + { + for (auto seg2 : set2.segments) + { + if (seg2->sidedef == seg->sidedef) return true; + } + } + } + return false; + } + + //============================================================================= + // + // + // + //============================================================================= + + void ConstructOutput(FSectionContainer &output) + { + output.allSections.Resize(groups.Size()); + output.allIndices.Resize(level.subsectors.Size() + level.sides.Size()); + output.sectionForSubsectorPtr = &output.allIndices[0]; + output.sectionForSidedefPtr = &output.allIndices[level.subsectors.Size()]; + + unsigned numsegments = 0; + unsigned numsides = 0; + + // First index all the line segments here so that we can later do some quick referencing via the global array and count them and the distinct number of sidedefs in the section. + for (auto &group : groups) + { + for (auto &work : group.groupedSections) + { + auto §ion = *work.section; + for (auto segment : section.segments) + { + if (segment->refseg) + { + segment->tempindex = numsegments++; + group.segments.Push(segment); + } + } + for (auto side : section.originalSides) + { + group.sideMap[side->Index()] = true; + } + } + numsides += group.sideMap.CountUsed(); + } + output.allLines.Resize(numsegments); + output.allSides.Resize(numsides); + + numsegments = 0; + numsides = 0; + + // Now piece it all together + unsigned curgroup = 0; + for (auto &group : groups) + { + FSection &dest = output.allSections[curgroup]; + dest.sector = &level.sectors[group.groupedSections[0].section->sectorindex]; + dest.mapsection = (short)group.groupedSections[0].section->mapsection; + dest.hacked = false; + dest.lighthead = nullptr; + dest.validcount = 0; + dest.segments.Set(&output.allLines[numsegments], group.segments.Size()); + dest.sides.Set(&output.allSides[numsides], group.sideMap.CountUsed()); + dest.bounds = {1e32, 1e32, -1e32, -1e32}; + numsegments += group.segments.Size(); + + for (auto &segment : group.segments) + { + // Use the indices calculated above to store these elements. + auto &fseg = output.allLines[segment->tempindex]; + fseg.start = segment->start; + fseg.end = segment->end; + fseg.partner = segment->partner == nullptr ? nullptr : &output.allLines[segment->partner->tempindex]; + fseg.sidedef = segment->sidedef; + dest.bounds.addVertex(fseg.start->fX(), fseg.start->fY()); + dest.bounds.addVertex(fseg.end->fX(), fseg.end->fY()); + } + TMap::Iterator it(group.sideMap); + TMap::Pair *pair; + while (it.NextPair(pair)) + { + output.allSides[numsides++] = &level.sides[pair->Key]; + } + curgroup++; + } + } +}; + + + +//============================================================================= +// +// +// +//============================================================================= + +void PrintSections(FSectionContainer &container) +{ + for (unsigned i = 0; i < container.allSections.Size(); i++) + { + auto §ion = container.allSections[i]; + + Printf(PRINT_LOG, "\n\nStart of section %d sector %d, mapsection %d, bounds=(%2.3f, %2.3f, %2.3f, %2.3f)\n", i, section.sector->Index(), section.mapsection, + section.bounds.left, section.bounds.top, section.bounds.right, section.bounds.bottom); + + for (unsigned j = 0; j < section.segments.Size(); j++) + { + auto &seg = section.segments[j]; + if (j > 0 && seg.start != section.segments[j - 1].end) + { + Printf(PRINT_LOG, "\n"); + } + FString partnerstring; + if (seg.partner) + { + if (seg.partner->sidedef) partnerstring.Format(", partner = %d (line %d)", seg.partner->sidedef->Index(), seg.partner->sidedef->linedef->Index()); + else partnerstring = ", partner = seg"; + } + else if (seg.sidedef && seg.sidedef->linedef) + { + partnerstring = ", one-sided line"; + } + if (seg.sidedef) + { + Printf(PRINT_LOG, "segment for sidedef %d (line %d) from (%2.6f, %2.6f) to (%2.6f, %2.6f)%s\n", + seg.sidedef->Index(), seg.sidedef->linedef->Index(), seg.start->fX(), seg.start->fY(), seg.end->fX(), seg.end->fY(), partnerstring.GetChars()); + } + else + { + Printf(PRINT_LOG, "segment for seg from (%2.6f, %2.6f) to (%2.6f, %2.6f)%s\n", + seg.start->fX(), seg.start->fY(), seg.end->fX(), seg.end->fY(), partnerstring.GetChars()); + } + } + } + Printf(PRINT_LOG, "%d sectors, %d subsectors, %d sections\n", level.sectors.Size(), level.subsectors.Size(), container.allSections.Size()); +} + + +//============================================================================= +// +// +// +//============================================================================= + +void MakeSections() +{ + FSectionContainer container; + cycle_t timer; + timer.Reset(); + timer.Clock(); + FSectionCreator creat; + creat.GroupSubsectors(); + creat.CompileSections(); + creat.MakeOutlines(); + creat.MergeLines(); + creat.FindOuterLoops(); + creat.GroupSections(); + creat.ConstructOutput(container); + timer.Unclock(); + PrintSections(container); + Printf("Time = %2.3f ms\n", timer.TimeMS()); +} + +CCMD(makesections) +{ + MakeSections(); +} \ No newline at end of file diff --git a/src/hwrenderer/data/hw_sections.h b/src/hwrenderer/data/hw_sections.h new file mode 100644 index 000000000..1cc6f2efa --- /dev/null +++ b/src/hwrenderer/data/hw_sections.h @@ -0,0 +1,126 @@ + +#ifndef __GL_SECTIONS_H +#define __GL_SECTIONS_H + +#include "tarray.h" +#include "r_defs.h" + +//========================================================================== +// +// +// +//========================================================================== + +struct BoundingRect +{ + double left, top, right, bottom; + + bool contains(const BoundingRect & other) + { + return left <= other.left && top <= other.top && right >= other.right && bottom >= other.bottom; + } + + bool intersects(const BoundingRect & other) + { + return !(other.left > right || + other.right < left || + other.top > bottom || + other.bottom < top); + } + + void Union(const BoundingRect & other) + { + if (other.left < left) left = other.left; + if (other.right > right) right = other.right; + if (other.top < top) top = other.top; + if (other.bottom > bottom) bottom = other.bottom; + } + + double distanceTo(const BoundingRect &other) + { + if (intersects(other)) return 0; + return std::max(std::min(fabs(left - other.right), fabs(right - other.left)), + std::min(fabs(top - other.bottom), fabs(bottom - other.top))); + } + + void addVertex(double x, double y) + { + if (x < left) left = x; + if (x > right) right = x; + if (y < top) top = y; + if (y > bottom) bottom = y; + } + + bool operator == (const BoundingRect &other) + { + return left == other.left && top == other.top && right == other.right && bottom == other.bottom; + } +}; + + +struct FSectionLine +{ + vertex_t *start; + vertex_t *end; + FSectionLine *partner; + side_t *sidedef; +}; + +struct FSection +{ + // tbd: Do we need a list of subsectors here? Ideally the subsectors should not be used anywhere anymore except for finding out where a location is. + TArrayView segments; + TArrayView sides; // contains all sidedefs, including the internal ones that do not make up the outer shape. (this list is not exclusive. A sidedef can be in multiple sections!) + sector_t *sector; + FLightNode *lighthead; // Light nodes (blended and additive) + BoundingRect bounds; + int validcount; + short mapsection; + char hacked; // 1: is part of a render hack +}; + +class FSectionContainer +{ +public: + TArray allLines; + TArray allSections; + //TArray allVertices; + TArray allSides; + TArray allIndices; + + int *sectionForSubsectorPtr; // stored inside allIndices + int *sectionForSidedefPtr; // also stored inside allIndices; + + FSection *SectionForSubsector(subsector_t *sub) + { + return SectionForSubsector(sub->Index()); + } + FSection *SectionForSubsector(int ssindex) + { + return ssindex < 0 ? nullptr : &allSections[sectionForSubsectorPtr[ssindex]]; + } + FSection *SectionForSidedef(side_t *side) + { + return SectionForSidedef(side->Index()); + } + FSection *SectionForSidedef(int sindex) + { + return sindex < 0 ? nullptr : &allSections[sectionForSidedefPtr[sindex]]; + } + void Clear() + { + allLines.Clear(); + allSections.Clear(); + allIndices.Clear(); + } + void Reset() + { + Clear(); + allLines.ShrinkToFit(); + allSections.ShrinkToFit(); + allIndices.ShrinkToFit(); + } +}; + + +#endif \ No newline at end of file diff --git a/src/p_setup.cpp b/src/p_setup.cpp index 4a48afbb6..d3ff4c499 100644 --- a/src/p_setup.cpp +++ b/src/p_setup.cpp @@ -4055,6 +4055,8 @@ void P_SetupLevel (const char *lumpname, int position, bool newGame) if (hasglnodes) { P_SetRenderSector(); + FixMinisegReferences(); + FixHoles(); } bodyqueslot = 0; diff --git a/src/p_setup.h b/src/p_setup.h index 31612894b..1f773e951 100644 --- a/src/p_setup.h +++ b/src/p_setup.h @@ -160,6 +160,9 @@ bool P_LoadGLNodes(MapData * map); bool P_CheckNodes(MapData * map, bool rebuilt, int buildtime); bool P_CheckForGLNodes(); void P_SetRenderSector(); +void FixMinisegReferences(); +void FixHoles(); +void ReportUnpairedMinisegs(); struct sidei_t // [RH] Only keep BOOM sidedef init stuff around for init diff --git a/src/r_data/renderinfo.cpp b/src/r_data/renderinfo.cpp index f0b8600fe..bf59ec0c0 100644 --- a/src/r_data/renderinfo.cpp +++ b/src/r_data/renderinfo.cpp @@ -247,7 +247,7 @@ static void PrepareSectorData() for (auto &sub : level.subsectors) { - sub.sectorindex = (uint16_t)sub.render_sector->subsectorcount++; + sub.render_sector->subsectorcount++; } for (auto &sec : level.sectors) @@ -573,7 +573,244 @@ void InitRenderInfo() } +//========================================================================== +// +// FixMinisegReferences +// +// Sometimes it can happen that two matching minisegs do not have their partner set. +// Fix that here. +// +//========================================================================== +void FixMinisegReferences() +{ + TArray bogussegs; + + for (unsigned i = 0; i < level.segs.Size(); i++) + { + if (level.segs[i].sidedef == nullptr && level.segs[i].PartnerSeg == nullptr) + { + bogussegs.Push(&level.segs[i]); + } + } + + for (unsigned i = 0; i < bogussegs.Size(); i++) + { + auto seg1 = bogussegs[i]; + seg_t *pick = nullptr; + unsigned int picki = -1; + + // Try to fix the reference: If there's exactly one other seg in the set which matches as a partner link those two segs together. + for (unsigned j = i + 1; j < bogussegs.Size(); j++) + { + auto seg2 = bogussegs[j]; + if (seg1->v1 == seg2->v2 && seg2->v1 == seg1->v2 && seg1->Subsector->render_sector == seg2->Subsector->render_sector) + { + pick = seg2; + picki = j; + break; + } + } + if (pick) + { + DPrintf(DMSG_NOTIFY, "Linking miniseg pair from (%2.3f, %2.3f) -> (%2.3f, %2.3f) in sector %d\n", pick->v2->fX(), pick->v2->fY(), pick->v1->fX(), pick->v1->fY(), pick->frontsector->Index()); + pick->PartnerSeg = seg1; + seg1->PartnerSeg = pick; + assert(seg1->v1 == pick->v2 && pick->v1 == seg1->v2); + bogussegs.Delete(picki); + bogussegs.Delete(i); + i--; + } + } +} + +//========================================================================== +// +// FixHoles +// +// ZDBSP can leave holes in the node tree on extremely detailed maps. +// To help out the triangulator these are filled with dummy subsectors +// so that it can process the area correctly. +// +//========================================================================== + +void FixHoles() +{ + TArray bogussegs; + TArray> segloops; + + for (unsigned i = 0; i < level.segs.Size(); i++) + { + if (level.segs[i].sidedef == nullptr && level.segs[i].PartnerSeg == nullptr) + { + bogussegs.Push(&level.segs[i]); + } + } + + while (bogussegs.Size() > 0) + { + segloops.Reserve(1); + auto *segloop = &segloops.Last(); + + seg_t *startseg; + seg_t *checkseg; + while (bogussegs.Size() > 0) + { + bool foundsome = false; + if (segloop->Size() == 0) + { + bogussegs.Pop(startseg); + segloop->Push(startseg); + checkseg = startseg; + } + for (unsigned i = 0; i < bogussegs.Size(); i++) + { + auto seg1 = bogussegs[i]; + + if (seg1->v1 == checkseg->v2 && seg1->Subsector->render_sector == checkseg->Subsector->render_sector) + { + foundsome = true; + segloop->Push(seg1); + bogussegs.Delete(i); + i--; + checkseg = seg1; + + if (seg1->v2 == startseg->v1) + { + // The loop is complete. Start a new one + segloops.Reserve(1); + segloop = &segloops.Last(); + } + } + } + if (!foundsome) + { + if ((*segloop)[0]->v1 != segloop->Last()->v2) + { + // There was no connected seg, leaving an unclosed loop. + // Clear this and continue looking. + segloop->Clear(); + } + } + } + for (unsigned i = 0; i < segloops.Size(); i++) + { + if (segloops[i].Size() == 0) + { + segloops.Delete(i); + i--; + } + } + + // Add dummy entries to the level's seg and subsector arrays + if (segloops.Size() > 0) + { + // cound the number of segs to add. + unsigned segcount = 0; + for (auto &segloop : segloops) + segcount += segloop.Size(); + + seg_t *oldsegstartptr = &level.segs[0]; + subsector_t *oldssstartptr = &level.subsectors[0]; + + unsigned newsegstart = level.segs.Reserve(segcount); + unsigned newssstart = level.subsectors.Reserve(segloops.Size()); + + seg_t *newsegstartptr = &level.segs[0]; + subsector_t *newssstartptr = &level.subsectors[0]; + + // Now fix all references to these in the level data. + // Note that the Index() method does not work here due to the reallocation. + for (auto &seg : level.segs) + { + if (seg.PartnerSeg) seg.PartnerSeg = newsegstartptr + (seg.PartnerSeg - oldsegstartptr); + seg.Subsector = newssstartptr + (seg.Subsector - oldssstartptr); + } + for (auto &sub : level.subsectors) + { + sub.firstline = newsegstartptr + (sub.firstline - oldsegstartptr); + } + for (auto &node : level.nodes) + { + // How hideous... :( + for (auto & p : node.children) + { + auto intp = (intptr_t)p; + if (intp & 1) + { + subsector_t *sp = (subsector_t*)(intp - 1); + sp = newssstartptr + (sp - oldssstartptr); + intp = intptr_t(sp) + 1; + p = (void*)intp; + } + } + } + for (auto &segloop : segloops) + { + for (auto &seg : segloop) + { + seg = newsegstartptr + (seg - oldsegstartptr); + } + } + + // The seg lists in the sidedefs and the subsector lists in the sectors are not set yet when this gets called. + + // Add the new data. This doesn't care about convexity. It is never directly used to generate a primitive. + for (auto &segloop : segloops) + { + Printf("Adding dummy subsector for sector %d\n", segloop[0]->Subsector->render_sector->Index()); + + subsector_t &sub = level.subsectors[newssstart++]; + memset(&sub, 0, sizeof(sub)); + sub.sector = segloop[0]->frontsector; + sub.render_sector = segloop[0]->Subsector->render_sector; + sub.numlines = segloop.Size(); + sub.firstline = &level.segs[newsegstart]; + sub.flags = SSECF_HOLE; + + for (auto otherseg : segloop) + { + Printf(" Adding seg from (%2.3f, %2.3f) -> (%2.3f, %2.3f)\n", otherseg->v2->fX(), otherseg->v2->fY(), otherseg->v1->fX(), otherseg->v1->fY()); + seg_t &seg = level.segs[newsegstart++]; + memset(&seg, 0, sizeof(seg)); + seg.v1 = otherseg->v2; + seg.v2 = otherseg->v1; + seg.frontsector = seg.backsector = otherseg->backsector = otherseg->frontsector; + seg.PartnerSeg = otherseg; + otherseg->PartnerSeg = &seg; + seg.Subsector = ⊂ + } + } + } + } +} + +//========================================================================== +// +// ReportUnpairedMinisegs +// +// Debug routine +// reports all unpaired minisegs that couldn't be fixed by either +// explicitly pairing them or combining them to a dummy subsector +// +//========================================================================== + +void ReportUnpairedMinisegs() +{ + int bogus = 0; + for (unsigned i = 0; i < level.segs.Size(); i++) + { + if (level.segs[i].sidedef == nullptr && level.segs[i].PartnerSeg == nullptr) + { + Printf("Unpaired miniseg %d, sector %d, (%d: %2.6f, %2.6f) -> (%d: %2.6f, %2.6f)\n", + i, level.segs[i].Subsector->render_sector->Index(), + level.segs[i].v1->Index(), level.segs[i].v1->fX(), level.segs[i].v1->fY(), + level.segs[i].v2->Index(), level.segs[i].v2->fX(), level.segs[i].v2->fY()); + bogus++; + } + } + if (bogus > 0) Printf("%d unpaired minisegs found\n", bogus); +} //========================================================================== // // @@ -594,3 +831,8 @@ CCMD(listmapsections) } } } + +CCMD(listbadminisegs) +{ + ReportUnpairedMinisegs(); +} diff --git a/src/r_defs.h b/src/r_defs.h index f3da27262..4bccef526 100644 --- a/src/r_defs.h +++ b/src/r_defs.h @@ -1437,6 +1437,7 @@ enum SSECF_DEGENERATE = 1, SSECMF_DRAWN = 2, SSECF_POLYORG = 4, + SSECF_HOLE = 8, }; struct FPortalCoverage diff --git a/src/tarray.h b/src/tarray.h index 153fcd0ba..79b8853bd 100644 --- a/src/tarray.h +++ b/src/tarray.h @@ -250,6 +250,12 @@ public: return Array[Count-1]; } + // returns address of first element + T *Data() const + { + return &Array[0]; + } + unsigned int Find(const T& item) const { unsigned int i; @@ -267,6 +273,7 @@ public: ::new((void*)&Array[Count]) T(item); return Count++; } + void Append(const TArray &item) { unsigned start = Reserve(item.Size()); @@ -350,6 +357,18 @@ public: ::new ((void *)&Array[index]) T(item); } } + + // Reserves a range of entries in the middle of the array, shifting elements as needed + void ReserveAt(unsigned int index, unsigned int amount) + { + Grow(amount); + memmove(&Array[index + amount], &Array[index], sizeof(T)*(Count - index - amount)); + for (unsigned i = 0; i < amount; i++) + { + ::new ((void *)&Array[index + i]) T(); + } + } + void ShrinkToFit () { if (Most > Count) @@ -1332,3 +1351,125 @@ public: memset(&bytes[0], 0, bytes.Size()); } }; + + +// A wrapper to externally stored data. +// I would have expected something for this in the stl, but std::span is only in C++20. +template +class TArrayView +{ +public: + + typedef TIterator iterator; + typedef TIterator const_iterator; + + iterator begin() + { + return &Array[0]; + } + const_iterator begin() const + { + return &Array[0]; + } + const_iterator cbegin() const + { + return &Array[0]; + } + + iterator end() + { + return &Array[Count]; + } + const_iterator end() const + { + return &Array[Count]; + } + const_iterator cend() const + { + return &Array[Count]; + } + + + //////// + TArrayView() = default; // intended to keep this type trivial. + TArrayView(T *data, unsigned count = 0) + { + Count = count; + Array = data; + } + TArrayView(const TArrayView &other) + { + Count = other.Count; + Array = other.Array; + } + TArrayView &operator= (const TArrayView &other) + { + Count = other.Count; + Array = other.Array; + return *this; + } + // Check equality of two arrays + bool operator==(const TArrayView &other) const + { + if (Count != other.Count) + { + return false; + } + for (unsigned int i = 0; i < Count; ++i) + { + if (Array[i] != other.Array[i]) + { + return false; + } + } + return true; + } + // Return a reference to an element + T &operator[] (size_t index) const + { + return Array[index]; + } + // Returns a reference to the last element + T &Last() const + { + return Array[Count - 1]; + } + + // returns address of first element + T *Data() const + { + return &Array[0]; + } + + unsigned Size() const + { + return Count; + } + + unsigned int Find(const T& item) const + { + unsigned int i; + for (i = 0; i < Count; ++i) + { + if (Array[i] == item) + break; + } + return i; + } + + void Set(T *data, unsigned count) + { + Array = data; + Count = count; + } + + void Clear() + { + Count = 0; + Array = nullptr; + } +private: + T *Array; + unsigned int Count; +}; + diff --git a/unused/gl_sections.cpp b/unused/gl_sections.cpp deleted file mode 100644 index 08a68be8e..000000000 --- a/unused/gl_sections.cpp +++ /dev/null @@ -1,845 +0,0 @@ -/* -** gl_sections.cpp -** Splits sectors into continuous separate parts -** -**--------------------------------------------------------------------------- -** Copyright 2008 Christoph Oelckers -** All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions -** are met: -** -** 1. Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** 2. Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in the -** documentation and/or other materials provided with the distribution. -** 3. The name of the author may not be used to endorse or promote products -** derived from this software without specific prior written permission. -** 4. When not used as part of GZDoom or a GZDoom derivative, this code will be -** covered by the terms of the GNU Lesser General Public License as published -** by the Free Software Foundation; either version 2.1 of the License, or (at -** your option) any later version. -** 5. Full disclosure of the entire project's source code, except for third -** party libraries is mandatory. (NOTE: This clause is non-negotiable!) -** -** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**--------------------------------------------------------------------------- -** -*/ - -#include "gl/system/gl_system.h" -#include -#include "i_system.h" -#include "p_local.h" -#include "c_dispatch.h" -#include "gl/data/gl_sections.h" - -typedef void (CALLBACK *tessFunc)(); - -TArray SectionLines; -TArray SectionLoops; -TArray Sections; -TArray SectionForSubsector; - -CVAR (Bool, dumpsections, false, 0) - -#define ISDONE(no, p) (p[(no)>>3] & (1 << ((no)&7))) -#define SETDONE(no, p) p[(no)>>3] |= (1 << ((no)&7)) - -inline vertex_t *V1(side_t *s) -{ - line_t *ln = s->linedef; - return s == ln->sidedef[0]? ln->v1: ln->v2; -} - -inline vertex_t *V2(side_t *s) -{ - line_t *ln = s->linedef; - return s == ln->sidedef[0]? ln->v2: ln->v1; -} - -//========================================================================== -// -// -// -//========================================================================== - -class FSectionCreator -{ - static FSectionCreator *creator; - - uint8_t *processed_segs; - uint8_t *processed_subsectors; - int *section_for_segs; - - vertex_t *v1_l1, *v2_l1; - - FGLSectionLoop *loop; - FGLSection *section; // current working section - -public: - //========================================================================== - // - // - // - //========================================================================== - - FSectionCreator() - { - processed_segs = new uint8_t[(numsegs+7)/8]; - processed_subsectors = new uint8_t[(numsubsectors+7)/8]; - - memset(processed_segs, 0, (numsegs+7)/8); - memset(processed_subsectors, 0, (numsubsectors+7)/8); - - section_for_segs = new int[numsegs]; - memset(section_for_segs, -1, numsegs * sizeof(int)); - } - - //========================================================================== - // - // - // - //========================================================================== - - ~FSectionCreator() - { - delete [] processed_segs; - delete [] processed_subsectors; - delete [] section_for_segs; - } - - //========================================================================== - // - // - // - //========================================================================== - - void NewLoop() - { - section->numloops++; - loop = &SectionLoops[SectionLoops.Reserve(1)]; - loop->startline = SectionLines.Size(); - loop->numlines = 0 ; - } - - void NewSection(sector_t *sec) - { - section = &Sections[Sections.Reserve(1)]; - section->sector = sec; - section->subsectors.Clear(); - section->numloops = 0; - section->startloop = SectionLoops.Size(); - section->validcount = -1; - NewLoop(); - } - - void FinalizeSection() - { - } - - //========================================================================== - // - // - // - //========================================================================== - - bool AddSeg(seg_t *seg) - { - FGLSectionLine &line = SectionLines[SectionLines.Reserve(1)]; - - - bool firstline = loop->numlines == 0; - - if (ISDONE(seg-segs, processed_segs)) - { - // should never happen! - DPrintf("Tried to add seg %d to Sections twice. Cannot create Sections.\n", seg-segs); - return false; - } - - SETDONE(seg-segs, processed_segs); - section_for_segs[seg-segs] = Sections.Size()-1; - - line.start = seg->v1; - line.end = seg->v2; - line.sidedef = seg->sidedef; - line.linedef = seg->linedef; - line.refseg = seg; - line.polysub = NULL; - line.otherside = -1; - - if (loop->numlines == 0) - { - v1_l1 = seg->v1; - v2_l1 = seg->v2; - } - loop->numlines++; - return true; - } - - //========================================================================== - // - // Utility stuff - // - //========================================================================== - - sector_t *FrontRenderSector(seg_t *seg) - { - return seg->Subsector->render_sector; - } - - sector_t *BackRenderSector(seg_t *seg) - { - if (seg->PartnerSeg == NULL) return NULL; - return seg->PartnerSeg->Subsector->render_sector; - } - - bool IntraSectorSeg(seg_t *seg) - { - return FrontRenderSector(seg) == BackRenderSector(seg); - } - - - //========================================================================== - // - // returns the seg whose partner seg determines where this - // section continues - // - //========================================================================== - bool AddSubSector(subsector_t *subsec, vertex_t *startpt, seg_t **pNextSeg) - { - unsigned i = 0; - if (startpt != NULL) - { - // find the seg in this subsector that starts at the given vertex - for(i = 0; i < subsec->numlines; i++) - { - if (subsec->firstline[i].v1 == startpt) break; - } - if (i == subsec->numlines) - { - DPrintf("Vertex not found in subsector %d. Cannot create Sections.\n", subsec-subsectors); - return false; // Nodes are bad - } - } - else - { - // Find the first unprocessed non-miniseg - for(i = 0; i < subsec->numlines; i++) - { - seg_t *seg = subsec->firstline + i; - - if (seg->sidedef == NULL) continue; - if (IntraSectorSeg(seg)) continue; - if (ISDONE(seg-segs, processed_segs)) continue; - break; - } - if (i == subsec->numlines) - { - DPrintf("Unable to find a start seg. Cannot create Sections.\n"); - return false; // Nodes are bad - } - - startpt = subsec->firstline[i].v1; - } - - seg_t *thisseg = subsec->firstline + i; - if (IntraSectorSeg(thisseg)) - { - SETDONE(thisseg-segs, processed_segs); - // continue with the loop in the adjoining subsector - *pNextSeg = thisseg; - return true; - } - - while(1) - { - if (loop->numlines > 0 && thisseg->v1 == v1_l1 && thisseg->v2 == v2_l1) - { - // This loop is complete - *pNextSeg = NULL; - return true; - } - - if (!AddSeg(thisseg)) return NULL; - - i = (i+1) % subsec->numlines; - seg_t *nextseg = subsec->firstline + i; - - if (thisseg->v2 != nextseg->v1) - { - DPrintf("Segs in subsector %d are not continuous. Cannot create Sections.\n", subsec-subsectors); - return false; // Nodes are bad - } - - if (IntraSectorSeg(nextseg)) - { - SETDONE(nextseg-segs, processed_segs); - // continue with the loop in the adjoining subsector - *pNextSeg = nextseg; - return true; - } - thisseg = nextseg; - } - } - - //============================================================================= - // - // - // - //============================================================================= - - bool FindNextSeg(seg_t **pSeg) - { - // find an unprocessed non-miniseg or a miniseg with an unprocessed - // partner subsector that belongs to the same rendersector - for (unsigned i = 0; i < section->subsectors.Size(); i++) - { - for(unsigned j = 0; j < section->subsectors[i]->numlines; j++) - { - seg_t *seg = section->subsectors[i]->firstline + j; - bool intra = IntraSectorSeg(seg); - - if (!intra && !ISDONE(seg-segs, processed_segs)) - { - *pSeg = seg; - return true; - } - else if (intra && - !ISDONE(seg->PartnerSeg->Subsector-subsectors, processed_subsectors)) - { - *pSeg = seg->PartnerSeg; - return true; - } - } - } - *pSeg = NULL; - return true; - } - - //============================================================================= - // - // all segs and subsectors must be grouped into Sections - // - //============================================================================= - bool CheckSections() - { - bool res = true; - for (int i = 0; i < numsegs; i++) - { - if (segs[i].sidedef != NULL && !ISDONE(i, processed_segs) && !IntraSectorSeg(&segs[i])) - { - Printf("Seg %d (Linedef %d) not processed during section creation\n", i, segs[i].linedef-lines); - res = false; - } - } - for (int i = 0; i < numsubsectors; i++) - { - if (!ISDONE(i, processed_subsectors)) - { - Printf("Subsector %d (Sector %d) not processed during section creation\n", i, subsectors[i].sector-sectors); - res = false; - } - } - return res; - } - - //============================================================================= - // - // - // - //============================================================================= - void DeleteLine(int i) - { - SectionLines.Delete(i); - for(int i = SectionLoops.Size() - 1; i >= 0; i--) - { - FGLSectionLoop *loop = &SectionLoops[i]; - if (loop->startline > i) loop->startline--; - } - } - - //============================================================================= - // - // - // - //============================================================================= - void MergeLines(FGLSectionLoop *loop) - { - int i; - int deleted = 0; - FGLSectionLine *ln1; - FGLSectionLine *ln2; - // Merge identical lines in the list - for(i = loop->numlines - 1; i > 0; i--) - { - ln1 = loop->GetLine(i); - ln2 = loop->GetLine(i-1); - - if (ln1->sidedef == ln2->sidedef && ln1->otherside == ln2->otherside) - { - // identical references. These 2 lines can be merged. - ln2->end = ln1->end; - SectionLines.Delete(loop->startline + i); - loop->numlines--; - deleted++; - } - } - - // If we started in the middle of a sidedef the first and last lines - // may reference the same sidedef. check that, too. - - int loopstart = 0; - - ln1 = loop->GetLine(0); - for(i = loop->numlines - 1; i > 0; i--) - { - ln2 = loop->GetLine(i); - if (ln1->sidedef != ln2->sidedef || ln1->otherside != ln2->otherside) - break; - } - if (i < loop->numlines-1) - { - i++; - ln2 = loop->GetLine(i); - ln1->start = ln2->start; - SectionLines.Delete(loop->startline + i, loop->numlines - i); - deleted += loop->numlines - i; - loop->numlines = i; - } - - // Adjust all following loops - for(unsigned ii = unsigned(loop - &SectionLoops[0]) + 1; ii < SectionLoops.Size(); ii++) - { - SectionLoops[ii].startline -= deleted; - } - } - - //============================================================================= - // - // - // - //============================================================================= - void SetReferences() - { - for(unsigned i = 0; i < SectionLines.Size(); i++) - { - FGLSectionLine *ln = &SectionLines[i]; - seg_t *seg = ln->refseg; - - if (seg != NULL) - { - seg_t *partner = seg->PartnerSeg; - - if (seg->PartnerSeg == NULL) - { - ln->otherside = -1; - } - else - { - ln->otherside = section_for_segs[partner-segs]; - } - } - else - { - ln->otherside = -1; - } - } - - for(unsigned i = 0; i < SectionLoops.Size(); i++) - { - MergeLines(&SectionLoops[i]); - } - } - - //============================================================================= - // - // cbTessBegin - // - // called when the tesselation of a new loop starts - // - //============================================================================= - - static void CALLBACK cbTessBegin(GLenum type, void *section) - { - FGLSection *sect = (FGLSection*)section; - sect->primitives.Push(type); - sect->primitives.Push(sect->vertices.Size()); - } - - //============================================================================= - // - // cbTessError - // - // called when the tesselation failed - // - //============================================================================= - - static void CALLBACK cbTessError(GLenum error, void *section) - { - } - - //============================================================================= - // - // cbTessCombine - // - // called when the two or more vertexes are on the same coordinate - // - //============================================================================= - - static void CALLBACK cbTessCombine( GLdouble coords[3], void *vert[4], GLfloat w[4], void **dataOut ) - { - *dataOut = vert[0]; - } - - //============================================================================= - // - // cbTessVertex - // - // called when a vertex is found - // - //============================================================================= - - static void CALLBACK cbTessVertex( void *vert, void *section ) - { - FGLSection *sect = (FGLSection*)section; - sect->vertices.Push(int(intptr_t(vert))); - } - - //============================================================================= - // - // cbTessEnd - // - // called when the tesselation of a the current loop ends - // - //============================================================================= - - static void CALLBACK cbTessEnd(void *section) - { - } - - //============================================================================= - // - // - // - //============================================================================= - void tesselateSections() - { - // init tesselator - GLUtesselator *tess = gluNewTess(); - if (!tess) - { - return; - } - // set callbacks - gluTessCallback(tess, GLU_TESS_BEGIN_DATA, (tessFunc)cbTessBegin); - gluTessCallback(tess, GLU_TESS_VERTEX_DATA, (tessFunc)cbTessVertex); - gluTessCallback(tess, GLU_TESS_ERROR_DATA, (tessFunc)cbTessError); - gluTessCallback(tess, GLU_TESS_COMBINE, (tessFunc)cbTessCombine); - gluTessCallback(tess, GLU_TESS_END_DATA, (tessFunc)cbTessEnd); - - for(unsigned int i=0;inumloops; j++) - { - gluTessBeginContour(tess); - FGLSectionLoop *loop = sect->GetLoop(j); - for(int k=0; knumlines; k++) - { - FGLSectionLine *line = loop->GetLine(k); - vertex_t *vert = line->start; - GLdouble v[3] = { - -(double)vert->x/(double)FRACUNIT, // negate to get proper winding - 0.0, - (double)vert->y/(double)FRACUNIT - }; - gluTessVertex(tess, v, (void*)(vert - vertexes)); - } - gluTessEndContour(tess); - } - gluTessEndPolygon(tess); - sect->vertices.Push(-1337); - sect->vertices.ShrinkToFit(); - } - gluDeleteTess(tess); - } - - - //============================================================================= - // - // First mark all subsectors that have no outside boundaries as processed - // No line in such a subsector will ever be part of a section's border - // - //============================================================================= - - void MarkInternalSubsectors() - { - for(int i=0; i < numsubsectors; i++) - { - subsector_t *sub = &subsectors[i]; - int j; - - for(j=0; j < sub->numlines; j++) - { - seg_t *seg = sub->firstline + j; - if (!IntraSectorSeg(seg)) break; - } - if (j==sub->numlines) - { - // All lines are intra-sector so mark this as processed - SETDONE(i, processed_subsectors); - for(j=0; j < sub->numlines; j++) - { - seg_t *seg = sub->firstline + j; - SETDONE((sub->firstline-segs)+j, processed_segs); - if (seg->PartnerSeg != NULL) - { - SETDONE(int(seg->PartnerSeg - segs), processed_segs); - } - } - } - } - } - - //============================================================================= - // - // - // - //============================================================================= - bool CreateSections() - { - int pick = 0; - - MarkInternalSubsectors(); - while (pick < numsubsectors) - { - if (ISDONE(pick, processed_subsectors)) - { - pick++; - continue; - } - - - subsector_t *subsector = &subsectors[pick]; - - seg_t *workseg = NULL; - vertex_t *startpt = NULL; - - NewSection(subsector->render_sector); - while (1) - { - if (!ISDONE(subsector-subsectors, processed_subsectors)) - { - SETDONE(subsector-subsectors, processed_subsectors); - section->subsectors.Push(subsector); - SectionForSubsector[subsector - subsectors] = int(section - &Sections[0]); - } - - bool result = AddSubSector(subsector, startpt, &workseg); - - if (!result) - { - return false; // couldn't create Sections - } - else if (workseg != NULL) - { - // crossing into another subsector - seg_t *partner = workseg->PartnerSeg; - if (workseg->v2 != partner->v1) - { - DPrintf("Inconsistent subsector references in seg %d. Cannot create Sections.\n", workseg-segs); - return false; - } - subsector = partner->Subsector; - startpt = workseg->v1; - } - else - { - // loop complete. Check adjoining subsectors for other loops to - // be added to this section - if (!FindNextSeg(&workseg)) - { - return false; - } - else if (workseg == NULL) - { - // No more subsectors found. This section is complete! - FinalizeSection(); - break; - } - else - { - subsector = workseg->Subsector; - // If this is a regular seg, start there, otherwise start - // at the subsector's first seg - startpt = workseg->sidedef == NULL? NULL : workseg->v1; - - NewLoop(); - } - } - } - } - - if (!CheckSections()) return false; - SetReferences(); - - Sections.ShrinkToFit(); - SectionLoops.ShrinkToFit(); - SectionLines.ShrinkToFit(); - - tesselateSections(); - - return true; - } -}; - -FSectionCreator *FSectionCreator::creator; - - -//============================================================================= -// -// -// -//============================================================================= - -void DumpSection(int no, FGLSection *sect) -{ - Printf(PRINT_LOG, "Section %d, sector %d\n{\n", no, sect->sector->sectornum); - - for(int i = 0; i < sect->numloops; i++) - { - Printf(PRINT_LOG, "\tLoop %d\n\t{\n", i); - - FGLSectionLoop *loop = sect->GetLoop(i); - - for(int i = 0; i < loop->numlines; i++) - { - FGLSectionLine *ln = loop->GetLine(i); - if (ln->sidedef != NULL) - { - vertex_t *v1 = V1(ln->sidedef); - vertex_t *v2 = V2(ln->sidedef); - double dx = FIXED2DBL(v2->x-v1->x); - double dy = FIXED2DBL(v2->y-v1->y); - double dx1 = FIXED2DBL(ln->start->x-v1->x); - double dy1 = FIXED2DBL(ln->start->y-v1->y); - double dx2 = FIXED2DBL(ln->end->x-v1->x); - double dy2 = FIXED2DBL(ln->end->y-v1->y); - double d = sqrt(dx*dx+dy*dy); - double d1 = sqrt(dx1*dx1+dy1*dy1); - double d2 = sqrt(dx2*dx2+dy2*dy2); - - Printf(PRINT_LOG, "\t\tLinedef %d, %s: Start (%1.2f, %1.2f), End (%1.2f, %1.2f)", - ln->linedef - lines, ln->sidedef == ln->linedef->sidedef[0]? "front":"back", - ln->start->x/65536.f, ln->start->y/65536.f, - ln->end->x/65536.f, ln->end->y/65536.f); - - if (ln->otherside != -1) - { - Printf (PRINT_LOG, ", other side = %d", ln->otherside); - } - if (d1 > 0.005 || d2 < 0.995) - { - Printf(PRINT_LOG, ", Range = %1.3f, %1.3f", d1/d, d2/d); - } - } - else - { - Printf(PRINT_LOG, "\t\tMiniseg: Start (%1.3f, %1.3f), End (%1.3f, %1.3f)\n", - ln->start->x/65536.f, ln->start->y/65536.f, ln->end->x/65536.f, ln->end->y/65536.f); - - if (ln->otherside != -1) - { - Printf (PRINT_LOG, ", other side = %d", ln->otherside); - } - } - Printf(PRINT_LOG, "\n"); - } - Printf(PRINT_LOG, "\t}\n"); - } - int prim = 1; - for(unsigned i = 0; i < sect->vertices.Size(); i++) - { - int v = sect->vertices[i]; - if (v < 0) - { - if (i > 0) - { - Printf(PRINT_LOG, "\t}\n"); - } - switch (v) - { - case -GL_TRIANGLE_FAN: - Printf(PRINT_LOG, "\t%d: Triangle fan\n\t{\n", prim); - break; - - case -GL_TRIANGLE_STRIP: - Printf(PRINT_LOG, "\t%d: Triangle strip\n\t{\n", prim); - break; - - case -GL_TRIANGLES: - Printf(PRINT_LOG, "\t%d: Triangles\n\t{\n", prim); - break; - - default: - break; - } - prim++; - } - else - { - Printf(PRINT_LOG, "\t\tVertex %d: (%1.2f, %1.2f)\n", - v, vertexes[v].x/65536.f, vertexes[v].y/65536.f); - } - } - Printf(PRINT_LOG, "}\n\n"); -} - -//============================================================================= -// -// -// -//============================================================================= - -void DumpSections() -{ - for(unsigned i = 0; i < Sections.Size(); i++) - { - DumpSection(i, &Sections[i]); - } -} - -//============================================================================= -// -// -// -//============================================================================= - -void gl_CreateSections() -{ - SectionLines.Clear(); - SectionLoops.Clear(); - Sections.Clear(); - SectionForSubsector.Resize(numsubsectors); - memset(&SectionForSubsector[0], -1, numsubsectors * sizeof(SectionForSubsector[0])); - FSectionCreator creat; - creat.CreateSections(); - if (dumpsections) DumpSections(); -} - diff --git a/unused/gl_sections.h b/unused/gl_sections.h deleted file mode 100644 index 1974fab46..000000000 --- a/unused/gl_sections.h +++ /dev/null @@ -1,57 +0,0 @@ - -#ifndef __GL_SECTIONS_H -#define __GL_SECTIONS_H - -#include "tarray.h" -#include "r_defs.h" - -struct FGLSectionLine -{ - vertex_t *start; - vertex_t *end; - side_t *sidedef; - line_t *linedef; - seg_t *refseg; // we need to reference at least one seg for each line. - subsector_t *polysub; // If this is part of a polyobject we need a reference to the containing subsector - int otherside; -}; - -struct FGLSectionLoop -{ - int startline; - int numlines; - - FGLSectionLine *GetLine(int no); -}; - -struct FGLSection -{ - sector_t *sector; - TArray subsectors; - TArray primitives; // each primitive has 2 entries: Primitive type and vertex count - TArray vertices; - int startloop; - int numloops; - int validcount; - - FGLSectionLoop *GetLoop(int no); -}; - -extern TArray SectionLines; -extern TArray SectionLoops; -extern TArray Sections; -extern TArray SectionForSubsector; - -inline FGLSectionLine *FGLSectionLoop::GetLine(int no) -{ - return &SectionLines[startline + no]; -} - -inline FGLSectionLoop *FGLSection::GetLoop(int no) -{ - return &SectionLoops[startloop + no]; -} - -void gl_CreateSections(); - -#endif \ No newline at end of file From 0deb388a757f6716d703fb400ce0b15f3cfcdabd Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Sun, 4 Nov 2018 22:19:11 +0100 Subject: [PATCH 02/16] - automatically create sections and store them with the level data. - added subsector indexing to sections. This is needed for finding a section from a point. --- src/actor.h | 1 + src/g_levellocals.h | 3 +++ src/hwrenderer/data/hw_sections.cpp | 32 ++++++++++++++++++++--------- src/hwrenderer/data/hw_sections.h | 14 +++++++++++++ src/p_maputl.cpp | 1 + src/p_setup.cpp | 1 + src/r_data/renderinfo.cpp | 2 ++ 7 files changed, 44 insertions(+), 10 deletions(-) diff --git a/src/actor.h b/src/actor.h index 043da9b7c..d87c51e98 100644 --- a/src/actor.h +++ b/src/actor.h @@ -1083,6 +1083,7 @@ public: FBlockNode *BlockNode; // links in blocks (if needed) struct sector_t *Sector; subsector_t * subsector; + FSection * section; double floorz, ceilingz; // closest together of contacted secs double dropoffz; // killough 11/98: the lowest floor over all contacted Sectors. diff --git a/src/g_levellocals.h b/src/g_levellocals.h index dfdb6dbef..6a42c12c5 100644 --- a/src/g_levellocals.h +++ b/src/g_levellocals.h @@ -42,6 +42,7 @@ #include "p_blockmap.h" #include "p_local.h" #include "p_destructible.h" +#include "hwrenderer/data/hw_sections.h" struct FLevelLocals { @@ -94,6 +95,8 @@ struct FLevelLocals TArray linkedPortals; // only the linked portals, this is used to speed up looking for them in P_CollectConnectedGroups. TArray portalGroups; TArray linePortalSpans; + FSectionContainer sections; + int NumMapSections; TArray Zones; diff --git a/src/hwrenderer/data/hw_sections.cpp b/src/hwrenderer/data/hw_sections.cpp index 9364b9712..e56736191 100644 --- a/src/hwrenderer/data/hw_sections.cpp +++ b/src/hwrenderer/data/hw_sections.cpp @@ -88,6 +88,7 @@ struct Group TArray groupedSections; TMap sideMap; TArray segments; + TArray subsectors; }; class FSectionCreator @@ -531,12 +532,14 @@ public: { const double MAX_GROUP_DIST = 256; TArray build; + TArray subsectorcopy; if (workingSet.Size() == 1) { groupForSection[workingSet[0].index] = groups.Size(); Group g; g.groupedSections = std::move(workingSet); + g.subsectors = std::move(rawsections[workingSet[0].index]); groups.Push(std::move(g)); return; } @@ -546,8 +549,10 @@ public: build.Clear(); build.Push(workingSet[0]); groupForSection[workingSet[0].index] = groups.Size(); + subsectorcopy = std::move(rawsections[workingSet[0].index]); workingSet.Delete(0); + // Don't use iterators here. These arrays are modified inside. for (unsigned j = 0; j < build.Size(); j++) { @@ -560,6 +565,7 @@ public: { build.Push(workingSet[i]); groupForSection[workingSet[i].index] = groups.Size(); + subsectorcopy.Append(rawsections[workingSet[i].index]); workingSet.Delete(i); i--; continue; @@ -570,6 +576,7 @@ public: { build.Push(workingSet[i]); groupForSection[workingSet[i].index] = groups.Size(); + subsectorcopy.Append(rawsections[workingSet[i].index]); workingSet.Delete(i); i--; continue; @@ -578,6 +585,7 @@ public: } Group g; g.groupedSections = std::move(build); + g.subsectors = std::move(subsectorcopy); groups.Push(std::move(g)); } } @@ -615,6 +623,7 @@ public: output.allIndices.Resize(level.subsectors.Size() + level.sides.Size()); output.sectionForSubsectorPtr = &output.allIndices[0]; output.sectionForSidedefPtr = &output.allIndices[level.subsectors.Size()]; + memset(output.sectionForSubsectorPtr, -1, sizeof(int) * level.subsectors.Size()); unsigned numsegments = 0; unsigned numsides = 0; @@ -642,9 +651,11 @@ public: } output.allLines.Resize(numsegments); output.allSides.Resize(numsides); + output.allSubsectors.Resize(level.subsectors.Size()); numsegments = 0; numsides = 0; + unsigned numsubsectors = 0; // Now piece it all together unsigned curgroup = 0; @@ -658,6 +669,7 @@ public: dest.validcount = 0; dest.segments.Set(&output.allLines[numsegments], group.segments.Size()); dest.sides.Set(&output.allSides[numsides], group.sideMap.CountUsed()); + dest.subsectors.Set(&output.allSubsectors[numsubsectors]); dest.bounds = {1e32, 1e32, -1e32, -1e32}; numsegments += group.segments.Size(); @@ -677,7 +689,14 @@ public: while (it.NextPair(pair)) { output.allSides[numsides++] = &level.sides[pair->Key]; + output.sectionForSidedefPtr[pair->Key] = curgroup; } + memcpy(&output.allSubsectors[numsubsectors], &group.subsectors[0], group.subsectors.Size() * sizeof(subsector_t*)); + for (auto ssi : group.subsectors) + { + output.sectionForSubsectorPtr[ssi] = curgroup; + } + numsubsectors += group.subsectors.Size(); curgroup++; } } @@ -739,12 +758,8 @@ void PrintSections(FSectionContainer &container) // //============================================================================= -void MakeSections() +void CreateSections(FSectionContainer &container) { - FSectionContainer container; - cycle_t timer; - timer.Reset(); - timer.Clock(); FSectionCreator creat; creat.GroupSubsectors(); creat.CompileSections(); @@ -753,12 +768,9 @@ void MakeSections() creat.FindOuterLoops(); creat.GroupSections(); creat.ConstructOutput(container); - timer.Unclock(); - PrintSections(container); - Printf("Time = %2.3f ms\n", timer.TimeMS()); } -CCMD(makesections) +CCMD(printsections) { - MakeSections(); + PrintSections(level.sections); } \ No newline at end of file diff --git a/src/hwrenderer/data/hw_sections.h b/src/hwrenderer/data/hw_sections.h index 1cc6f2efa..6edda1143 100644 --- a/src/hwrenderer/data/hw_sections.h +++ b/src/hwrenderer/data/hw_sections.h @@ -2,9 +2,19 @@ #ifndef __GL_SECTIONS_H #define __GL_SECTIONS_H +#include #include "tarray.h" #include "r_defs.h" +// Undefine Windows garbage. +#ifdef min +#undef min +#endif + +#ifdef max +#undef max +#endif + //========================================================================== // // @@ -71,6 +81,7 @@ struct FSection // tbd: Do we need a list of subsectors here? Ideally the subsectors should not be used anywhere anymore except for finding out where a location is. TArrayView segments; TArrayView sides; // contains all sidedefs, including the internal ones that do not make up the outer shape. (this list is not exclusive. A sidedef can be in multiple sections!) + TArrayView subsectors; // contains all sidedefs, including the internal ones that do not make up the outer shape. (this list is not exclusive. A sidedef can be in multiple sections!) sector_t *sector; FLightNode *lighthead; // Light nodes (blended and additive) BoundingRect bounds; @@ -86,6 +97,7 @@ public: TArray allSections; //TArray allVertices; TArray allSides; + TArray allSubsectors; TArray allIndices; int *sectionForSubsectorPtr; // stored inside allIndices @@ -123,4 +135,6 @@ public: }; +void CreateSections(FSectionContainer &container); + #endif \ No newline at end of file diff --git a/src/p_maputl.cpp b/src/p_maputl.cpp index c94d80073..19c9496d3 100644 --- a/src/p_maputl.cpp +++ b/src/p_maputl.cpp @@ -470,6 +470,7 @@ void AActor::LinkToWorld(FLinkContext *ctx, bool spawningmapthing, sector_t *sec Sector = sector; subsector = R_PointInSubsector(Pos()); // this is from the rendering nodes, not the gameplay nodes! + section = level.sections.SectionForSubsector(subsector->Index()); if (!(flags & MF_NOSECTOR)) { diff --git a/src/p_setup.cpp b/src/p_setup.cpp index d3ff4c499..a204144ef 100644 --- a/src/p_setup.cpp +++ b/src/p_setup.cpp @@ -3559,6 +3559,7 @@ void P_FreeLevelData () FBehavior::StaticUnloadModules (); + level.sections.Clear(); level.segs.Clear(); level.sectors.Clear(); level.lines.Clear(); diff --git a/src/r_data/renderinfo.cpp b/src/r_data/renderinfo.cpp index bf59ec0c0..f50c32d51 100644 --- a/src/r_data/renderinfo.cpp +++ b/src/r_data/renderinfo.cpp @@ -532,6 +532,8 @@ static void PrepareSegs() void InitRenderInfo() { + CreateSections(level.sections); + PrepareSegs(); PrepareSectorData(); InitVertexData(); From d7db00d92e0bc400eb6e60e244b9d60a118fadf7 Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Mon, 5 Nov 2018 01:01:48 +0100 Subject: [PATCH 03/16] - sector rendering refactoring for sections - work in progress. --- src/actor.h | 1 + src/hwrenderer/data/hw_sections.cpp | 123 +++++++++++++++++++++++- src/hwrenderer/data/hw_sections.h | 51 +++++++++- src/hwrenderer/scene/hw_bsp.cpp | 5 +- src/hwrenderer/scene/hw_drawinfo.cpp | 4 +- src/hwrenderer/scene/hw_drawinfo.h | 2 +- src/hwrenderer/scene/hw_drawstructs.h | 2 + src/hwrenderer/scene/hw_flats.cpp | 6 +- src/hwrenderer/scene/hw_renderhacks.cpp | 3 +- 9 files changed, 185 insertions(+), 12 deletions(-) diff --git a/src/actor.h b/src/actor.h index d87c51e98..697410711 100644 --- a/src/actor.h +++ b/src/actor.h @@ -53,6 +53,7 @@ struct FBlockNode; struct FPortalGroupArray; struct visstyle_t; class FLightDefaults; +struct FSection; // // NOTES: AActor // diff --git a/src/hwrenderer/data/hw_sections.cpp b/src/hwrenderer/data/hw_sections.cpp index e56736191..2c698386c 100644 --- a/src/hwrenderer/data/hw_sections.cpp +++ b/src/hwrenderer/data/hw_sections.cpp @@ -34,6 +34,7 @@ #include "p_setup.h" #include "c_dispatch.h" #include "memarena.h" +#include "flatvertices.h" using DoublePoint = std::pair; @@ -611,6 +612,114 @@ public: return false; } + + //============================================================================= + // + // + // + //============================================================================= + + // Temporary data for creating an indexed buffer + struct VertexIndexGenerationInfo + { + TArray vertices; + TMap vertexmap; + + TArray indices; + + uint32_t AddVertex(vertex_t *vert) + { + auto check = vertexmap.CheckKey(vert); + if (check != nullptr) return *check; + auto index = vertices.Push(vert); + vertexmap[vert] = index; + return index; + } + + uint32_t GetIndex(vertex_t *vert) + { + auto check = vertexmap.CheckKey(vert); + if (check != nullptr) return *check; + return ~0u; + } + + uint32_t AddIndexForVertex(vertex_t *vert) + { + return indices.Push(GetIndex(vert)); + } + + uint32_t AddIndex(uint32_t indx) + { + return indices.Push(indx); + } + }; + + //============================================================================= + // + // + // + //============================================================================= + + void CreateIndexedSubsectorVertices(subsector_t *sub, VertexIndexGenerationInfo &gen) + { + if (sub->numlines < 3) return; + + uint32_t startindex = gen.indices.Size(); + + if ((sub->flags & SSECF_HOLE) && sub->numlines > 3) + { + // Hole filling "subsectors" are not necessarily convex so they require real triangulation. + // These things are extremely rare so performance is secondary here. + + using Point = std::pair; + std::vector> polygon; + std::vector *curPoly; + + for (unsigned i = 0; i < sub->numlines; i++) + { + polygon.resize(1); + curPoly = &polygon.back(); + curPoly->push_back({ sub->firstline[i].v1->fX(), sub->firstline[i].v1->fY() }); + } + auto indices = mapbox::earcut(polygon); + for (auto vti : indices) + { + gen.AddIndexForVertex(sub->firstline[vti].v1); + } + } + else + { + int firstndx = gen.GetIndex(sub->firstline[0].v1); + int secondndx = gen.GetIndex(sub->firstline[1].v1); + for (unsigned int k = 2; k < sub->numlines; k++) + { + gen.AddIndex(firstndx); + gen.AddIndex(secondndx); + auto ndx = gen.GetIndex(sub->firstline[k].v1); + gen.AddIndex(ndx); + secondndx = ndx; + } + } + } + + + void CreateVerticesForSection(FSectionContainer &output, FSection §ion) + { + VertexIndexGenerationInfo gen; + + for (auto sub : section.subsectors) + { + CreateIndexedSubsectorVertices(sub, gen); + } + section.vertexindex = output.allVertices.Size(); + section.vertexcount = gen.vertices.Size(); + section.indexindex = output.allVertexIndices.Size(); + section.indexcount = gen.indices.Size(); + output.allVertices.Append(gen.vertices); + output.allVertexIndices.Append(gen.indices); + } + + //============================================================================= // // @@ -620,10 +729,14 @@ public: void ConstructOutput(FSectionContainer &output) { output.allSections.Resize(groups.Size()); - output.allIndices.Resize(level.subsectors.Size() + level.sides.Size()); + output.allIndices.Resize(level.subsectors.Size() + level.sides.Size() + 2*level.sectors.Size()); output.sectionForSubsectorPtr = &output.allIndices[0]; output.sectionForSidedefPtr = &output.allIndices[level.subsectors.Size()]; + output.firstSectionForSectorPtr = &output.allIndices[level.subsectors.Size() + level.sides.Size()]; + output.numberOfSectionForSectorPtr = &output.allIndices[level.subsectors.Size() + level.sides.Size() + level.sectors.Size()]; memset(output.sectionForSubsectorPtr, -1, sizeof(int) * level.subsectors.Size()); + memset(output.firstSectionForSectorPtr, -1, sizeof(int) * level.sectors.Size()); + memset(output.numberOfSectionForSectorPtr, 0, sizeof(int) * level.sectors.Size()); unsigned numsegments = 0; unsigned numsides = 0; @@ -669,10 +782,15 @@ public: dest.validcount = 0; dest.segments.Set(&output.allLines[numsegments], group.segments.Size()); dest.sides.Set(&output.allSides[numsides], group.sideMap.CountUsed()); - dest.subsectors.Set(&output.allSubsectors[numsubsectors]); + dest.subsectors.Set(&output.allSubsectors[numsubsectors], group.subsectors.Size()); + dest.vertexindex = -1; + dest.vertexcount = 0; dest.bounds = {1e32, 1e32, -1e32, -1e32}; numsegments += group.segments.Size(); + if (output.firstSectionForSectorPtr[dest.sector->Index()] == -1) + output.firstSectionForSectorPtr[dest.sector->Index()] = curgroup; + for (auto &segment : group.segments) { // Use the indices calculated above to store these elements. @@ -697,6 +815,7 @@ public: output.sectionForSubsectorPtr[ssi] = curgroup; } numsubsectors += group.subsectors.Size(); + CreateVerticesForSection(output, dest); curgroup++; } } diff --git a/src/hwrenderer/data/hw_sections.h b/src/hwrenderer/data/hw_sections.h index 6edda1143..7e1e94b6c 100644 --- a/src/hwrenderer/data/hw_sections.h +++ b/src/hwrenderer/data/hw_sections.h @@ -80,11 +80,15 @@ struct FSection { // tbd: Do we need a list of subsectors here? Ideally the subsectors should not be used anywhere anymore except for finding out where a location is. TArrayView segments; - TArrayView sides; // contains all sidedefs, including the internal ones that do not make up the outer shape. (this list is not exclusive. A sidedef can be in multiple sections!) - TArrayView subsectors; // contains all sidedefs, including the internal ones that do not make up the outer shape. (this list is not exclusive. A sidedef can be in multiple sections!) + TArrayView sides; // contains all sidedefs, including the internal ones that do not make up the outer shape. + TArrayView subsectors; // contains all subsectors making up this section sector_t *sector; - FLightNode *lighthead; // Light nodes (blended and additive) + FLightNode *lighthead; // Light nodes (blended and additive) BoundingRect bounds; + int vertexindex; + int vertexcount; // index and length of this section's entry in the allVertices array + int indexindex; + int indexcount; // index and length of this section's entry in the allVertices array int validcount; short mapsection; char hacked; // 1: is part of a render hack @@ -95,13 +99,16 @@ class FSectionContainer public: TArray allLines; TArray allSections; - //TArray allVertices; + TArray allVertices; + TArray allVertexIndices; TArray allSides; TArray allSubsectors; TArray allIndices; int *sectionForSubsectorPtr; // stored inside allIndices int *sectionForSidedefPtr; // also stored inside allIndices; + int *firstSectionForSectorPtr; // ditto. + int *numberOfSectionForSectorPtr; // ditto. FSection *SectionForSubsector(subsector_t *sub) { @@ -111,6 +118,14 @@ public: { return ssindex < 0 ? nullptr : &allSections[sectionForSubsectorPtr[ssindex]]; } + int SectionNumForSubsector(subsector_t *sub) + { + return SectionNumForSubsector(sub->Index()); + } + int SectionNumForSubsector(int ssindex) + { + return ssindex < 0 ? -1 : sectionForSubsectorPtr[ssindex]; + } FSection *SectionForSidedef(side_t *side) { return SectionForSidedef(side->Index()); @@ -119,11 +134,35 @@ public: { return sindex < 0 ? nullptr : &allSections[sectionForSidedefPtr[sindex]]; } + int SectionNumForSidedef(side_t *side) + { + return SectionNumForSidedef(side->Index()); + } + int SectionNumForSidedef(int sindex) + { + return sindex < 0 ? -1 : sectionForSidedefPtr[sindex]; + } + TArrayView SectionsForSector(sector_t *sec) + { + return SectionsForSector(sec->Index()); + } + TArrayView SectionsForSector(int sindex) + { + return sindex < 0 ? TArrayView(0) : TArrayView(&allSections[firstSectionForSectorPtr[sindex]], numberOfSectionForSectorPtr[sindex]); + } + int SectionIndex(const FSection *sect) + { + return int(sect - allSections.Data()); + } void Clear() { allLines.Clear(); allSections.Clear(); allIndices.Clear(); + allVertexIndices.Clear(); + allVertices.Clear(); + allSides.Clear(); + allSubsectors.Clear(); } void Reset() { @@ -131,6 +170,10 @@ public: allLines.ShrinkToFit(); allSections.ShrinkToFit(); allIndices.ShrinkToFit(); + allVertexIndices.ShrinkToFit(); + allVertices.ShrinkToFit(); + allSides.ShrinkToFit(); + allSubsectors.ShrinkToFit(); } }; diff --git a/src/hwrenderer/scene/hw_bsp.cpp b/src/hwrenderer/scene/hw_bsp.cpp index 75be620f4..92b911781 100644 --- a/src/hwrenderer/scene/hw_bsp.cpp +++ b/src/hwrenderer/scene/hw_bsp.cpp @@ -155,6 +155,7 @@ void HWDrawInfo::WorkerThread() { GLFlat flat; SetupFlat.Clock(); + flat.section = level.sections.SectionForSubsector(job->sub); front = hw_FakeFlat(job->sub->render_sector, &fakefront, in_area, false); flat.ProcessSector(this, front); SetupFlat.Unclock(); @@ -679,7 +680,8 @@ void HWDrawInfo::DoSubsector(subsector_t * sub) fakesector = hw_FakeFlat(sector, &fake, in_area, false); } - uint8_t &srf = sectorrenderflags[sub->render_sector->sectornum]; + auto secnum = level.sections.SectionNumForSubsector(sub); + uint8_t &srf = section_renderflags[secnum]; if (!(srf & SSRF_PROCESSED)) { srf |= SSRF_PROCESSED; @@ -691,6 +693,7 @@ void HWDrawInfo::DoSubsector(subsector_t * sub) else { GLFlat flat; + flat.section = level.sections.SectionForSubsector(sub); SetupFlat.Clock(); flat.ProcessSector(this, fakesector); SetupFlat.Unclock(); diff --git a/src/hwrenderer/scene/hw_drawinfo.cpp b/src/hwrenderer/scene/hw_drawinfo.cpp index d781fc64d..128b1d8fa 100644 --- a/src/hwrenderer/scene/hw_drawinfo.cpp +++ b/src/hwrenderer/scene/hw_drawinfo.cpp @@ -214,11 +214,11 @@ void HWDrawInfo::ClearBuffers() CurrentMapSections.Resize(level.NumMapSections); CurrentMapSections.Zero(); - sectorrenderflags.Resize(level.sectors.Size()); + section_renderflags.Resize(level.sections.allSections.Size()); ss_renderflags.Resize(level.subsectors.Size()); no_renderflags.Resize(level.subsectors.Size()); - memset(§orrenderflags[0], 0, level.sectors.Size() * sizeof(sectorrenderflags[0])); + memset(§ion_renderflags[0], 0, level.sections.allSections.Size() * sizeof(section_renderflags[0])); memset(&ss_renderflags[0], 0, level.subsectors.Size() * sizeof(ss_renderflags[0])); memset(&no_renderflags[0], 0, level.nodes.Size() * sizeof(no_renderflags[0])); diff --git a/src/hwrenderer/scene/hw_drawinfo.h b/src/hwrenderer/scene/hw_drawinfo.h index 1eb4f6282..c3a9ddfb3 100644 --- a/src/hwrenderer/scene/hw_drawinfo.h +++ b/src/hwrenderer/scene/hw_drawinfo.h @@ -170,7 +170,7 @@ struct HWDrawInfo TArray HandledSubsectors; - TArray sectorrenderflags; + TArray section_renderflags; TArray ss_renderflags; TArray no_renderflags; diff --git a/src/hwrenderer/scene/hw_drawstructs.h b/src/hwrenderer/scene/hw_drawstructs.h index 38514a6bf..194de2c50 100644 --- a/src/hwrenderer/scene/hw_drawstructs.h +++ b/src/hwrenderer/scene/hw_drawstructs.h @@ -27,6 +27,7 @@ struct FSpriteModelFrame; struct particle_t; class FRenderState; struct GLDecal; +struct FSection; enum area_t : int; enum HWRenderStyle @@ -293,6 +294,7 @@ class GLFlat { public: sector_t * sector; + FSection *section; float z; // the z position of the flat (only valid for non-sloped planes) FMaterial *gltexture; diff --git a/src/hwrenderer/scene/hw_flats.cpp b/src/hwrenderer/scene/hw_flats.cpp index 776346114..db9edfccb 100644 --- a/src/hwrenderer/scene/hw_flats.cpp +++ b/src/hwrenderer/scene/hw_flats.cpp @@ -189,6 +189,8 @@ void GLFlat::DrawSubsectors(HWDrawInfo *di, FRenderState &state) SetupLights(di, sector->lighthead, lightdata, sector->PortalGroup); } state.SetLightIndex(dynlightindex); + + if (vcount > 0 && !di->ClipLineShouldBeActive()) { state.DrawIndexed(DT_Triangles, iboindex, vcount); @@ -197,6 +199,7 @@ void GLFlat::DrawSubsectors(HWDrawInfo *di, FRenderState &state) } else { + /* int index = iboindex; bool applied = false; for (int i = 0; i < sector->subsectorcount; i++) @@ -213,6 +216,7 @@ void GLFlat::DrawSubsectors(HWDrawInfo *di, FRenderState &state) } index += (sub->numlines - 2) * 3; } + */ } if (!(renderflags&SSRF_RENDER3DPLANES)) @@ -473,7 +477,7 @@ void GLFlat::ProcessSector(HWDrawInfo *di, sector_t * frontsector) extsector_t::xfloor &x = sector->e->XFloor; dynlightindex = -1; - uint8_t &srf = di->sectorrenderflags[sector->sectornum]; + uint8_t &srf = di->section_renderflags[level.sections.SectionIndex(section)]; const auto &vp = di->Viewpoint; // diff --git a/src/hwrenderer/scene/hw_renderhacks.cpp b/src/hwrenderer/scene/hw_renderhacks.cpp index f6899b434..afc8aaab8 100644 --- a/src/hwrenderer/scene/hw_renderhacks.cpp +++ b/src/hwrenderer/scene/hw_renderhacks.cpp @@ -850,7 +850,8 @@ void HWDrawInfo::PrepareUnhandledMissingTextures() if (seg->linedef->validcount == validcount) continue; // already done seg->linedef->validcount = validcount; - if (!(sectorrenderflags[seg->backsector->sectornum] & SSRF_RENDERFLOOR)) continue; + int section = level.sections.SectionNumForSidedef(seg->sidedef); + if (!(section_renderflags[section] & SSRF_RENDERFLOOR)) continue; if (seg->frontsector->GetPlaneTexZ(sector_t::floor) > Viewpoint.Pos.Z) continue; // out of sight if (seg->backsector->transdoor) continue; if (seg->backsector->GetTexture(sector_t::floor) == skyflatnum) continue; From 950ed07ae6627040359264e96d714a5822275f6a Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Mon, 5 Nov 2018 15:30:50 +0100 Subject: [PATCH 04/16] WIP --- src/hwrenderer/data/flatvertices.cpp | 81 ++----- src/hwrenderer/data/flatvertices.h | 33 +-- src/hwrenderer/data/hw_sections.cpp | 302 +++++++++++++++++---------- src/hwrenderer/data/hw_sections.h | 20 +- 4 files changed, 228 insertions(+), 208 deletions(-) diff --git a/src/hwrenderer/data/flatvertices.cpp b/src/hwrenderer/data/flatvertices.cpp index 20e139c58..c19169db3 100644 --- a/src/hwrenderer/data/flatvertices.cpp +++ b/src/hwrenderer/data/flatvertices.cpp @@ -35,6 +35,13 @@ #include "hwrenderer/data/buffers.h" #include "hwrenderer/scene/hw_renderstate.h" +namespace VertexBuilder +{ + TArray BuildVertices(); +} + +using VertexContainers = TArray; + //========================================================================== // @@ -158,54 +165,22 @@ static F3DFloor *Find3DFloor(sector_t *target, sector_t *model) // //========================================================================== -int FFlatVertexBuffer::CreateIndexedSubsectorVertices(subsector_t *sub, const secplane_t &plane, int floor, int vi, FFlatVertexBuffer::FIndexGenerationInfo &gen) +int FFlatVertexBuffer::CreateIndexedSectorVertices(sector_t *sec, const secplane_t &plane, int floor, VertexContainer &verts) { - if (sub->numlines < 3) return -1; - - int idx = ibo_data.Reserve((sub->numlines - 2) * 3); - int idxc = idx; - int firstndx = gen.GetIndex(sub->firstline[0].v1); - int secondndx = gen.GetIndex(sub->firstline[1].v1); - for (unsigned int k = 2; knumlines; k++) - { - auto ndx = gen.GetIndex(sub->firstline[k].v1); - - ibo_data[idx++] = vi + firstndx; - ibo_data[idx++] = vi + secondndx; - ibo_data[idx++] = vi + ndx; - secondndx = ndx; - } - return idx; -} - -//========================================================================== -// -// Creates the vertices for one plane in one subsector -// -//========================================================================== - -int FFlatVertexBuffer::CreateIndexedSectorVertices(sector_t *sec, const secplane_t &plane, int floor, FFlatVertexBuffer::FIndexGenerationInfo &gen) -{ - int rt = ibo_data.Size(); - int vi = vbo_shadowdata.Reserve(gen.vertices.Size()); + int vi = vbo_shadowdata.Reserve(verts.vertices.Size()); float diff; // Create the actual vertices. if (sec->transdoor && floor) diff = -1.f; else diff = 0.f; - for (unsigned i = 0; i < gen.vertices.Size(); i++) + for (unsigned i = 0; i < verts.vertices.Size(); i++) { - vbo_shadowdata[vi + i].SetFlatVertex(gen.vertices[i], plane); + vbo_shadowdata[vi + i].SetFlatVertex(verts.vertices[i].vertex, plane); vbo_shadowdata[vi + i].z += diff; } - - // Create the indices for the subsectors - for (int j = 0; jsubsectorcount; j++) - { - subsector_t *sub = sec->subsectors[j]; - CreateIndexedSubsectorVertices(sub, plane, floor, vi, gen); - } - sec->ibocount = ibo_data.Size() - rt; + + int rt = ibo_data.size(); + ibo_data.Append(verts.indices); return rt; } @@ -215,19 +190,20 @@ int FFlatVertexBuffer::CreateIndexedSectorVertices(sector_t *sec, const secplane // //========================================================================== -int FFlatVertexBuffer::CreateIndexedVertices(int h, sector_t *sec, const secplane_t &plane, int floor, TArray &gen) +int FFlatVertexBuffer::CreateIndexedVertices(int h, sector_t *sec, const secplane_t &plane, int floor, VertexContainers &verts) { sec->vboindex[h] = vbo_shadowdata.Size(); // First calculate the vertices for the sector itself sec->vboheight[h] = sec->GetPlaneTexZ(h); - sec->iboindex[h] = CreateIndexedSectorVertices(sec, plane, floor, gen[sec->Index()]); + sec->ibocount = verts.indices.Size(); + sec->iboindex[h] = CreateIndexedSectorVertices(sec, plane, floor, verts[sec->Index()]); // Next are all sectors using this one as heightsec TArray &fakes = sec->e->FakeFloor.Sectors; for (unsigned g = 0; g < fakes.Size(); g++) { sector_t *fsec = fakes[g]; - fsec->iboindex[2 + h] = CreateIndexedSectorVertices(fsec, plane, false, gen[fsec->Index()]); + fsec->iboindex[2 + h] = CreateIndexedSectorVertices(fsec, plane, false, verts[fsec->Index()]); } // and finally all attached 3D floors @@ -244,7 +220,7 @@ int FFlatVertexBuffer::CreateIndexedVertices(int h, sector_t *sec, const secplan if (dotop || dobottom) { - auto ndx = CreateIndexedSectorVertices(fsec, plane, false, gen[fsec->Index()]); + auto ndx = CreateIndexedSectorVertices(fsec, plane, false, verts[fsec->Index()]); if (dotop) ffloor->top.vindex = ndx; if (dobottom) ffloor->bottom.vindex = ndx; } @@ -263,26 +239,13 @@ int FFlatVertexBuffer::CreateIndexedVertices(int h, sector_t *sec, const secplan void FFlatVertexBuffer::CreateIndexedFlatVertices() { - TArray gen; - gen.Resize(level.sectors.Size()); - // This must be generated up front so that the following code knows how many vertices a sector contains. - for (unsigned i = 0; i < level.sectors.Size(); i++) - { - for (int j = 0; j < level.sectors[i].subsectorcount; j++) - { - auto sub = level.sectors[i].subsectors[j]; - for (unsigned k = 0; k < sub->numlines; k++) - { - auto vert = sub->firstline[k].v1; - gen[i].AddVertex(vert); - } - } - } + auto verts = VertexBuilder::BuildVertices(); + for (int h = sector_t::floor; h <= sector_t::ceiling; h++) { for (auto &sec : level.sectors) { - CreateIndexedVertices(h, &sec, sec.GetSecPlane(h), h == sector_t::floor, gen); + CreateIndexedVertices(h, &sec, sec.GetSecPlane(h), h == sector_t::floor, verts); } } diff --git a/src/hwrenderer/data/flatvertices.h b/src/hwrenderer/data/flatvertices.h index c55448379..13a8d3130 100644 --- a/src/hwrenderer/data/flatvertices.h +++ b/src/hwrenderer/data/flatvertices.h @@ -62,31 +62,6 @@ class FFlatVertexBuffer static const unsigned int BUFFER_SIZE = 2000000; static const unsigned int BUFFER_SIZE_TO_USE = 1999500; - - // Temporary data for creating an indexed buffer - struct FIndexGenerationInfo - { - TArray vertices; - TMap vertexmap; - - uint32_t AddVertex(vertex_t *vert) - { - auto check = vertexmap.CheckKey(vert); - if (check != nullptr) return *check; - auto index = vertices.Push(vert); - vertexmap[vert] = index; - return index; - } - - uint32_t GetIndex(vertex_t *vert) - { - auto check = vertexmap.CheckKey(vert); - if (check != nullptr) return *check; - return ~0; - } - }; - - public: enum { @@ -140,9 +115,9 @@ public: } private: - int CreateIndexedSubsectorVertices(subsector_t *sub, const secplane_t &plane, int floor, int vi, FIndexGenerationInfo &gen); - int CreateIndexedSectorVertices(sector_t *sec, const secplane_t &plane, int floor, FIndexGenerationInfo &gen); - int CreateIndexedVertices(int h, sector_t *sec, const secplane_t &plane, int floor, TArray &gen); + int CreateIndexedSectionVertices(subsector_t *sub, const secplane_t &plane, int floor, VertexContainer &cont); + int CreateIndexedSectorVertices(sector_t *sec, const secplane_t &plane, int floor, VertexContainer &cont); + int CreateIndexedVertices(int h, sector_t *sec, const secplane_t &plane, int floor, VertexContainers &cont); void CreateIndexedFlatVertices(); void UpdatePlaneVertices(sector_t *sec, int plane); @@ -154,4 +129,4 @@ public: }; -#endif \ No newline at end of file +#endif diff --git a/src/hwrenderer/data/hw_sections.cpp b/src/hwrenderer/data/hw_sections.cpp index 2c698386c..31c1986e6 100644 --- a/src/hwrenderer/data/hw_sections.cpp +++ b/src/hwrenderer/data/hw_sections.cpp @@ -40,7 +40,6 @@ using DoublePoint = std::pair; template<> struct THashTraits { - // Use all bits when hashing doubles instead of converting them to ints. hash_t Hash(const DoublePoint &key) { return (hash_t)SuperFastHash((const char*)(const void*)&key, sizeof(key)); @@ -48,6 +47,15 @@ template<> struct THashTraits int Compare(const DoublePoint &left, const DoublePoint &right) { return left != right; } }; +template<> struct THashTraits +{ + hash_t Hash(const FSectionVertex &key) + { + return (int)(((intptr_t)key.vertex) >> 4) ^ (key.qualifier << 16); + } + int Compare(const FSectionVertex &left, const FSectionVertex &right) { return left.vertex != right.vertex && left.qualifier != right.qualifier; } +}; + struct WorkSectionLine { @@ -613,112 +621,6 @@ public: } - //============================================================================= - // - // - // - //============================================================================= - - // Temporary data for creating an indexed buffer - struct VertexIndexGenerationInfo - { - TArray vertices; - TMap vertexmap; - - TArray indices; - - uint32_t AddVertex(vertex_t *vert) - { - auto check = vertexmap.CheckKey(vert); - if (check != nullptr) return *check; - auto index = vertices.Push(vert); - vertexmap[vert] = index; - return index; - } - - uint32_t GetIndex(vertex_t *vert) - { - auto check = vertexmap.CheckKey(vert); - if (check != nullptr) return *check; - return ~0u; - } - - uint32_t AddIndexForVertex(vertex_t *vert) - { - return indices.Push(GetIndex(vert)); - } - - uint32_t AddIndex(uint32_t indx) - { - return indices.Push(indx); - } - }; - - //============================================================================= - // - // - // - //============================================================================= - - void CreateIndexedSubsectorVertices(subsector_t *sub, VertexIndexGenerationInfo &gen) - { - if (sub->numlines < 3) return; - - uint32_t startindex = gen.indices.Size(); - - if ((sub->flags & SSECF_HOLE) && sub->numlines > 3) - { - // Hole filling "subsectors" are not necessarily convex so they require real triangulation. - // These things are extremely rare so performance is secondary here. - - using Point = std::pair; - std::vector> polygon; - std::vector *curPoly; - - for (unsigned i = 0; i < sub->numlines; i++) - { - polygon.resize(1); - curPoly = &polygon.back(); - curPoly->push_back({ sub->firstline[i].v1->fX(), sub->firstline[i].v1->fY() }); - } - auto indices = mapbox::earcut(polygon); - for (auto vti : indices) - { - gen.AddIndexForVertex(sub->firstline[vti].v1); - } - } - else - { - int firstndx = gen.GetIndex(sub->firstline[0].v1); - int secondndx = gen.GetIndex(sub->firstline[1].v1); - for (unsigned int k = 2; k < sub->numlines; k++) - { - gen.AddIndex(firstndx); - gen.AddIndex(secondndx); - auto ndx = gen.GetIndex(sub->firstline[k].v1); - gen.AddIndex(ndx); - secondndx = ndx; - } - } - } - - - void CreateVerticesForSection(FSectionContainer &output, FSection §ion) - { - VertexIndexGenerationInfo gen; - - for (auto sub : section.subsectors) - { - CreateIndexedSubsectorVertices(sub, gen); - } - section.vertexindex = output.allVertices.Size(); - section.vertexcount = gen.vertices.Size(); - section.indexindex = output.allVertexIndices.Size(); - section.indexcount = gen.indices.Size(); - output.allVertices.Append(gen.vertices); - output.allVertexIndices.Append(gen.indices); - } - //============================================================================= // @@ -815,7 +717,7 @@ public: output.sectionForSubsectorPtr[ssi] = curgroup; } numsubsectors += group.subsectors.Size(); - CreateVerticesForSection(output, dest); + CreateVerticesForSection(output, dest, true); curgroup++; } } @@ -892,4 +794,186 @@ void CreateSections(FSectionContainer &container) CCMD(printsections) { PrintSections(level.sections); -} \ No newline at end of file +} + + + +//============================================================================= +// +// One sector's vertex data. +// +//============================================================================= + +struct VertexContainer +{ + TArray vertices; + TMap vertexmap; + bool perSubsector = false; + + TArray indices; + + uint32_t AddVertex(FSectionVertex *vert) + { + auto check = vertexmap.CheckKey(vert); + if (check != nullptr) return *check; + auto index = vertices.Push(*vert); + vertexmap[vert] = index; + return index; + } + + uint32_t AddVertex(vertex_t *vert, int qualifier) + { + FSectionVertex vertx = { vert, qualifier}; + return AddVertex(&vertx); + } + + uint32_t GetIndex(FSectionVertex *vert) + { + auto check = vertexmap.CheckKey(vert); + if (check != nullptr) return *check; + return ~0u; + } + + uint32_t GetIndex(vertex_t *vert, int qualifier) + { + FSectionVertex vertx = { vert, qualifier}; + return GetIndex(&vertx); + } + + uint32_t AddIndexForVertex(FSectionVertex *vert) + { + return indices.Push(GetIndex(vert)); + } + + uint32_t AddIndexForVertex(vertex_t *vert, int qualifier) + { + return indices.Push(GetIndex(vert, qualifier)); + } + + uint32_t AddIndex(uint32_t indx) + { + return indices.Push(indx); + } +}; + + +//============================================================================= +// +// Creates vertex meshes for sector planes +// +//============================================================================= + +namespace VertexBuilder +{ + + //============================================================================= + // + // + // + //============================================================================= + + static void CreateVerticesForSubsector(subsector_t *sub, VertexContainer &gen, int qualifier) + { + if (sub->numlines < 3) return; + + uint32_t startindex = gen.indices.Size(); + + if ((sub->flags & SSECF_HOLE) && sub->numlines > 3) + { + // Hole filling "subsectors" are not necessarily convex so they require real triangulation. + // These things are extremely rare so performance is secondary here. + + using Point = std::pair; + std::vector> polygon; + std::vector *curPoly; + + for (unsigned i = 0; i < sub->numlines; i++) + { + polygon.resize(1); + curPoly = &polygon.back(); + curPoly->push_back({ sub->firstline[i].v1->fX(), sub->firstline[i].v1->fY() }); + } + auto indices = mapbox::earcut(polygon); + for (auto vti : indices) + { + gen.AddIndexForVertex(sub->firstline[vti].v1, qualifier); + } + } + else + { + int firstndx = gen.GetIndex(sub->firstline[0].v1, qualifier); + int secondndx = gen.GetIndex(sub->firstline[1].v1, qualifier); + for (unsigned int k = 2; k < sub->numlines; k++) + { + gen.AddIndex(firstndx); + gen.AddIndex(secondndx); + auto ndx = gen.GetIndex(sub->firstline[k].v1, qualifier); + gen.AddIndex(ndx); + secondndx = ndx; + } + } + } + + //============================================================================= + // + // + // + //============================================================================= + + static void TriangulateSection(FSection §, VertexContainer &gen, int qualifier) + { + if (sect.segments.Size() < 3) return; + + // todo + } + + //============================================================================= + // + // + // + //============================================================================= + + + static void CreateVerticesForSection(FSection §ion, VertexContainer &gen, bool useSubsectors) + { + section.vertexindex = gen.indices.Size(); + + if (useSubsectors) + { + for (auto sub : section.subsectors) + { + CreateVerticesForSubsector(sub, gen, -1); + } + } + else + { + TriangulateSection(section, gen, -1); + } + section.vertexcount = gen.indices.Size() - section.vertexindex; + } + + //========================================================================== + // + // Creates the vertices for one plane in one subsector + // + //========================================================================== + + static void CreateVerticesForSector(sector_t *sec, VertexContainer gen) + { + auto sections = level.sections.SectionsForSector(sec); + for (auto §ion :sections) + { + CreateVerticesForSection( section, gen, true); + } + } + + TArray BuildVertices() + { + TArray verticesPerSector(level.sectors.Size(), true); + for (unsigned i=0; i allLines; TArray allSections; - TArray allVertices; - TArray allVertexIndices; TArray allSides; TArray allSubsectors; TArray allIndices; @@ -159,8 +161,6 @@ public: allLines.Clear(); allSections.Clear(); allIndices.Clear(); - allVertexIndices.Clear(); - allVertices.Clear(); allSides.Clear(); allSubsectors.Clear(); } @@ -170,8 +170,6 @@ public: allLines.ShrinkToFit(); allSections.ShrinkToFit(); allIndices.ShrinkToFit(); - allVertexIndices.ShrinkToFit(); - allVertices.ShrinkToFit(); allSides.ShrinkToFit(); allSubsectors.ShrinkToFit(); } @@ -180,4 +178,4 @@ public: void CreateSections(FSectionContainer &container); -#endif \ No newline at end of file +#endif From 625eb1e76a85afb1871c5485b82cb9e6e5fcba81 Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Mon, 5 Nov 2018 21:11:54 +0100 Subject: [PATCH 05/16] - FVertexBuilder's output looks correct now. --- src/CMakeLists.txt | 1 + src/earcut.hpp | 790 +++++++++++++++++++++++ src/hwrenderer/data/flatvertices.cpp | 41 +- src/hwrenderer/data/flatvertices.h | 3 +- src/hwrenderer/data/hw_sections.cpp | 228 +------ src/hwrenderer/data/hw_sections.h | 6 - src/hwrenderer/data/hw_vertexbuilder.cpp | 146 +++++ src/hwrenderer/data/hw_vertexbuilder.h | 69 ++ src/p_setup.cpp | 2 + src/r_data/renderinfo.cpp | 2 - src/tarray.h | 4 + 11 files changed, 1064 insertions(+), 228 deletions(-) create mode 100644 src/earcut.hpp create mode 100644 src/hwrenderer/data/hw_vertexbuilder.cpp create mode 100644 src/hwrenderer/data/hw_vertexbuilder.h diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 559379a6d..da9b92dda 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1049,6 +1049,7 @@ set (PCH_SOURCES gl/system/gl_buffers.cpp gl/textures/gl_hwtexture.cpp gl/textures/gl_samplers.cpp + hwrenderer/data/hw_vertexbuilder.cpp hwrenderer/data/hw_sections.cpp hwrenderer/data/flatvertices.cpp hwrenderer/data/hw_viewpointbuffer.cpp diff --git a/src/earcut.hpp b/src/earcut.hpp new file mode 100644 index 000000000..d6a2c9798 --- /dev/null +++ b/src/earcut.hpp @@ -0,0 +1,790 @@ +/* +ISC License + +Copyright (c) 2015, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +*/ +#pragma once + +#include +#include +#include +#include +#include + +namespace mapbox { + +namespace util { + +template struct nth { + inline static typename std::tuple_element::type + get(const T& t) { return std::get(t); }; +}; + +} + +namespace detail { + +template +class Earcut { +public: + std::vector indices; + std::size_t vertices = 0; + + template + void operator()(const Polygon& points); + +private: + struct Node { + Node(N index, double x_, double y_) : i(index), x(x_), y(y_) {} + Node(const Node&) = delete; + Node& operator=(const Node&) = delete; + Node(Node&&) = delete; + Node& operator=(Node&&) = delete; + + const N i; + const double x; + const double y; + + // previous and next vertice nodes in a polygon ring + Node* prev = nullptr; + Node* next = nullptr; + + // z-order curve value + int32_t z = 0; + + // previous and next nodes in z-order + Node* prevZ = nullptr; + Node* nextZ = nullptr; + + // indicates whether this is a steiner point + bool steiner = false; + }; + + template Node* linkedList(const Ring& points, const bool clockwise); + Node* filterPoints(Node* start, Node* end = nullptr); + void earcutLinked(Node* ear, int pass = 0); + bool isEar(Node* ear); + bool isEarHashed(Node* ear); + Node* cureLocalIntersections(Node* start); + void splitEarcut(Node* start); + template Node* eliminateHoles(const Polygon& points, Node* outerNode); + void eliminateHole(Node* hole, Node* outerNode); + Node* findHoleBridge(Node* hole, Node* outerNode); + void indexCurve(Node* start); + Node* sortLinked(Node* list); + int32_t zOrder(const double x_, const double y_); + Node* getLeftmost(Node* start); + bool pointInTriangle(double ax, double ay, double bx, double by, double cx, double cy, double px, double py) const; + bool isValidDiagonal(Node* a, Node* b); + double area(const Node* p, const Node* q, const Node* r) const; + bool equals(const Node* p1, const Node* p2); + bool intersects(const Node* p1, const Node* q1, const Node* p2, const Node* q2); + bool intersectsPolygon(const Node* a, const Node* b); + bool locallyInside(const Node* a, const Node* b); + bool middleInside(const Node* a, const Node* b); + Node* splitPolygon(Node* a, Node* b); + template Node* insertNode(std::size_t i, const Point& p, Node* last); + void removeNode(Node* p); + + bool hashing; + double minX, maxX; + double minY, maxY; + double inv_size = 0; + + template > + class ObjectPool { + public: + ObjectPool() { } + ObjectPool(std::size_t blockSize_) { + reset(blockSize_); + } + ~ObjectPool() { + clear(); + } + template + T* construct(Args&&... args) { + if (currentIndex >= blockSize) { + currentBlock = alloc.allocate(blockSize); + allocations.emplace_back(currentBlock); + currentIndex = 0; + } + T* object = ¤tBlock[currentIndex++]; + alloc.construct(object, std::forward(args)...); + return object; + } + void reset(std::size_t newBlockSize) { + for (auto allocation : allocations) alloc.deallocate(allocation, blockSize); + allocations.clear(); + blockSize = std::max(1, newBlockSize); + currentBlock = nullptr; + currentIndex = blockSize; + } + void clear() { reset(blockSize); } + private: + T* currentBlock = nullptr; + std::size_t currentIndex = 1; + std::size_t blockSize = 1; + std::vector allocations; + Alloc alloc; + }; + ObjectPool nodes; +}; + +template template +void Earcut::operator()(const Polygon& points) { + // reset + indices.clear(); + vertices = 0; + + if (points.empty()) return; + + double x; + double y; + int threshold = 80; + std::size_t len = 0; + + for (size_t i = 0; threshold >= 0 && i < points.size(); i++) { + threshold -= static_cast(points[i].size()); + len += points[i].size(); + } + + //estimate size of nodes and indices + nodes.reset(len * 3 / 2); + indices.reserve(len + points[0].size()); + + Node* outerNode = linkedList(points[0], true); + if (!outerNode) return; + + if (points.size() > 1) outerNode = eliminateHoles(points, outerNode); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + hashing = threshold < 0; + if (hashing) { + Node* p = outerNode->next; + minX = maxX = outerNode->x; + minY = maxY = outerNode->y; + do { + x = p->x; + y = p->y; + minX = std::min(minX, x); + minY = std::min(minY, y); + maxX = std::max(maxX, x); + maxY = std::max(maxY, y); + p = p->next; + } while (p != outerNode); + + // minX, minY and size are later used to transform coords into integers for z-order calculation + inv_size = std::max(maxX - minX, maxY - minY); + inv_size = inv_size != .0 ? (1. / inv_size) : .0; + } + + earcutLinked(outerNode); + + nodes.clear(); +} + +// create a circular doubly linked list from polygon points in the specified winding order +template template +typename Earcut::Node* +Earcut::linkedList(const Ring& points, const bool clockwise) { + using Point = typename Ring::value_type; + double sum = 0; + const std::size_t len = points.size(); + std::size_t i, j; + Node* last = nullptr; + + // calculate original winding order of a polygon ring + for (i = 0, j = len > 0 ? len - 1 : 0; i < len; j = i++) { + const auto& p1 = points[i]; + const auto& p2 = points[j]; + const double p20 = util::nth<0, Point>::get(p2); + const double p10 = util::nth<0, Point>::get(p1); + const double p11 = util::nth<1, Point>::get(p1); + const double p21 = util::nth<1, Point>::get(p2); + sum += (p20 - p10) * (p11 + p21); + } + + // link points into circular doubly-linked list in the specified winding order + if (clockwise == (sum > 0)) { + for (i = 0; i < len; i++) last = insertNode(vertices + i, points[i], last); + } else { + for (i = len; i-- > 0;) last = insertNode(vertices + i, points[i], last); + } + + if (last && equals(last, last->next)) { + removeNode(last); + last = last->next; + } + + vertices += len; + + return last; +} + +// eliminate colinear or duplicate points +template +typename Earcut::Node* +Earcut::filterPoints(Node* start, Node* end) { + if (!end) end = start; + + Node* p = start; + bool again; + do { + again = false; + + if (!p->steiner && (equals(p, p->next) /*|| area(p->prev, p, p->next) == 0*/)) + { + removeNode(p); + p = end = p->prev; + + if (p == p->next) break; + again = true; + + } else { + p = p->next; + } + } while (again || p != end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +template +void Earcut::earcutLinked(Node* ear, int pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && hashing) indexCurve(ear); + + Node* stop = ear; + Node* prev; + Node* next; + + int iterations = 0; + + // iterate through ears, slicing them one by one + while (ear->prev != ear->next) { + iterations++; + prev = ear->prev; + next = ear->next; + + if (hashing ? isEarHashed(ear) : isEar(ear)) { + // cut off the triangle + indices.emplace_back(prev->i); + indices.emplace_back(ear->i); + indices.emplace_back(next->i); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next->next; + stop = next->next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear == stop) { + // try filtering points and slicing again + if (!pass) earcutLinked(filterPoints(ear), 1); + + // if this didn't work, try curing all small self-intersections locally + else if (pass == 1) { + ear = cureLocalIntersections(ear); + earcutLinked(ear, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass == 2) splitEarcut(ear); + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +template +bool Earcut::isEar(Node* ear) { + const Node* a = ear->prev; + const Node* b = ear; + const Node* c = ear->next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + Node* p = ear->next->next; + + while (p != ear->prev) { + if (pointInTriangle(a->x, a->y, b->x, b->y, c->x, c->y, p->x, p->y) && + area(p->prev, p, p->next) >= 0) return false; + p = p->next; + } + + return true; +} + +template +bool Earcut::isEarHashed(Node* ear) { + const Node* a = ear->prev; + const Node* b = ear; + const Node* c = ear->next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + const double minTX = std::min(a->x, std::min(b->x, c->x)); + const double minTY = std::min(a->y, std::min(b->y, c->y)); + const double maxTX = std::max(a->x, std::max(b->x, c->x)); + const double maxTY = std::max(a->y, std::max(b->y, c->y)); + + // z-order range for the current triangle bbox; + const int32_t minZ = zOrder(minTX, minTY); + const int32_t maxZ = zOrder(maxTX, maxTY); + + // first look for points inside the triangle in increasing z-order + Node* p = ear->nextZ; + + while (p && p->z <= maxZ) { + if (p != ear->prev && p != ear->next && + pointInTriangle(a->x, a->y, b->x, b->y, c->x, c->y, p->x, p->y) && + area(p->prev, p, p->next) >= 0) return false; + p = p->nextZ; + } + + // then look for points in decreasing z-order + p = ear->prevZ; + + while (p && p->z >= minZ) { + if (p != ear->prev && p != ear->next && + pointInTriangle(a->x, a->y, b->x, b->y, c->x, c->y, p->x, p->y) && + area(p->prev, p, p->next) >= 0) return false; + p = p->prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +template +typename Earcut::Node* +Earcut::cureLocalIntersections(Node* start) { + Node* p = start; + do { + Node* a = p->prev; + Node* b = p->next->next; + + // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2]) + if (!equals(a, b) && intersects(a, p, p->next, b) && locallyInside(a, b) && locallyInside(b, a)) { + indices.emplace_back(a->i); + indices.emplace_back(p->i); + indices.emplace_back(b->i); + + // remove two nodes involved + removeNode(p); + removeNode(p->next); + + p = start = b; + } + p = p->next; + } while (p != start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +template +void Earcut::splitEarcut(Node* start) { + // look for a valid diagonal that divides the polygon into two + Node* a = start; + do { + Node* b = a->next->next; + while (b != a->prev) { + if (a->i != b->i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + Node* c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a->next); + c = filterPoints(c, c->next); + + // run earcut on each half + earcutLinked(a); + earcutLinked(c); + return; + } + b = b->next; + } + a = a->next; + } while (a != start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +template template +typename Earcut::Node* +Earcut::eliminateHoles(const Polygon& points, Node* outerNode) { + const size_t len = points.size(); + + std::vector queue; + for (size_t i = 1; i < len; i++) { + Node* list = linkedList(points[i], false); + if (list) { + if (list == list->next) list->steiner = true; + queue.push_back(getLeftmost(list)); + } + } + std::sort(queue.begin(), queue.end(), [](const Node* a, const Node* b) { + return a->x < b->x; + }); + + // process holes from left to right + for (size_t i = 0; i < queue.size(); i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode->next); + } + + return outerNode; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +template +void Earcut::eliminateHole(Node* hole, Node* outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + Node* b = splitPolygon(outerNode, hole); + filterPoints(b, b->next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +template +typename Earcut::Node* +Earcut::findHoleBridge(Node* hole, Node* outerNode) { + Node* p = outerNode; + double hx = hole->x; + double hy = hole->y; + double qx = -std::numeric_limits::infinity(); + Node* m = nullptr; + + // find a segment intersected by a ray from the hole's leftmost Vertex to the left; + // segment's endpoint with lesser x will be potential connection Vertex + do { + if (hy <= p->y && hy >= p->next->y && p->next->y != p->y) { + double x = p->x + (hy - p->y) * (p->next->x - p->x) / (p->next->y - p->y); + if (x <= hx && x > qx) { + qx = x; + if (x == hx) { + if (hy == p->y) return p; + if (hy == p->next->y) return p->next; + } + m = p->x < p->next->x ? p : p->next; + } + } + p = p->next; + } while (p != outerNode); + + if (!m) return 0; + + if (hx == qx) return m->prev; + + // look for points inside the triangle of hole Vertex, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the Vertex of the minimum angle with the ray as connection Vertex + + const Node* stop = m; + double tanMin = std::numeric_limits::infinity(); + double tanCur = 0; + + p = m->next; + double mx = m->x; + double my = m->y; + + while (p != stop) { + if (hx >= p->x && p->x >= mx && hx != p->x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p->x, p->y)) { + + tanCur = std::abs(hy - p->y) / (hx - p->x); // tangential + + if ((tanCur < tanMin || (tanCur == tanMin && p->x > m->x)) && locallyInside(p, hole)) { + m = p; + tanMin = tanCur; + } + } + + p = p->next; + } + + return m; +} + +// interlink polygon nodes in z-order +template +void Earcut::indexCurve(Node* start) { + assert(start); + Node* p = start; + + do { + p->z = p->z ? p->z : zOrder(p->x, p->y); + p->prevZ = p->prev; + p->nextZ = p->next; + p = p->next; + } while (p != start); + + p->prevZ->nextZ = nullptr; + p->prevZ = nullptr; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +template +typename Earcut::Node* +Earcut::sortLinked(Node* list) { + assert(list); + Node* p; + Node* q; + Node* e; + Node* tail; + int i, numMerges, pSize, qSize; + int inSize = 1; + + for (;;) { + p = list; + list = nullptr; + tail = nullptr; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q->nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize == 0) { + e = q; + q = q->nextZ; + qSize--; + } else if (qSize == 0 || !q) { + e = p; + p = p->nextZ; + pSize--; + } else if (p->z <= q->z) { + e = p; + p = p->nextZ; + pSize--; + } else { + e = q; + q = q->nextZ; + qSize--; + } + + if (tail) tail->nextZ = e; + else list = e; + + e->prevZ = tail; + tail = e; + } + + p = q; + } + + tail->nextZ = nullptr; + + if (numMerges <= 1) return list; + + inSize *= 2; + } +} + +// z-order of a Vertex given coords and size of the data bounding box +template +int32_t Earcut::zOrder(const double x_, const double y_) { + // coords are transformed into non-negative 15-bit integer range + int32_t x = static_cast(32767.0 * (x_ - minX) * inv_size); + int32_t y = static_cast(32767.0 * (y_ - minY) * inv_size); + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +template +typename Earcut::Node* +Earcut::getLeftmost(Node* start) { + Node* p = start; + Node* leftmost = start; + do { + if (p->x < leftmost->x) leftmost = p; + p = p->next; + } while (p != start); + + return leftmost; +} + +// check if a point lies within a convex triangle +template +bool Earcut::pointInTriangle(double ax, double ay, double bx, double by, double cx, double cy, double px, double py) const { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +template +bool Earcut::isValidDiagonal(Node* a, Node* b) { + return a->next->i != b->i && a->prev->i != b->i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +template +double Earcut::area(const Node* p, const Node* q, const Node* r) const { + return (q->y - p->y) * (r->x - q->x) - (q->x - p->x) * (r->y - q->y); +} + +// check if two points are equal +template +bool Earcut::equals(const Node* p1, const Node* p2) { + return p1->x == p2->x && p1->y == p2->y; +} + +// check if two segments intersect +template +bool Earcut::intersects(const Node* p1, const Node* q1, const Node* p2, const Node* q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return (area(p1, q1, p2) > 0) != (area(p1, q1, q2) > 0) && + (area(p2, q2, p1) > 0) != (area(p2, q2, q1) > 0); +} + +// check if a polygon diagonal intersects any polygon segments +template +bool Earcut::intersectsPolygon(const Node* a, const Node* b) { + const Node* p = a; + do { + if (p->i != a->i && p->next->i != a->i && p->i != b->i && p->next->i != b->i && + intersects(p, p->next, a, b)) return true; + p = p->next; + } while (p != a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +template +bool Earcut::locallyInside(const Node* a, const Node* b) { + return area(a->prev, a, a->next) < 0 ? + area(a, b, a->next) >= 0 && area(a, a->prev, b) >= 0 : + area(a, b, a->prev) < 0 || area(a, a->next, b) < 0; +} + +// check if the middle Vertex of a polygon diagonal is inside the polygon +template +bool Earcut::middleInside(const Node* a, const Node* b) { + const Node* p = a; + bool inside = false; + double px = (a->x + b->x) / 2; + double py = (a->y + b->y) / 2; + do { + if (((p->y > py) != (p->next->y > py)) && p->next->y != p->y && + (px < (p->next->x - p->x) * (py - p->y) / (p->next->y - p->y) + p->x)) + inside = !inside; + p = p->next; + } while (p != a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits +// polygon into two; if one belongs to the outer ring and another to a hole, it merges it into a +// single ring +template +typename Earcut::Node* +Earcut::splitPolygon(Node* a, Node* b) { + Node* a2 = nodes.construct(a->i, a->x, a->y); + Node* b2 = nodes.construct(b->i, b->x, b->y); + Node* an = a->next; + Node* bp = b->prev; + + a->next = b; + b->prev = a; + + a2->next = an; + an->prev = a2; + + b2->next = a2; + a2->prev = b2; + + bp->next = b2; + b2->prev = bp; + + return b2; +} + +// create a node and util::optionally link it with previous one (in a circular doubly linked list) +template template +typename Earcut::Node* +Earcut::insertNode(std::size_t i, const Point& pt, Node* last) { + Node* p = nodes.construct(static_cast(i), util::nth<0, Point>::get(pt), util::nth<1, Point>::get(pt)); + + if (!last) { + p->prev = p; + p->next = p; + + } else { + assert(last); + p->next = last->next; + p->prev = last; + last->next->prev = p; + last->next = p; + } + return p; +} + +template +void Earcut::removeNode(Node* p) { + p->next->prev = p->prev; + p->prev->next = p->next; + + if (p->prevZ) p->prevZ->nextZ = p->nextZ; + if (p->nextZ) p->nextZ->prevZ = p->prevZ; +} +} + +template +std::vector earcut(const Polygon& poly) { + mapbox::detail::Earcut earcut; + earcut(poly); + return std::move(earcut.indices); +} +} diff --git a/src/hwrenderer/data/flatvertices.cpp b/src/hwrenderer/data/flatvertices.cpp index c19169db3..3083cbc09 100644 --- a/src/hwrenderer/data/flatvertices.cpp +++ b/src/hwrenderer/data/flatvertices.cpp @@ -35,14 +35,6 @@ #include "hwrenderer/data/buffers.h" #include "hwrenderer/scene/hw_renderstate.h" -namespace VertexBuilder -{ - TArray BuildVertices(); -} - -using VertexContainers = TArray; - - //========================================================================== // // @@ -179,7 +171,7 @@ int FFlatVertexBuffer::CreateIndexedSectorVertices(sector_t *sec, const secplane vbo_shadowdata[vi + i].z += diff; } - int rt = ibo_data.size(); + int rt = ibo_data.Size(); ibo_data.Append(verts.indices); return rt; } @@ -190,20 +182,20 @@ int FFlatVertexBuffer::CreateIndexedSectorVertices(sector_t *sec, const secplane // //========================================================================== -int FFlatVertexBuffer::CreateIndexedVertices(int h, sector_t *sec, const secplane_t &plane, int floor, VertexContainers &verts) +int FFlatVertexBuffer::CreateIndexedVertices(int h, sector_t *sec, const secplane_t &plane, int floor, VertexContainer &verts) { sec->vboindex[h] = vbo_shadowdata.Size(); // First calculate the vertices for the sector itself sec->vboheight[h] = sec->GetPlaneTexZ(h); sec->ibocount = verts.indices.Size(); - sec->iboindex[h] = CreateIndexedSectorVertices(sec, plane, floor, verts[sec->Index()]); + sec->iboindex[h] = CreateIndexedSectorVertices(sec, plane, floor, verts); // Next are all sectors using this one as heightsec TArray &fakes = sec->e->FakeFloor.Sectors; for (unsigned g = 0; g < fakes.Size(); g++) { sector_t *fsec = fakes[g]; - fsec->iboindex[2 + h] = CreateIndexedSectorVertices(fsec, plane, false, verts[fsec->Index()]); + fsec->iboindex[2 + h] = CreateIndexedSectorVertices(fsec, plane, false, verts); } // and finally all attached 3D floors @@ -220,7 +212,7 @@ int FFlatVertexBuffer::CreateIndexedVertices(int h, sector_t *sec, const secplan if (dotop || dobottom) { - auto ndx = CreateIndexedSectorVertices(fsec, plane, false, verts[fsec->Index()]); + auto ndx = CreateIndexedSectorVertices(fsec, plane, false, verts); if (dotop) ffloor->top.vindex = ndx; if (dobottom) ffloor->bottom.vindex = ndx; } @@ -239,13 +231,32 @@ int FFlatVertexBuffer::CreateIndexedVertices(int h, sector_t *sec, const secplan void FFlatVertexBuffer::CreateIndexedFlatVertices() { - auto verts = VertexBuilder::BuildVertices(); + auto verts = BuildVertices(); + + int i = 0; + for (auto &vert : verts) + { + Printf(PRINT_LOG, "Sector %d\n", i); + Printf(PRINT_LOG, "%d vertices, %d indices\n", vert.vertices.Size(), vert.indices.Size()); + int j = 0; + for (auto &v : vert.vertices) + { + Printf(PRINT_LOG, " %d: (%2.3f, %2.3f)\n", j++, v.vertex->fX(), v.vertex->fY()); + } + for (unsigned i=0;i #include @@ -117,7 +118,7 @@ public: private: int CreateIndexedSectionVertices(subsector_t *sub, const secplane_t &plane, int floor, VertexContainer &cont); int CreateIndexedSectorVertices(sector_t *sec, const secplane_t &plane, int floor, VertexContainer &cont); - int CreateIndexedVertices(int h, sector_t *sec, const secplane_t &plane, int floor, VertexContainers &cont); + int CreateIndexedVertices(int h, sector_t *sec, const secplane_t &plane, int floor, VertexContainer &cont); void CreateIndexedFlatVertices(); void UpdatePlaneVertices(sector_t *sec, int plane); diff --git a/src/hwrenderer/data/hw_sections.cpp b/src/hwrenderer/data/hw_sections.cpp index 31c1986e6..4ad20d47a 100644 --- a/src/hwrenderer/data/hw_sections.cpp +++ b/src/hwrenderer/data/hw_sections.cpp @@ -47,16 +47,6 @@ template<> struct THashTraits int Compare(const DoublePoint &left, const DoublePoint &right) { return left != right; } }; -template<> struct THashTraits -{ - hash_t Hash(const FSectionVertex &key) - { - return (int)(((intptr_t)key.vertex) >> 4) ^ (key.qualifier << 16); - } - int Compare(const FSectionVertex &left, const FSectionVertex &right) { return left.vertex != right.vertex && left.qualifier != right.qualifier; } -}; - - struct WorkSectionLine { vertex_t *start; @@ -77,6 +67,7 @@ struct WorkSection bool hasminisegs; TArraysegments; TArray originalSides; // The segs will lose some of these while working on them. + TArray subsectors; }; struct TriangleWorkData @@ -107,7 +98,6 @@ class FSectionCreator bool verbose = false; TMap> subsectormap; - TArray> rawsections; // list of unprocessed subsectors. Sector and mapsection can be retrieved from the elements so aren't stored. TArray sections; TArray triangles; @@ -185,16 +175,18 @@ public: // //========================================================================== - void CompileSections() + TArray < TArray> CompileSections() { TMap>::Pair *pair; TMap>::Iterator it(subsectormap); + TArray> rawsections; // list of unprocessed subsectors. Sector and mapsection can be retrieved from the elements so aren't stored. while (it.NextPair(pair)) { - CompileSections(pair->Value); + CompileSections(pair->Value, rawsections); } subsectormap.Clear(); + return rawsections; } //========================================================================== @@ -203,7 +195,7 @@ public: // //========================================================================== - void CompileSections(TArray &list) + void CompileSections(TArray &list, TArray>&rawsections) { TArray sublist; TArray seglist; @@ -255,12 +247,15 @@ public: void MakeOutlines() { + auto rawsections = CompileSections(); TArray lineForSeg(level.segs.Size(), true); memset(lineForSeg.Data(), 0, sizeof(WorkSectionLine*) * level.segs.Size()); for (auto &list : rawsections) { MakeOutline(list, lineForSeg); } + rawsections.Clear(); + rawsections.ShrinkToFit(); // Assign partners after everything has been collected for (auto §ion : sections) @@ -403,8 +398,14 @@ public: *sectionlines[i] = { nullptr, nullptr, nullptr, nullptr, -1, (int)sections.Size(), nullptr }; } } - - sections.Push({ sector, mapsec, hasminisegs, std::move(sectionlines), std::move(foundsides) }); + sections.Reserve(1); + auto §ion = sections.Last(); + section.sectorindex = sector; + section.mapsection = mapsec; + section.hasminisegs = hasminisegs; + section.originalSides = std::move(foundsides); + section.segments = std::move(sectionlines); + section.subsectors = std::move(rawsection); } } @@ -547,8 +548,8 @@ public: { groupForSection[workingSet[0].index] = groups.Size(); Group g; + g.subsectors = std::move(workingSet[0].section->subsectors); g.groupedSections = std::move(workingSet); - g.subsectors = std::move(rawsections[workingSet[0].index]); groups.Push(std::move(g)); return; } @@ -558,7 +559,7 @@ public: build.Clear(); build.Push(workingSet[0]); groupForSection[workingSet[0].index] = groups.Size(); - subsectorcopy = std::move(rawsections[workingSet[0].index]); + subsectorcopy = std::move(workingSet[0].section->subsectors); workingSet.Delete(0); @@ -574,7 +575,7 @@ public: { build.Push(workingSet[i]); groupForSection[workingSet[i].index] = groups.Size(); - subsectorcopy.Append(rawsections[workingSet[i].index]); + subsectorcopy.Append(workingSet[i].section->subsectors); workingSet.Delete(i); i--; continue; @@ -585,7 +586,7 @@ public: { build.Push(workingSet[i]); groupForSection[workingSet[i].index] = groups.Size(); - subsectorcopy.Append(rawsections[workingSet[i].index]); + subsectorcopy.Append(workingSet[i].section->subsectors); workingSet.Delete(i); i--; continue; @@ -693,6 +694,8 @@ public: if (output.firstSectionForSectorPtr[dest.sector->Index()] == -1) output.firstSectionForSectorPtr[dest.sector->Index()] = curgroup; + output.numberOfSectionForSectorPtr[dest.sector->Index()]++; + for (auto &segment : group.segments) { // Use the indices calculated above to store these elements. @@ -711,13 +714,11 @@ public: output.allSides[numsides++] = &level.sides[pair->Key]; output.sectionForSidedefPtr[pair->Key] = curgroup; } - memcpy(&output.allSubsectors[numsubsectors], &group.subsectors[0], group.subsectors.Size() * sizeof(subsector_t*)); for (auto ssi : group.subsectors) { + output.allSubsectors[numsubsectors++] = &level.subsectors[ssi]; output.sectionForSubsectorPtr[ssi] = curgroup; } - numsubsectors += group.subsectors.Size(); - CreateVerticesForSection(output, dest, true); curgroup++; } } @@ -783,7 +784,6 @@ void CreateSections(FSectionContainer &container) { FSectionCreator creat; creat.GroupSubsectors(); - creat.CompileSections(); creat.MakeOutlines(); creat.MergeLines(); creat.FindOuterLoops(); @@ -797,183 +797,3 @@ CCMD(printsections) } - -//============================================================================= -// -// One sector's vertex data. -// -//============================================================================= - -struct VertexContainer -{ - TArray vertices; - TMap vertexmap; - bool perSubsector = false; - - TArray indices; - - uint32_t AddVertex(FSectionVertex *vert) - { - auto check = vertexmap.CheckKey(vert); - if (check != nullptr) return *check; - auto index = vertices.Push(*vert); - vertexmap[vert] = index; - return index; - } - - uint32_t AddVertex(vertex_t *vert, int qualifier) - { - FSectionVertex vertx = { vert, qualifier}; - return AddVertex(&vertx); - } - - uint32_t GetIndex(FSectionVertex *vert) - { - auto check = vertexmap.CheckKey(vert); - if (check != nullptr) return *check; - return ~0u; - } - - uint32_t GetIndex(vertex_t *vert, int qualifier) - { - FSectionVertex vertx = { vert, qualifier}; - return GetIndex(&vertx); - } - - uint32_t AddIndexForVertex(FSectionVertex *vert) - { - return indices.Push(GetIndex(vert)); - } - - uint32_t AddIndexForVertex(vertex_t *vert, int qualifier) - { - return indices.Push(GetIndex(vert, qualifier)); - } - - uint32_t AddIndex(uint32_t indx) - { - return indices.Push(indx); - } -}; - - -//============================================================================= -// -// Creates vertex meshes for sector planes -// -//============================================================================= - -namespace VertexBuilder -{ - - //============================================================================= - // - // - // - //============================================================================= - - static void CreateVerticesForSubsector(subsector_t *sub, VertexContainer &gen, int qualifier) - { - if (sub->numlines < 3) return; - - uint32_t startindex = gen.indices.Size(); - - if ((sub->flags & SSECF_HOLE) && sub->numlines > 3) - { - // Hole filling "subsectors" are not necessarily convex so they require real triangulation. - // These things are extremely rare so performance is secondary here. - - using Point = std::pair; - std::vector> polygon; - std::vector *curPoly; - - for (unsigned i = 0; i < sub->numlines; i++) - { - polygon.resize(1); - curPoly = &polygon.back(); - curPoly->push_back({ sub->firstline[i].v1->fX(), sub->firstline[i].v1->fY() }); - } - auto indices = mapbox::earcut(polygon); - for (auto vti : indices) - { - gen.AddIndexForVertex(sub->firstline[vti].v1, qualifier); - } - } - else - { - int firstndx = gen.GetIndex(sub->firstline[0].v1, qualifier); - int secondndx = gen.GetIndex(sub->firstline[1].v1, qualifier); - for (unsigned int k = 2; k < sub->numlines; k++) - { - gen.AddIndex(firstndx); - gen.AddIndex(secondndx); - auto ndx = gen.GetIndex(sub->firstline[k].v1, qualifier); - gen.AddIndex(ndx); - secondndx = ndx; - } - } - } - - //============================================================================= - // - // - // - //============================================================================= - - static void TriangulateSection(FSection §, VertexContainer &gen, int qualifier) - { - if (sect.segments.Size() < 3) return; - - // todo - } - - //============================================================================= - // - // - // - //============================================================================= - - - static void CreateVerticesForSection(FSection §ion, VertexContainer &gen, bool useSubsectors) - { - section.vertexindex = gen.indices.Size(); - - if (useSubsectors) - { - for (auto sub : section.subsectors) - { - CreateVerticesForSubsector(sub, gen, -1); - } - } - else - { - TriangulateSection(section, gen, -1); - } - section.vertexcount = gen.indices.Size() - section.vertexindex; - } - - //========================================================================== - // - // Creates the vertices for one plane in one subsector - // - //========================================================================== - - static void CreateVerticesForSector(sector_t *sec, VertexContainer gen) - { - auto sections = level.sections.SectionsForSector(sec); - for (auto §ion :sections) - { - CreateVerticesForSection( section, gen, true); - } - } - - TArray BuildVertices() - { - TArray verticesPerSector(level.sectors.Size(), true); - for (unsigned i=0; inumlines < 3) return; + + uint32_t startindex = gen.indices.Size(); + + if ((sub->flags & SSECF_HOLE) && sub->numlines > 3) + { + // Hole filling "subsectors" are not necessarily convex so they require real triangulation. + // These things are extremely rare so performance is secondary here. + + using Point = std::pair; + std::vector> polygon; + std::vector *curPoly; + + for (unsigned i = 0; i < sub->numlines; i++) + { + polygon.resize(1); + curPoly = &polygon.back(); + curPoly->push_back({ sub->firstline[i].v1->fX(), sub->firstline[i].v1->fY() }); + } + auto indices = mapbox::earcut(polygon); + for (auto vti : indices) + { + gen.AddIndexForVertex(sub->firstline[vti].v1, qualifier); + } + } + else + { + int firstndx = gen.AddVertex(sub->firstline[0].v1, qualifier); + int secondndx = gen.AddVertex(sub->firstline[1].v1, qualifier); + for (unsigned int k = 2; k < sub->numlines; k++) + { + gen.AddIndex(firstndx); + gen.AddIndex(secondndx); + auto ndx = gen.AddVertex(sub->firstline[k].v1, qualifier); + gen.AddIndex(ndx); + secondndx = ndx; + } + } +} + +//============================================================================= +// +// +// +//============================================================================= + +static void TriangulateSection(FSection §, VertexContainer &gen, int qualifier) +{ + if (sect.segments.Size() < 3) return; + + // todo +} + +//============================================================================= +// +// +// +//============================================================================= + + +static void CreateVerticesForSection(FSection §ion, VertexContainer &gen, bool useSubsectors) +{ + section.vertexindex = gen.indices.Size(); + + if (useSubsectors) + { + for (auto sub : section.subsectors) + { + CreateVerticesForSubsector(sub, gen, -1); + } + } + else + { + TriangulateSection(section, gen, -1); + } + section.vertexcount = gen.indices.Size() - section.vertexindex; +} + +//========================================================================== +// +// Creates the vertices for one plane in one subsector +// +//========================================================================== + +static void CreateVerticesForSector(sector_t *sec, VertexContainer &gen) +{ + auto sections = level.sections.SectionsForSector(sec); + for (auto §ion :sections) + { + CreateVerticesForSection( section, gen, true); + } +} + + +TArray BuildVertices() +{ + TArray verticesPerSector(level.sectors.Size(), true); + for (unsigned i=0; i struct THashTraits +{ + hash_t Hash(const FQualifiedVertex &key) + { + return (int)(((intptr_t)key.vertex) >> 4) ^ (key.qualifier << 16); + } + int Compare(const FQualifiedVertex &left, const FQualifiedVertex &right) { return left.vertex != right.vertex || left.qualifier != right.qualifier; } +}; + +//============================================================================= +// +// One sector's vertex data. +// +//============================================================================= + +struct VertexContainer +{ + TArray vertices; + TMap vertexmap; + bool perSubsector = false; + + TArray indices; + + uint32_t AddVertex(FQualifiedVertex *vert) + { + auto check = vertexmap.CheckKey(*vert); + if (check != nullptr) return *check; + auto index = vertices.Push(*vert); + vertexmap[*vert] = index; + return index; + } + + uint32_t AddVertex(vertex_t *vert, int qualifier) + { + FQualifiedVertex vertx = { vert, qualifier}; + return AddVertex(&vertx); + } + + uint32_t AddIndexForVertex(FQualifiedVertex *vert) + { + return indices.Push(AddVertex(vert)); + } + + uint32_t AddIndexForVertex(vertex_t *vert, int qualifier) + { + return indices.Push(AddVertex(vert, qualifier)); + } + + uint32_t AddIndex(uint32_t indx) + { + return indices.Push(indx); + } +}; + +using VertexContainers = TArray; + +VertexContainers BuildVertices(); + + diff --git a/src/p_setup.cpp b/src/p_setup.cpp index a204144ef..15cbb0b54 100644 --- a/src/p_setup.cpp +++ b/src/p_setup.cpp @@ -4067,6 +4067,8 @@ void P_SetupLevel (const char *lumpname, int position, bool newGame) for (i = 0; i < BODYQUESIZE; i++) bodyque[i] = NULL; + CreateSections(level.sections); + if (!buildmap) { // [RH] Spawn slope creating things first. diff --git a/src/r_data/renderinfo.cpp b/src/r_data/renderinfo.cpp index f50c32d51..bf59ec0c0 100644 --- a/src/r_data/renderinfo.cpp +++ b/src/r_data/renderinfo.cpp @@ -532,8 +532,6 @@ static void PrepareSegs() void InitRenderInfo() { - CreateSections(level.sections); - PrepareSegs(); PrepareSectorData(); InitVertexData(); diff --git a/src/tarray.h b/src/tarray.h index 79b8853bd..4a0d1570f 100644 --- a/src/tarray.h +++ b/src/tarray.h @@ -162,6 +162,10 @@ public: Most = max; Count = reserve? max : 0; Array = (T *)M_Malloc (sizeof(T)*max); + if (reserve) + { + for (unsigned i = 0; i < Count; i++) ::new(&Array[i]) T(); + } } TArray (const TArray &other) { From 50bd9c35944c34612b4eac2f43bd0e9abf6a882b Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Mon, 5 Nov 2018 21:29:57 +0100 Subject: [PATCH 06/16] - flatvertex generation is working again. --- src/hwrenderer/data/flatvertices.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/hwrenderer/data/flatvertices.cpp b/src/hwrenderer/data/flatvertices.cpp index 3083cbc09..b95e66bdf 100644 --- a/src/hwrenderer/data/flatvertices.cpp +++ b/src/hwrenderer/data/flatvertices.cpp @@ -159,7 +159,7 @@ static F3DFloor *Find3DFloor(sector_t *target, sector_t *model) int FFlatVertexBuffer::CreateIndexedSectorVertices(sector_t *sec, const secplane_t &plane, int floor, VertexContainer &verts) { - int vi = vbo_shadowdata.Reserve(verts.vertices.Size()); + unsigned vi = vbo_shadowdata.Reserve(verts.vertices.Size()); float diff; // Create the actual vertices. @@ -171,9 +171,12 @@ int FFlatVertexBuffer::CreateIndexedSectorVertices(sector_t *sec, const secplane vbo_shadowdata[vi + i].z += diff; } - int rt = ibo_data.Size(); - ibo_data.Append(verts.indices); - return rt; + unsigned rt = ibo_data.Reserve(verts.indices.Size()); + for (unsigned i = 0; i < verts.indices.Size(); i++) + { + ibo_data[rt + i] = vi + verts.indices[i]; + } + return (int)rt; } //========================================================================== From 375dd7e28fbf1cc6f365755784c01e25547eb03f Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Mon, 5 Nov 2018 22:14:18 +0100 Subject: [PATCH 07/16] - the sections are now being used as the smallest element to draw flat planes. This also removes one piece of code that was used to cope with the missing clip planes on old ATI cards, so support for those will most likely have to be dropped in the near future. --- src/hwrenderer/scene/hw_drawinfo.h | 5 ---- src/hwrenderer/scene/hw_flats.cpp | 34 +++++-------------------- src/hwrenderer/scene/hw_renderhacks.cpp | 2 -- src/hwrenderer/scene/hw_skydome.cpp | 5 ++++ src/hwrenderer/scene/hw_skydome.h | 1 + 5 files changed, 12 insertions(+), 35 deletions(-) diff --git a/src/hwrenderer/scene/hw_drawinfo.h b/src/hwrenderer/scene/hw_drawinfo.h index c3a9ddfb3..537c2a202 100644 --- a/src/hwrenderer/scene/hw_drawinfo.h +++ b/src/hwrenderer/scene/hw_drawinfo.h @@ -256,11 +256,6 @@ public: VPUniforms.mClipHeight = 0; } - bool ClipLineShouldBeActive() - { - return (screen->hwcaps & RFL_NO_CLIP_PLANES) && VPUniforms.mClipLine.X > -1000000.f; - } - HWPortal * FindPortal(const void * src); void RenderBSPNode(void *node); void RenderBSP(void *node); diff --git a/src/hwrenderer/scene/hw_flats.cpp b/src/hwrenderer/scene/hw_flats.cpp index db9edfccb..2278bbd58 100644 --- a/src/hwrenderer/scene/hw_flats.cpp +++ b/src/hwrenderer/scene/hw_flats.cpp @@ -182,8 +182,6 @@ void GLFlat::SetupLights(HWDrawInfo *di, FLightNode * node, FDynLightData &light void GLFlat::DrawSubsectors(HWDrawInfo *di, FRenderState &state) { - auto vcount = sector->ibocount; - if (level.HasDynamicLights && screen->BuffersArePersistent()) { SetupLights(di, sector->lighthead, lightdata, sector->PortalGroup); @@ -191,34 +189,13 @@ void GLFlat::DrawSubsectors(HWDrawInfo *di, FRenderState &state) state.SetLightIndex(dynlightindex); - if (vcount > 0 && !di->ClipLineShouldBeActive()) - { - state.DrawIndexed(DT_Triangles, iboindex, vcount); - flatvertices += vcount; - flatprimitives++; - } - else - { - /* - int index = iboindex; - bool applied = false; - for (int i = 0; i < sector->subsectorcount; i++) - { - subsector_t * sub = sector->subsectors[i]; - if (sub->numlines <= 2) continue; + state.DrawIndexed(DT_Triangles, iboindex + section->vertexindex, section->vertexcount); + flatvertices += section->vertexcount; + flatprimitives++; - if (di->ss_renderflags[sub->Index()] & renderflags) - { - state.DrawIndexed(DT_Triangles, index, (sub->numlines - 2) * 3, !applied); - applied = true; - flatvertices += sub->numlines; - flatprimitives++; - } - index += (sub->numlines - 2) * 3; - } - */ - } +#if 0 + //Temporarily disabled until the render hack code can be redone and refactored into its own draw elements if (!(renderflags&SSRF_RENDER3DPLANES)) { // Draw the subsectors assigned to it due to missing textures @@ -282,6 +259,7 @@ void GLFlat::DrawSubsectors(HWDrawInfo *di, FRenderState &state) } } +#endif } //========================================================================== diff --git a/src/hwrenderer/scene/hw_renderhacks.cpp b/src/hwrenderer/scene/hw_renderhacks.cpp index afc8aaab8..5fbc96aea 100644 --- a/src/hwrenderer/scene/hw_renderhacks.cpp +++ b/src/hwrenderer/scene/hw_renderhacks.cpp @@ -1297,7 +1297,6 @@ void HWDrawInfo::ProcessSectorStacks(area_t in_area) { subsector_t *sub = HandledSubsectors[j]; ss_renderflags[sub->Index()] &= ~SSRF_RENDERCEILING; - sub->sector->ibocount = -1; // cannot render this sector in one go. if (sub->portalcoverage[sector_t::ceiling].subsectors == NULL) { @@ -1343,7 +1342,6 @@ void HWDrawInfo::ProcessSectorStacks(area_t in_area) { subsector_t *sub = HandledSubsectors[j]; ss_renderflags[sub->Index()] &= ~SSRF_RENDERFLOOR; - sub->sector->ibocount = -1; // cannot render this sector in one go. if (sub->portalcoverage[sector_t::floor].subsectors == NULL) { diff --git a/src/hwrenderer/scene/hw_skydome.cpp b/src/hwrenderer/scene/hw_skydome.cpp index 7184b7bad..27342cf7d 100644 --- a/src/hwrenderer/scene/hw_skydome.cpp +++ b/src/hwrenderer/scene/hw_skydome.cpp @@ -96,6 +96,11 @@ FSkyVertexBuffer::FSkyVertexBuffer() mVertexBuffer->SetData(mVertices.Size() * sizeof(FSkyVertex), &mVertices[0], true); } +FSkyVertexBuffer::~FSkyVertexBuffer() +{ + delete mVertexBuffer; +} + //----------------------------------------------------------------------------- // // diff --git a/src/hwrenderer/scene/hw_skydome.h b/src/hwrenderer/scene/hw_skydome.h index b441bc8ca..ed130084c 100644 --- a/src/hwrenderer/scene/hw_skydome.h +++ b/src/hwrenderer/scene/hw_skydome.h @@ -67,6 +67,7 @@ public: public: FSkyVertexBuffer(); + ~FSkyVertexBuffer(); void SetupMatrices(FMaterial *tex, float x_offset, float y_offset, bool mirror, int mode, VSMatrix &modelmatrix, VSMatrix &textureMatrix); std::pair GetBufferObjects() const { From 9ddca3c3a923174a126e1df3c7a5f3170ef3544b Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Mon, 5 Nov 2018 22:35:24 +0100 Subject: [PATCH 08/16] - removed the subsector light lists as a preparation step to move over the light traversal code to use sections instead of subsectors. --- src/g_shared/a_dynlight.cpp | 52 ++----------------------- src/g_shared/a_dynlight.h | 1 - src/hwrenderer/scene/hw_renderhacks.cpp | 2 +- src/hwrenderer/scene/hw_spritelight.cpp | 6 +-- src/hwrenderer/scene/hw_walls.cpp | 2 +- src/polyrenderer/scene/poly_model.cpp | 2 +- src/polyrenderer/scene/poly_plane.cpp | 2 +- src/r_defs.h | 1 - src/swrenderer/things/r_model.cpp | 2 +- 9 files changed, 12 insertions(+), 58 deletions(-) diff --git a/src/g_shared/a_dynlight.cpp b/src/g_shared/a_dynlight.cpp index 98d57c4ab..b6e83abdc 100644 --- a/src/g_shared/a_dynlight.cpp +++ b/src/g_shared/a_dynlight.cpp @@ -574,7 +574,7 @@ void ADynamicLight::CollectWithinRadius(const DVector3 &opos, subsector_t *subSe { subSec = collected_ss[i].sub; - touching_subsectors = AddLightNode(&subSec->lighthead, subSec, this, touching_subsectors); + //touching_subsectors = AddLightNode(&subSec->lighthead, subSec, this, touching_subsectors); if (subSec->sector->validcount != ::validcount) { touching_sector = AddLightNode(&subSec->render_sector->lighthead, subSec->sector, this, touching_sector); @@ -682,12 +682,6 @@ void ADynamicLight::LinkLight() { node->lightsource = NULL; node = node->nextTarget; - } - node = touching_subsectors; - while (node) - { - node->lightsource = NULL; - node = node->nextTarget; } node = touching_sector; while (node) @@ -719,17 +713,6 @@ void ADynamicLight::LinkLight() node = node->nextTarget; } - node = touching_subsectors; - while (node) - { - if (node->lightsource == NULL) - { - node = DeleteLightNode(node); - } - else - node = node->nextTarget; - } - node = touching_sector; while (node) { @@ -763,7 +746,6 @@ void ADynamicLight::UnlinkLight () } } while (touching_sides) touching_sides = DeleteLightNode(touching_sides); - while (touching_subsectors) touching_subsectors = DeleteLightNode(touching_subsectors); while (touching_sector) touching_sector = DeleteLightNode(touching_sector); shadowmapped = false; } @@ -918,7 +900,7 @@ void AActor::RecreateAllAttachedLights() CCMD(listlights) { - int walls, sectors, subsecs; + int walls, sectors; int allwalls=0, allsectors=0, allsubsecs = 0; int i=0, shadowcount = 0; ADynamicLight * dl; @@ -928,7 +910,6 @@ CCMD(listlights) { walls=0; sectors=0; - subsecs = 0; Printf("%s at (%f, %f, %f), color = 0x%02x%02x%02x, radius = %f %s %s", dl->target? dl->target->GetClass()->TypeName.GetChars() : dl->GetClass()->TypeName.GetChars(), dl->X(), dl->Y(), dl->Z(), dl->args[LIGHT_RED], @@ -954,14 +935,6 @@ CCMD(listlights) node = node->nextTarget; } - node=dl->touching_subsectors; - - while (node) - { - allsubsecs++; - subsecs++; - node = node->nextTarget; - } node = dl->touching_sector; @@ -971,27 +944,10 @@ CCMD(listlights) sectors++; node = node->nextTarget; } - Printf("- %d walls, %d subsectors, %d sectors\n", walls, subsecs, sectors); + Printf("- %d walls, %d sectors\n", walls, sectors); } - Printf("%i dynamic lights, %d shadowmapped, %d walls, %d subsectors, %d sectors\n\n\n", i, shadowcount, allwalls, allsubsecs, allsectors); -} - -CCMD(listsublights) -{ - for(auto &sub : level.subsectors) - { - int lights = 0; - - FLightNode * node = sub.lighthead; - while (node != NULL) - { - lights++; - node = node->nextLight; - } - - Printf(PRINT_LOG, "Subsector %d - %d lights\n", sub.Index(), lights); - } + Printf("%i dynamic lights, %d shadowmapped, %d walls, %d sectors\n\n\n", i, shadowcount, allwalls, allsectors); } diff --git a/src/g_shared/a_dynlight.h b/src/g_shared/a_dynlight.h index fa9d5840e..671c7812f 100644 --- a/src/g_shared/a_dynlight.h +++ b/src/g_shared/a_dynlight.h @@ -206,7 +206,6 @@ public: bool IsSpot() { return !!(lightflags & LF_SPOT); } FState *targetState; FLightNode * touching_sides; - FLightNode * touching_subsectors; FLightNode * touching_sector; private: diff --git a/src/hwrenderer/scene/hw_renderhacks.cpp b/src/hwrenderer/scene/hw_renderhacks.cpp index 5fbc96aea..05770125d 100644 --- a/src/hwrenderer/scene/hw_renderhacks.cpp +++ b/src/hwrenderer/scene/hw_renderhacks.cpp @@ -54,7 +54,7 @@ int HWDrawInfo::SetupLightsForOtherPlane(subsector_t * sub, FDynLightData &light if (level.HasDynamicLights && !isFullbrightScene()) { Plane p; - FLightNode * node = sub->lighthead; + FLightNode * node = sub->sector->lighthead; lightdata.Clear(); while (node) diff --git a/src/hwrenderer/scene/hw_spritelight.cpp b/src/hwrenderer/scene/hw_spritelight.cpp index 9ce11f859..3b5a0c1d8 100644 --- a/src/hwrenderer/scene/hw_spritelight.cpp +++ b/src/hwrenderer/scene/hw_spritelight.cpp @@ -131,11 +131,11 @@ void HWDrawInfo::GetDynSpriteLight(AActor *thing, particle_t *particle, float *o { if (thing != NULL) { - GetDynSpriteLight(thing, (float)thing->X(), (float)thing->Y(), (float)thing->Center(), thing->subsector->lighthead, thing->Sector->PortalGroup, out); + GetDynSpriteLight(thing, (float)thing->X(), (float)thing->Y(), (float)thing->Center(), thing->Sector->lighthead, thing->Sector->PortalGroup, out); } else if (particle != NULL) { - GetDynSpriteLight(NULL, (float)particle->Pos.X, (float)particle->Pos.Y, (float)particle->Pos.Z, particle->subsector->lighthead, particle->subsector->sector->PortalGroup, out); + GetDynSpriteLight(NULL, (float)particle->Pos.X, (float)particle->Pos.Y, (float)particle->Pos.Z, particle->subsector->sector->lighthead, particle->subsector->sector->PortalGroup, out); } } @@ -160,7 +160,7 @@ void hw_GetDynModelLight(AActor *self, FDynLightData &modellightdata) BSPWalkCircle(x, y, radiusSquared, [&](subsector_t *subsector) // Iterate through all subsectors potentially touched by actor { - FLightNode * node = subsector->lighthead; + FLightNode * node = subsector->sector->lighthead; while (node) // check all lights touching a subsector { ADynamicLight *light = node->lightsource; diff --git a/src/hwrenderer/scene/hw_walls.cpp b/src/hwrenderer/scene/hw_walls.cpp index 8c5e90d87..b782c54e9 100644 --- a/src/hwrenderer/scene/hw_walls.cpp +++ b/src/hwrenderer/scene/hw_walls.cpp @@ -302,7 +302,7 @@ void GLWall::SetupLights(HWDrawInfo *di, FDynLightData &lightdata) else if (sub) { // Polobject segs cannot be checked per sidedef so use the subsector instead. - node = sub->lighthead; + node = sub->sector->lighthead; } else node = NULL; diff --git a/src/polyrenderer/scene/poly_model.cpp b/src/polyrenderer/scene/poly_model.cpp index 39695c016..78520826f 100644 --- a/src/polyrenderer/scene/poly_model.cpp +++ b/src/polyrenderer/scene/poly_model.cpp @@ -70,7 +70,7 @@ void PolyModelRenderer::AddLights(AActor *actor) BSPWalkCircle(x, y, radiusSquared, [&](subsector_t *subsector) // Iterate through all subsectors potentially touched by actor { - FLightNode * node = subsector->lighthead; + FLightNode * node = subsector->sector->lighthead; while (node) // check all lights touching a subsector { ADynamicLight *light = node->lightsource; diff --git a/src/polyrenderer/scene/poly_plane.cpp b/src/polyrenderer/scene/poly_plane.cpp index 08a8897e7..076a334f9 100644 --- a/src/polyrenderer/scene/poly_plane.cpp +++ b/src/polyrenderer/scene/poly_plane.cpp @@ -275,7 +275,7 @@ void RenderPolyPlane::SetDynLights(PolyRenderThread *thread, PolyDrawArgs &args, return; } - FLightNode *light_list = sub->lighthead; + FLightNode *light_list = sub->sector->lighthead; auto cameraLight = PolyCameraLight::Instance(); if ((cameraLight->FixedLightLevel() >= 0) || (cameraLight->FixedColormap() != nullptr)) diff --git a/src/r_defs.h b/src/r_defs.h index 4bccef526..9f1e7c265 100644 --- a/src/r_defs.h +++ b/src/r_defs.h @@ -1460,7 +1460,6 @@ struct subsector_t uint16_t sectorindex; // subsector related GL data - FLightNode * lighthead; // Light nodes (blended and additive) int validcount; short mapsection; char hacked; // 1: is part of a render hack diff --git a/src/swrenderer/things/r_model.cpp b/src/swrenderer/things/r_model.cpp index 1f02e0b6c..a3ce1a5bb 100644 --- a/src/swrenderer/things/r_model.cpp +++ b/src/swrenderer/things/r_model.cpp @@ -111,7 +111,7 @@ namespace swrenderer BSPWalkCircle(x, y, radiusSquared, [&](subsector_t *subsector) // Iterate through all subsectors potentially touched by actor { - FLightNode * node = subsector->lighthead; + FLightNode * node = subsector->sector->lighthead; while (node) // check all lights touching a subsector { ADynamicLight *light = node->lightsource; From ba66c0c889dc6bdd687b98775e7da015f2447add Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Tue, 6 Nov 2018 00:13:23 +0100 Subject: [PATCH 09/16] - changed dynamic light traversal to use sections instead of the subsectors. This is mostly complete, except for handling intra-section sidedefs. --- src/g_shared/a_dynlight.cpp | 155 ++++++++++++------------ src/g_shared/a_dynlight.h | 5 +- src/hwrenderer/data/hw_sections.cpp | 11 +- src/hwrenderer/data/hw_sections.h | 18 +-- src/hwrenderer/scene/hw_bsp.cpp | 7 +- src/hwrenderer/scene/hw_flats.cpp | 4 +- src/hwrenderer/scene/hw_renderhacks.cpp | 3 +- src/hwrenderer/scene/hw_spritelight.cpp | 9 +- src/hwrenderer/scene/hw_walls.cpp | 2 +- src/p_maputl.cpp | 2 +- src/polyrenderer/scene/poly_model.cpp | 2 +- src/polyrenderer/scene/poly_plane.cpp | 2 +- src/polyrenderer/scene/poly_sprite.cpp | 2 +- src/r_defs.h | 6 +- src/r_utility.cpp | 1 + src/r_utility.h | 1 + src/swrenderer/scene/r_opaque_pass.cpp | 8 +- src/swrenderer/things/r_model.cpp | 2 +- src/swrenderer/things/r_sprite.cpp | 3 +- src/swrenderer/things/r_visiblesprite.h | 1 + 20 files changed, 119 insertions(+), 125 deletions(-) diff --git a/src/g_shared/a_dynlight.cpp b/src/g_shared/a_dynlight.cpp index b6e83abdc..e8dc871bf 100644 --- a/src/g_shared/a_dynlight.cpp +++ b/src/g_shared/a_dynlight.cpp @@ -80,7 +80,7 @@ DEFINE_CLASS_PROPERTY(type, S, DynamicLight) { PROP_STRING_PARM(str, 0); static const char * ltype_names[]={ - "Point","Pulse","Flicker","Sector","RandomFlicker", "ColorPulse", "ColorFlicker", "RandomColorFlicker", NULL}; + "Point","Pulse","Flicker","Sector","RandomFlicker", "ColorPulse", "ColorFlicker", "RandomColorFlicker", nullptr}; static const int ltype_values[]={ PointLight, PulseLight, FlickerLight, SectorLight, RandomFlickerLight, ColorPulseLight, ColorFlickerLight, RandomColorFlickerLight }; @@ -182,7 +182,7 @@ void ADynamicLight::PostBeginPlay() if (!(SpawnFlags & MTF_DORMANT)) { - Activate (NULL); + Activate (nullptr); } subsector = R_PointInSubsector(Pos()); @@ -430,14 +430,14 @@ void ADynamicLight::SetOffset(const DVector3 &pos) //========================================================================== // // The target pointer in dynamic lights should never be substituted unless -// notOld is NULL (which indicates that the object was destroyed by force.) +// notOld is nullptr (which indicates that the object was destroyed by force.) // //========================================================================== size_t ADynamicLight::PointerSubstitution (DObject *old, DObject *notOld) { AActor *saved_target = target; size_t ret = Super::PointerSubstitution(old, notOld); - if (notOld != NULL) target = saved_target; + if (notOld != nullptr) target = saved_target; return ret; } @@ -494,7 +494,7 @@ FLightNode * AddLightNode(FLightNode ** thread, void * linkto, ADynamicLight * l // // P_DelSecnode() deletes a sector node from the list of // sectors this object appears in. Returns a pointer to the next node -// on the linked list, or NULL. +// on the linked list, or nullptr. // //============================================================================= @@ -516,7 +516,7 @@ static FLightNode * DeleteLightNode(FLightNode * node) delete node; return(tn); } - return(NULL); + return(nullptr); } // phares 3/13/98 @@ -527,20 +527,20 @@ static FLightNode * DeleteLightNode(FLightNode * node) // //========================================================================== -double ADynamicLight::DistToSeg(const DVector3 &pos, seg_t *seg) +double ADynamicLight::DistToSeg(const DVector3 &pos, FSectionLine *segment) { double u, px, py; - double seg_dx = seg->v2->fX() - seg->v1->fX(); - double seg_dy = seg->v2->fY() - seg->v1->fY(); + double seg_dx = segment->end->fX() - segment->start->fX(); + double seg_dy = segment->end->fY() - segment->start->fY(); double seg_length_sq = seg_dx * seg_dx + seg_dy * seg_dy; - u = (((pos.X - seg->v1->fX()) * seg_dx) + (pos.Y - seg->v1->fY()) * seg_dy) / seg_length_sq; + u = (((pos.X - segment->start->fX()) * seg_dx) + (pos.Y - segment->start->fY()) * seg_dy) / seg_length_sq; if (u < 0.) u = 0.; // clamp the test point to the line segment else if (u > 1.) u = 1.; - px = seg->v1->fX() + (u * seg_dx); - py = seg->v1->fY() + (u * seg_dy); + px = segment->start->fX() + (u * seg_dx); + py = segment->start->fY() + (u * seg_dy); px -= pos.X; py -= pos.Y; @@ -557,108 +557,110 @@ double ADynamicLight::DistToSeg(const DVector3 &pos, seg_t *seg) //========================================================================== struct LightLinkEntry { - subsector_t *sub; + FSection *sect; DVector3 pos; }; static TArray collected_ss; -void ADynamicLight::CollectWithinRadius(const DVector3 &opos, subsector_t *subSec, float radius) +void ADynamicLight::CollectWithinRadius(const DVector3 &opos, FSection *section, float radius) { - if (!subSec) return; + if (!section) return; collected_ss.Clear(); - collected_ss.Push({ subSec, opos }); - subSec->validcount = ::validcount; + collected_ss.Push({ section, opos }); + section->validcount = dl_validcount; bool hitonesidedback = false; for (unsigned i = 0; i < collected_ss.Size(); i++) { - subSec = collected_ss[i].sub; + section = collected_ss[i].sect; - //touching_subsectors = AddLightNode(&subSec->lighthead, subSec, this, touching_subsectors); - if (subSec->sector->validcount != ::validcount) - { - touching_sector = AddLightNode(&subSec->render_sector->lighthead, subSec->sector, this, touching_sector); - subSec->sector->validcount = ::validcount; - } + touching_sector = AddLightNode(§ion->lighthead, section, this, touching_sector); - for (unsigned int j = 0; j < subSec->numlines; ++j) + for (auto &segment : section->segments) { auto &pos = collected_ss[i].pos; - seg_t *seg = subSec->firstline + j; // check distance from x/y to seg and if within radius add this seg and, if present the opposing subsector (lather/rinse/repeat) // If out of range we do not need to bother with this seg. - if (DistToSeg(pos, seg) <= radius) + if (DistToSeg(pos, &segment) <= radius) { - if (seg->sidedef && seg->linedef && seg->linedef->validcount != ::validcount) + if (segment.sidedef) { - // light is in front of the seg - if ((pos.Y - seg->v1->fY()) * (seg->v2->fX() - seg->v1->fX()) + (seg->v1->fX() - pos.X) * (seg->v2->fY() - seg->v1->fY()) <= 0) + auto sidedef = segment.sidedef; + auto linedef = sidedef->linedef; + if (linedef && linedef->validcount != ::validcount) { - seg->linedef->validcount = validcount; - touching_sides = AddLightNode(&seg->sidedef->lighthead, seg->sidedef, this, touching_sides); - } - else if (seg->linedef->sidedef[0] == seg->sidedef && seg->linedef->sidedef[1] == nullptr) - { - hitonesidedback = true; - } - } - if (seg->linedef) - { - FLinePortal *port = seg->linedef->getPortal(); - if (port && port->mType == PORTT_LINKED) - { - line_t *other = port->mDestination; - if (other->validcount != ::validcount) + // light is in front of the seg + if ((pos.Y - segment.start->fY()) * (segment.end->fX() - segment.start->fX()) + (segment.start->fX() - pos.X) * (segment.end->fY() - segment.start->fY()) <= 0) { - subsector_t *othersub = R_PointInSubsector(other->v1->fPos() + other->Delta() / 2); - if (othersub->validcount != ::validcount) + linedef->validcount = ::validcount; + touching_sides = AddLightNode(&sidedef->lighthead, sidedef, this, touching_sides); + } + else if (linedef->sidedef[0] == sidedef && linedef->sidedef[1] == nullptr) + { + hitonesidedback = true; + } + } + if (linedef) + { + FLinePortal *port = linedef->getPortal(); + if (port && port->mType == PORTT_LINKED) + { + line_t *other = port->mDestination; + if (other->validcount != ::validcount) { - othersub->validcount = ::validcount; - collected_ss.Push({ othersub, PosRelative(other) }); + subsector_t *othersub = R_PointInSubsector(other->v1->fPos() + other->Delta() / 2); + FSection *othersect = othersub->section; + if (othersect->validcount != ::validcount) + { + othersect->validcount = ::validcount; + collected_ss.Push({ othersect, PosRelative(other) }); + } } } } } - seg_t *partner = seg->PartnerSeg; + auto partner = segment.partner; if (partner) { - subsector_t *sub = partner->Subsector; - if (sub != NULL && sub->validcount != ::validcount) + FSection *sect = partner->section; + if (sect != nullptr && sect->validcount != dl_validcount) { - sub->validcount = ::validcount; - collected_ss.Push({ sub, pos }); + sect->validcount = dl_validcount; + collected_ss.Push({ sect, pos }); } } } } - sector_t *sec = subSec->sector; + sector_t *sec = section->sector; if (!sec->PortalBlocksSight(sector_t::ceiling)) { - line_t *other = subSec->firstline->linedef; + line_t *other = section->segments[0].sidedef->linedef; if (sec->GetPortalPlaneZ(sector_t::ceiling) < Z() + radius) { DVector2 refpos = other->v1->fPos() + other->Delta() / 2 + sec->GetPortalDisplacement(sector_t::ceiling); subsector_t *othersub = R_PointInSubsector(refpos); - if (othersub->validcount != ::validcount) + FSection *othersect = othersub->section; + if (othersect->validcount != dl_validcount) { - othersub->validcount = ::validcount; - collected_ss.Push({ othersub, PosRelative(othersub->sector) }); + othersect->validcount = dl_validcount; + collected_ss.Push({ othersect, PosRelative(othersub->sector) }); } } } if (!sec->PortalBlocksSight(sector_t::floor)) { - line_t *other = subSec->firstline->linedef; + line_t *other = section->segments[0].sidedef->linedef; if (sec->GetPortalPlaneZ(sector_t::floor) > Z() - radius) { DVector2 refpos = other->v1->fPos() + other->Delta() / 2 + sec->GetPortalDisplacement(sector_t::floor); subsector_t *othersub = R_PointInSubsector(refpos); - if (othersub->validcount != ::validcount) + FSection *othersect = othersub->section; + if (othersect->validcount != dl_validcount) { - othersub->validcount = ::validcount; - collected_ss.Push({ othersub, PosRelative(othersub->sector) }); + othersect->validcount = dl_validcount; + collected_ss.Push({ othersect, PosRelative(othersub->sector) }); } } } @@ -680,32 +682,33 @@ void ADynamicLight::LinkLight() node = touching_sides; while (node) { - node->lightsource = NULL; + node->lightsource = nullptr; node = node->nextTarget; } node = touching_sector; while (node) { - node->lightsource = NULL; + node->lightsource = nullptr; node = node->nextTarget; } if (radius>0) { // passing in radius*radius allows us to do a distance check without any calls to sqrt - subsector_t * subSec = R_PointInSubsector(Pos()); - ::validcount++; - CollectWithinRadius(Pos(), subSec, float(radius*radius)); + FSection *sect = R_PointInSubsector(Pos())->section; + + dl_validcount++; + CollectWithinRadius(Pos(), sect, float(radius*radius)); } // Now delete any nodes that won't be used. These are the ones where - // m_thing is still NULL. + // m_thing is still nullptr. node = touching_sides; while (node) { - if (node->lightsource == NULL) + if (node->lightsource == nullptr) { node = DeleteLightNode(node); } @@ -716,7 +719,7 @@ void ADynamicLight::LinkLight() node = touching_sector; while (node) { - if (node->lightsource == NULL) + if (node->lightsource == nullptr) { node = DeleteLightNode(node); } @@ -733,7 +736,7 @@ void ADynamicLight::LinkLight() //========================================================================== void ADynamicLight::UnlinkLight () { - if (owned && target != NULL) + if (owned && target != nullptr) { // Delete reference in owning actor for(int c=target->AttachedLights.Size()-1; c>=0; c--) @@ -770,7 +773,7 @@ void AActor::AttachLight(unsigned int count, const FLightDefaults *lightdef) if (count < AttachedLights.Size()) { light = barrier_cast(AttachedLights[count]); - assert(light != NULL); + assert(light != nullptr); } else { @@ -797,13 +800,13 @@ void AActor::SetDynamicLights() TArray & LightAssociations = GetInfo()->LightAssociations; unsigned int count = 0; - if (state == NULL) return; + if (state == nullptr) return; if (LightAssociations.Size() > 0) { ADynamicLight *lights, *tmpLight; unsigned int i; - lights = tmpLight = NULL; + lights = tmpLight = nullptr; for (i = 0; i < LightAssociations.Size(); i++) { @@ -816,7 +819,7 @@ void AActor::SetDynamicLights() } if (count == 0 && state->Light > 0) { - for(int i= state->Light; StateLights[i] != NULL; i++) + for(int i= state->Light; StateLights[i] != nullptr; i++) { if (StateLights[i] != (FLightDefaults*)-1) { diff --git a/src/g_shared/a_dynlight.h b/src/g_shared/a_dynlight.h index 671c7812f..d28b787b1 100644 --- a/src/g_shared/a_dynlight.h +++ b/src/g_shared/a_dynlight.h @@ -12,6 +12,7 @@ struct seg_t; class ADynamicLight; class FSerializer; +struct FSectionLine; enum ELightType { @@ -209,8 +210,8 @@ public: FLightNode * touching_sector; private: - double DistToSeg(const DVector3 &pos, seg_t *seg); - void CollectWithinRadius(const DVector3 &pos, subsector_t *subSec, float radius); + double DistToSeg(const DVector3 &pos, FSectionLine *seg); + void CollectWithinRadius(const DVector3 &pos, FSection *section, float radius); protected: DVector3 m_off; diff --git a/src/hwrenderer/data/hw_sections.cpp b/src/hwrenderer/data/hw_sections.cpp index 4ad20d47a..c43a22eeb 100644 --- a/src/hwrenderer/data/hw_sections.cpp +++ b/src/hwrenderer/data/hw_sections.cpp @@ -633,11 +633,9 @@ public: { output.allSections.Resize(groups.Size()); output.allIndices.Resize(level.subsectors.Size() + level.sides.Size() + 2*level.sectors.Size()); - output.sectionForSubsectorPtr = &output.allIndices[0]; - output.sectionForSidedefPtr = &output.allIndices[level.subsectors.Size()]; - output.firstSectionForSectorPtr = &output.allIndices[level.subsectors.Size() + level.sides.Size()]; - output.numberOfSectionForSectorPtr = &output.allIndices[level.subsectors.Size() + level.sides.Size() + level.sectors.Size()]; - memset(output.sectionForSubsectorPtr, -1, sizeof(int) * level.subsectors.Size()); + output.sectionForSidedefPtr = &output.allIndices[0]; + output.firstSectionForSectorPtr = &output.allIndices[level.sides.Size()]; + output.numberOfSectionForSectorPtr = &output.allIndices[level.sides.Size() + level.sectors.Size()]; memset(output.firstSectionForSectorPtr, -1, sizeof(int) * level.sectors.Size()); memset(output.numberOfSectionForSectorPtr, 0, sizeof(int) * level.sectors.Size()); @@ -704,6 +702,7 @@ public: fseg.end = segment->end; fseg.partner = segment->partner == nullptr ? nullptr : &output.allLines[segment->partner->tempindex]; fseg.sidedef = segment->sidedef; + fseg.section = &dest; dest.bounds.addVertex(fseg.start->fX(), fseg.start->fY()); dest.bounds.addVertex(fseg.end->fX(), fseg.end->fY()); } @@ -717,7 +716,7 @@ public: for (auto ssi : group.subsectors) { output.allSubsectors[numsubsectors++] = &level.subsectors[ssi]; - output.sectionForSubsectorPtr[ssi] = curgroup; + level.subsectors[ssi].section = &output.allSections[curgroup]; } curgroup++; } diff --git a/src/hwrenderer/data/hw_sections.h b/src/hwrenderer/data/hw_sections.h index 178d0ed84..668c2ba39 100644 --- a/src/hwrenderer/data/hw_sections.h +++ b/src/hwrenderer/data/hw_sections.h @@ -73,6 +73,7 @@ struct FSectionLine vertex_t *start; vertex_t *end; FSectionLine *partner; + FSection *section; side_t *sidedef; }; @@ -101,27 +102,10 @@ public: TArray allSubsectors; TArray allIndices; - int *sectionForSubsectorPtr; // stored inside allIndices int *sectionForSidedefPtr; // also stored inside allIndices; int *firstSectionForSectorPtr; // ditto. int *numberOfSectionForSectorPtr; // ditto. - FSection *SectionForSubsector(subsector_t *sub) - { - return SectionForSubsector(sub->Index()); - } - FSection *SectionForSubsector(int ssindex) - { - return ssindex < 0 ? nullptr : &allSections[sectionForSubsectorPtr[ssindex]]; - } - int SectionNumForSubsector(subsector_t *sub) - { - return SectionNumForSubsector(sub->Index()); - } - int SectionNumForSubsector(int ssindex) - { - return ssindex < 0 ? -1 : sectionForSubsectorPtr[ssindex]; - } FSection *SectionForSidedef(side_t *side) { return SectionForSidedef(side->Index()); diff --git a/src/hwrenderer/scene/hw_bsp.cpp b/src/hwrenderer/scene/hw_bsp.cpp index 92b911781..affca42a8 100644 --- a/src/hwrenderer/scene/hw_bsp.cpp +++ b/src/hwrenderer/scene/hw_bsp.cpp @@ -155,7 +155,7 @@ void HWDrawInfo::WorkerThread() { GLFlat flat; SetupFlat.Clock(); - flat.section = level.sections.SectionForSubsector(job->sub); + flat.section = job->sub->section; front = hw_FakeFlat(job->sub->render_sector, &fakefront, in_area, false); flat.ProcessSector(this, front); SetupFlat.Unclock(); @@ -680,8 +680,7 @@ void HWDrawInfo::DoSubsector(subsector_t * sub) fakesector = hw_FakeFlat(sector, &fake, in_area, false); } - auto secnum = level.sections.SectionNumForSubsector(sub); - uint8_t &srf = section_renderflags[secnum]; + uint8_t &srf = section_renderflags[level.sections.SectionIndex(sub->section)]; if (!(srf & SSRF_PROCESSED)) { srf |= SSRF_PROCESSED; @@ -693,7 +692,7 @@ void HWDrawInfo::DoSubsector(subsector_t * sub) else { GLFlat flat; - flat.section = level.sections.SectionForSubsector(sub); + flat.section = sub->section; SetupFlat.Clock(); flat.ProcessSector(this, fakesector); SetupFlat.Unclock(); diff --git a/src/hwrenderer/scene/hw_flats.cpp b/src/hwrenderer/scene/hw_flats.cpp index 2278bbd58..f7948e080 100644 --- a/src/hwrenderer/scene/hw_flats.cpp +++ b/src/hwrenderer/scene/hw_flats.cpp @@ -184,7 +184,7 @@ void GLFlat::DrawSubsectors(HWDrawInfo *di, FRenderState &state) { if (level.HasDynamicLights && screen->BuffersArePersistent()) { - SetupLights(di, sector->lighthead, lightdata, sector->PortalGroup); + SetupLights(di, section->lighthead, lightdata, sector->PortalGroup); } state.SetLightIndex(dynlightindex); @@ -346,7 +346,7 @@ inline void GLFlat::PutFlat(HWDrawInfo *di, bool fog) { if (level.HasDynamicLights && gltexture != nullptr) { - SetupLights(di, sector->lighthead, lightdata, sector->PortalGroup); + SetupLights(di, section->lighthead, lightdata, sector->PortalGroup); } } di->AddFlat(this, fog); diff --git a/src/hwrenderer/scene/hw_renderhacks.cpp b/src/hwrenderer/scene/hw_renderhacks.cpp index 05770125d..8f3325f2d 100644 --- a/src/hwrenderer/scene/hw_renderhacks.cpp +++ b/src/hwrenderer/scene/hw_renderhacks.cpp @@ -54,7 +54,8 @@ int HWDrawInfo::SetupLightsForOtherPlane(subsector_t * sub, FDynLightData &light if (level.HasDynamicLights && !isFullbrightScene()) { Plane p; - FLightNode * node = sub->sector->lighthead; + + FLightNode * node = sub->section->lighthead; lightdata.Clear(); while (node) diff --git a/src/hwrenderer/scene/hw_spritelight.cpp b/src/hwrenderer/scene/hw_spritelight.cpp index 3b5a0c1d8..a0d76343b 100644 --- a/src/hwrenderer/scene/hw_spritelight.cpp +++ b/src/hwrenderer/scene/hw_spritelight.cpp @@ -131,11 +131,11 @@ void HWDrawInfo::GetDynSpriteLight(AActor *thing, particle_t *particle, float *o { if (thing != NULL) { - GetDynSpriteLight(thing, (float)thing->X(), (float)thing->Y(), (float)thing->Center(), thing->Sector->lighthead, thing->Sector->PortalGroup, out); + GetDynSpriteLight(thing, (float)thing->X(), (float)thing->Y(), (float)thing->Center(), thing->section->lighthead, thing->Sector->PortalGroup, out); } else if (particle != NULL) { - GetDynSpriteLight(NULL, (float)particle->Pos.X, (float)particle->Pos.Y, (float)particle->Pos.Z, particle->subsector->sector->lighthead, particle->subsector->sector->PortalGroup, out); + GetDynSpriteLight(NULL, (float)particle->Pos.X, (float)particle->Pos.Y, (float)particle->Pos.Z, particle->subsector->section->lighthead, particle->subsector->sector->PortalGroup, out); } } @@ -157,10 +157,13 @@ void hw_GetDynModelLight(AActor *self, FDynLightData &modellightdata) float y = (float)self->Y(); float z = (float)self->Center(); float radiusSquared = (float)(self->renderradius * self->renderradius); + dl_validcount++; BSPWalkCircle(x, y, radiusSquared, [&](subsector_t *subsector) // Iterate through all subsectors potentially touched by actor { - FLightNode * node = subsector->sector->lighthead; + auto section = subsector->section; + if (section->validcount == dl_validcount) return; // already done from a previous subsector. + FLightNode * node = section->lighthead; while (node) // check all lights touching a subsector { ADynamicLight *light = node->lightsource; diff --git a/src/hwrenderer/scene/hw_walls.cpp b/src/hwrenderer/scene/hw_walls.cpp index b782c54e9..b91c38ae1 100644 --- a/src/hwrenderer/scene/hw_walls.cpp +++ b/src/hwrenderer/scene/hw_walls.cpp @@ -302,7 +302,7 @@ void GLWall::SetupLights(HWDrawInfo *di, FDynLightData &lightdata) else if (sub) { // Polobject segs cannot be checked per sidedef so use the subsector instead. - node = sub->sector->lighthead; + node = sub->section->lighthead; } else node = NULL; diff --git a/src/p_maputl.cpp b/src/p_maputl.cpp index 19c9496d3..008edb210 100644 --- a/src/p_maputl.cpp +++ b/src/p_maputl.cpp @@ -470,7 +470,7 @@ void AActor::LinkToWorld(FLinkContext *ctx, bool spawningmapthing, sector_t *sec Sector = sector; subsector = R_PointInSubsector(Pos()); // this is from the rendering nodes, not the gameplay nodes! - section = level.sections.SectionForSubsector(subsector->Index()); + section = subsector->section; if (!(flags & MF_NOSECTOR)) { diff --git a/src/polyrenderer/scene/poly_model.cpp b/src/polyrenderer/scene/poly_model.cpp index 78520826f..91c975d1e 100644 --- a/src/polyrenderer/scene/poly_model.cpp +++ b/src/polyrenderer/scene/poly_model.cpp @@ -70,7 +70,7 @@ void PolyModelRenderer::AddLights(AActor *actor) BSPWalkCircle(x, y, radiusSquared, [&](subsector_t *subsector) // Iterate through all subsectors potentially touched by actor { - FLightNode * node = subsector->sector->lighthead; + FLightNode * node = subsector->section->lighthead; while (node) // check all lights touching a subsector { ADynamicLight *light = node->lightsource; diff --git a/src/polyrenderer/scene/poly_plane.cpp b/src/polyrenderer/scene/poly_plane.cpp index 076a334f9..18d24cfd7 100644 --- a/src/polyrenderer/scene/poly_plane.cpp +++ b/src/polyrenderer/scene/poly_plane.cpp @@ -275,7 +275,7 @@ void RenderPolyPlane::SetDynLights(PolyRenderThread *thread, PolyDrawArgs &args, return; } - FLightNode *light_list = sub->sector->lighthead; + FLightNode *light_list = sub->section->lighthead; auto cameraLight = PolyCameraLight::Instance(); if ((cameraLight->FixedLightLevel() >= 0) || (cameraLight->FixedColormap() != nullptr)) diff --git a/src/polyrenderer/scene/poly_sprite.cpp b/src/polyrenderer/scene/poly_sprite.cpp index 011fa67c6..122f518c6 100644 --- a/src/polyrenderer/scene/poly_sprite.cpp +++ b/src/polyrenderer/scene/poly_sprite.cpp @@ -381,7 +381,7 @@ void RenderPolySprite::SetDynlight(AActor *thing, PolyDrawArgs &args) float lit_red = 0; float lit_green = 0; float lit_blue = 0; - auto node = thing->Sector->lighthead; + auto node = thing->section->lighthead; while (node != nullptr) { ADynamicLight *light = node->lightsource; diff --git a/src/r_defs.h b/src/r_defs.h index 9f1e7c265..5163e8f83 100644 --- a/src/r_defs.h +++ b/src/r_defs.h @@ -51,6 +51,7 @@ struct FLinePortal; struct seg_t; struct sector_t; class AActor; +struct FSection; #define MAXWIDTH 12000 #define MAXHEIGHT 5000 @@ -1028,7 +1029,6 @@ public: // killough 3/7/98: support flat heights drawn at another sector's heights sector_t *heightsec; // other sector, or NULL if no other sector - FLightNode * lighthead; uint32_t bottommap, midmap, topmap; // killough 4/4/98: dynamic colormaps // [RH] these can also be blend values if @@ -1455,13 +1455,13 @@ struct subsector_t FMiniBSP *BSP; seg_t *firstline; sector_t *render_sector; + FSection *section; uint32_t numlines; uint16_t flags; - uint16_t sectorindex; + short mapsection; // subsector related GL data int validcount; - short mapsection; char hacked; // 1: is part of a render hack void BuildPolyBSP(); diff --git a/src/r_utility.cpp b/src/r_utility.cpp index 8de8727f1..77c685626 100644 --- a/src/r_utility.cpp +++ b/src/r_utility.cpp @@ -142,6 +142,7 @@ bool setsizeneeded; unsigned int R_OldBlend = ~0; int validcount = 1; // increment every time a check is made +int dl_validcount = 1; // increment every time a check is made FCanvasTextureInfo *FCanvasTextureInfo::List; DVector3a view; diff --git a/src/r_utility.h b/src/r_utility.h index b18588ab9..e5ac4a2b8 100644 --- a/src/r_utility.h +++ b/src/r_utility.h @@ -66,6 +66,7 @@ extern FViewWindow r_viewwindow; extern int setblocks; extern bool r_NoInterpolate; extern int validcount; +extern int dl_validcount; // For use with FSection. validcount is in use by the renderer and any quick section exclusion needs another variable. extern angle_t LocalViewAngle; // [RH] Added to consoleplayer's angle extern int LocalViewPitch; // [RH] Used directly instead of consoleplayer's pitch diff --git a/src/swrenderer/scene/r_opaque_pass.cpp b/src/swrenderer/scene/r_opaque_pass.cpp index 987b89b5b..de6922500 100644 --- a/src/swrenderer/scene/r_opaque_pass.cpp +++ b/src/swrenderer/scene/r_opaque_pass.cpp @@ -558,7 +558,7 @@ namespace swrenderer Fake3DOpaque::Normal, 0); - ceilingplane->AddLights(Thread, frontsector->lighthead); + ceilingplane->AddLights(Thread, sub->section->lighthead); } int adjusted_floorlightlevel = floorlightlevel; @@ -598,7 +598,7 @@ namespace swrenderer Fake3DOpaque::Normal, 0); - floorplane->AddLights(Thread, frontsector->lighthead); + floorplane->AddLights(Thread, sub->section->lighthead); } Add3DFloorPlanes(sub, frontsector, basecolormap, foggy, adjusted_ceilinglightlevel, adjusted_floorlightlevel); @@ -742,7 +742,7 @@ namespace swrenderer Fake3DOpaque::FakeFloor, fakeAlpha); - floorplane3d->AddLights(Thread, tempsec.lighthead); + floorplane3d->AddLights(Thread, sub->section->lighthead); FakeDrawLoop(sub, &tempsec, floorplane3d, nullptr, foggy, basecolormap, Fake3DOpaque::FakeFloor); } @@ -810,7 +810,7 @@ namespace swrenderer Fake3DOpaque::FakeCeiling, fakeAlpha); - ceilingplane3d->AddLights(Thread, tempsec.lighthead); + ceilingplane3d->AddLights(Thread, sub->section->lighthead); FakeDrawLoop(sub, &tempsec, nullptr, ceilingplane3d, foggy, basecolormap, Fake3DOpaque::FakeCeiling); } diff --git a/src/swrenderer/things/r_model.cpp b/src/swrenderer/things/r_model.cpp index a3ce1a5bb..2ee416973 100644 --- a/src/swrenderer/things/r_model.cpp +++ b/src/swrenderer/things/r_model.cpp @@ -111,7 +111,7 @@ namespace swrenderer BSPWalkCircle(x, y, radiusSquared, [&](subsector_t *subsector) // Iterate through all subsectors potentially touched by actor { - FLightNode * node = subsector->sector->lighthead; + FLightNode * node = subsector->section->lighthead; while (node) // check all lights touching a subsector { ADynamicLight *light = node->lightsource; diff --git a/src/swrenderer/things/r_sprite.cpp b/src/swrenderer/things/r_sprite.cpp index 36e9ca89f..1251860d9 100644 --- a/src/swrenderer/things/r_sprite.cpp +++ b/src/swrenderer/things/r_sprite.cpp @@ -202,6 +202,7 @@ namespace swrenderer // killough 3/27/98: save sector for special clipping later vis->heightsec = heightsec; vis->sector = thing->Sector; + vis->section = thing->section; vis->depth = (float)tz; vis->gpos = { (float)pos.X, (float)pos.Y, (float)pos.Z }; @@ -251,7 +252,7 @@ namespace swrenderer float lit_red = 0; float lit_green = 0; float lit_blue = 0; - auto node = vis->sector->lighthead; + auto node = vis->section->lighthead; while (node != nullptr) { ADynamicLight *light = node->lightsource; diff --git a/src/swrenderer/things/r_visiblesprite.h b/src/swrenderer/things/r_visiblesprite.h index b1ddebae7..37787a809 100644 --- a/src/swrenderer/things/r_visiblesprite.h +++ b/src/swrenderer/things/r_visiblesprite.h @@ -73,6 +73,7 @@ namespace swrenderer FVector3 gpos = { 0.0f, 0.0f, 0.0f }; // origin in world coordinates sector_t *sector = nullptr; // sector this sprite is in + FSection *section; ColormapLight Light; float Alpha = 0.0f; From 87973ff50476a58ea06624a5cc7c31e60d29cd4b Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Tue, 6 Nov 2018 00:47:43 +0100 Subject: [PATCH 10/16] - added handling for intra-sector lines to lighting code. --- src/g_shared/a_dynlight.cpp | 95 ++++++++++++++++------------- src/g_shared/a_dynlight.h | 2 +- src/hwrenderer/data/hw_sections.cpp | 4 +- 3 files changed, 56 insertions(+), 45 deletions(-) diff --git a/src/g_shared/a_dynlight.cpp b/src/g_shared/a_dynlight.cpp index e8dc871bf..8f5c3ec1a 100644 --- a/src/g_shared/a_dynlight.cpp +++ b/src/g_shared/a_dynlight.cpp @@ -527,20 +527,20 @@ static FLightNode * DeleteLightNode(FLightNode * node) // //========================================================================== -double ADynamicLight::DistToSeg(const DVector3 &pos, FSectionLine *segment) +double ADynamicLight::DistToSeg(const DVector3 &pos, vertex_t *start, vertex_t *end) { double u, px, py; - double seg_dx = segment->end->fX() - segment->start->fX(); - double seg_dy = segment->end->fY() - segment->start->fY(); + double seg_dx = end->fX() - start->fX(); + double seg_dy = end->fY() - start->fY(); double seg_length_sq = seg_dx * seg_dx + seg_dy * seg_dy; - u = (((pos.X - segment->start->fX()) * seg_dx) + (pos.Y - segment->start->fY()) * seg_dy) / seg_length_sq; + u = (((pos.X - start->fX()) * seg_dx) + (pos.Y - start->fY()) * seg_dy) / seg_length_sq; if (u < 0.) u = 0.; // clamp the test point to the line segment else if (u > 1.) u = 1.; - px = segment->start->fX() + (u * seg_dx); - py = segment->start->fY() + (u * seg_dy); + px = start->fX() + (u * seg_dx); + py = start->fY() + (u * seg_dy); px -= pos.X; py -= pos.Y; @@ -572,53 +572,58 @@ void ADynamicLight::CollectWithinRadius(const DVector3 &opos, FSection *section, bool hitonesidedback = false; for (unsigned i = 0; i < collected_ss.Size(); i++) { + auto &pos = collected_ss[i].pos; section = collected_ss[i].sect; touching_sector = AddLightNode(§ion->lighthead, section, this, touching_sector); + + auto processSide = [&](side_t *sidedef, vertex_t *v1, vertex_t *v2) + { + auto linedef = sidedef->linedef; + if (linedef && linedef->validcount != ::validcount) + { + // light is in front of the seg + if ((pos.Y - v1->fY()) * (v2->fX() - v1->fX()) + (v1->fX() - pos.X) * (v2->fY() - v1->fY()) <= 0) + { + linedef->validcount = ::validcount; + touching_sides = AddLightNode(&sidedef->lighthead, sidedef, this, touching_sides); + } + else if (linedef->sidedef[0] == sidedef && linedef->sidedef[1] == nullptr) + { + hitonesidedback = true; + } + } + if (linedef) + { + FLinePortal *port = linedef->getPortal(); + if (port && port->mType == PORTT_LINKED) + { + line_t *other = port->mDestination; + if (other->validcount != ::validcount) + { + subsector_t *othersub = R_PointInSubsector(other->v1->fPos() + other->Delta() / 2); + FSection *othersect = othersub->section; + if (othersect->validcount != ::validcount) + { + othersect->validcount = ::validcount; + collected_ss.Push({ othersect, PosRelative(other) }); + } + } + } + } + }; + for (auto &segment : section->segments) { - auto &pos = collected_ss[i].pos; - // check distance from x/y to seg and if within radius add this seg and, if present the opposing subsector (lather/rinse/repeat) // If out of range we do not need to bother with this seg. - if (DistToSeg(pos, &segment) <= radius) + if (DistToSeg(pos, segment.start, segment.end) <= radius) { - if (segment.sidedef) + auto sidedef = segment.sidedef; + if (sidedef) { - auto sidedef = segment.sidedef; - auto linedef = sidedef->linedef; - if (linedef && linedef->validcount != ::validcount) - { - // light is in front of the seg - if ((pos.Y - segment.start->fY()) * (segment.end->fX() - segment.start->fX()) + (segment.start->fX() - pos.X) * (segment.end->fY() - segment.start->fY()) <= 0) - { - linedef->validcount = ::validcount; - touching_sides = AddLightNode(&sidedef->lighthead, sidedef, this, touching_sides); - } - else if (linedef->sidedef[0] == sidedef && linedef->sidedef[1] == nullptr) - { - hitonesidedback = true; - } - } - if (linedef) - { - FLinePortal *port = linedef->getPortal(); - if (port && port->mType == PORTT_LINKED) - { - line_t *other = port->mDestination; - if (other->validcount != ::validcount) - { - subsector_t *othersub = R_PointInSubsector(other->v1->fPos() + other->Delta() / 2); - FSection *othersect = othersub->section; - if (othersect->validcount != ::validcount) - { - othersect->validcount = ::validcount; - collected_ss.Push({ othersect, PosRelative(other) }); - } - } - } - } + processSide(sidedef, segment.start, segment.end); } auto partner = segment.partner; @@ -633,6 +638,10 @@ void ADynamicLight::CollectWithinRadius(const DVector3 &opos, FSection *section, } } } + for (auto side : section->sides) + { + processSide(side, side->V1(), side->V2()); + } sector_t *sec = section->sector; if (!sec->PortalBlocksSight(sector_t::ceiling)) { diff --git a/src/g_shared/a_dynlight.h b/src/g_shared/a_dynlight.h index d28b787b1..369b826e3 100644 --- a/src/g_shared/a_dynlight.h +++ b/src/g_shared/a_dynlight.h @@ -210,7 +210,7 @@ public: FLightNode * touching_sector; private: - double DistToSeg(const DVector3 &pos, FSectionLine *seg); + double DistToSeg(const DVector3 &pos, vertex_t *start, vertex_t *end); void CollectWithinRadius(const DVector3 &pos, FSection *section, float radius); protected: diff --git a/src/hwrenderer/data/hw_sections.cpp b/src/hwrenderer/data/hw_sections.cpp index c43a22eeb..3ef6502c6 100644 --- a/src/hwrenderer/data/hw_sections.cpp +++ b/src/hwrenderer/data/hw_sections.cpp @@ -658,7 +658,9 @@ public: } for (auto side : section.originalSides) { - group.sideMap[side->Index()] = true; + // This is only used for attaching lights to those sidedefs which are not part of the outline. + if (side->linedef && side->linedef->sidedef[1] && side->linedef->sidedef[0]->sector == side->linedef->sidedef[1]->sector) + group.sideMap[side->Index()] = true; } } numsides += group.sideMap.CountUsed(); From df52a71475af281fc8fdaa520ff5bf43838220e0 Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Tue, 6 Nov 2018 01:01:33 +0100 Subject: [PATCH 11/16] - fixed validcount. --- src/g_shared/a_dynlight.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/g_shared/a_dynlight.cpp b/src/g_shared/a_dynlight.cpp index 8f5c3ec1a..50e1d1991 100644 --- a/src/g_shared/a_dynlight.cpp +++ b/src/g_shared/a_dynlight.cpp @@ -707,6 +707,7 @@ void ADynamicLight::LinkLight() FSection *sect = R_PointInSubsector(Pos())->section; dl_validcount++; + validcount++; CollectWithinRadius(Pos(), sect, float(radius*radius)); } From aee47d23bdd421ed0f9bab45aa646d683078a5d8 Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Tue, 6 Nov 2018 11:53:03 +0100 Subject: [PATCH 12/16] - fixed validcount for real and added a side check for intra-section sides to light code. --- src/g_shared/a_dynlight.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/g_shared/a_dynlight.cpp b/src/g_shared/a_dynlight.cpp index 50e1d1991..a7aa405cd 100644 --- a/src/g_shared/a_dynlight.cpp +++ b/src/g_shared/a_dynlight.cpp @@ -578,7 +578,7 @@ void ADynamicLight::CollectWithinRadius(const DVector3 &opos, FSection *section, touching_sector = AddLightNode(§ion->lighthead, section, this, touching_sector); - auto processSide = [&](side_t *sidedef, vertex_t *v1, vertex_t *v2) + auto processSide = [&](side_t *sidedef, const vertex_t *v1, const vertex_t *v2) { auto linedef = sidedef->linedef; if (linedef && linedef->validcount != ::validcount) @@ -640,7 +640,11 @@ void ADynamicLight::CollectWithinRadius(const DVector3 &opos, FSection *section, } for (auto side : section->sides) { - processSide(side, side->V1(), side->V2()); + auto v1 = side->V1(), v2 = side->V2(); + if (DistToSeg(pos, v1, v2) <= radius) + { + processSide(side, v1, v2); + } } sector_t *sec = section->sector; if (!sec->PortalBlocksSight(sector_t::ceiling)) @@ -707,7 +711,7 @@ void ADynamicLight::LinkLight() FSection *sect = R_PointInSubsector(Pos())->section; dl_validcount++; - validcount++; + ::validcount++; CollectWithinRadius(Pos(), sect, float(radius*radius)); } From a6e77ae0944d47d71d00952b635c90eeb80bdd5c Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Tue, 6 Nov 2018 18:20:59 +0100 Subject: [PATCH 13/16] Refactored the render hack storage so that it can be decoupled from the regular GLFlat render items. Having these in there makes it impossible to change render techniques so these are better done as separate items. --- src/hwrenderer/scene/hw_drawinfo.cpp | 27 +--- src/hwrenderer/scene/hw_drawinfo.h | 36 +---- src/hwrenderer/scene/hw_drawstructs.h | 6 +- src/hwrenderer/scene/hw_flats.cpp | 202 +++++++++++++++--------- src/hwrenderer/scene/hw_renderhacks.cpp | 85 +++++----- 5 files changed, 174 insertions(+), 182 deletions(-) diff --git a/src/hwrenderer/scene/hw_drawinfo.cpp b/src/hwrenderer/scene/hw_drawinfo.cpp index 128b1d8fa..0dd67634e 100644 --- a/src/hwrenderer/scene/hw_drawinfo.cpp +++ b/src/hwrenderer/scene/hw_drawinfo.cpp @@ -56,18 +56,6 @@ sector_t * hw_FakeFlat(sector_t * sec, sector_t * dest, area_t in_area, bool bac // //========================================================================== -template -inline void DeleteLinkedList(T *node) -{ - while (node) - { - auto n = node; - node = node->next; - delete n; - } -} - - class FDrawInfoList { public: @@ -188,17 +176,10 @@ HWDrawInfo *HWDrawInfo::EndDrawInfo() void HWDrawInfo::ClearBuffers() { - for (auto node : otherfloorplanes) DeleteLinkedList(node); - otherfloorplanes.Clear(); - - for (auto node : otherceilingplanes) DeleteLinkedList(node); - otherceilingplanes.Clear(); - - for (auto node : floodfloorsegs) DeleteLinkedList(node); - floodfloorsegs.Clear(); - - for (auto node : floodceilingsegs) DeleteLinkedList(node); - floodceilingsegs.Clear(); + otherFloorPlanes.Clear(); + otherCeilingPlanes.Clear(); + floodFloorSegs.Clear(); + floodCeilingSegs.Clear(); // clear all the lists that might not have been cleared already MissingUpperTextures.Clear(); diff --git a/src/hwrenderer/scene/hw_drawinfo.h b/src/hwrenderer/scene/hw_drawinfo.h index 537c2a202..e40c361ef 100644 --- a/src/hwrenderer/scene/hw_drawinfo.h +++ b/src/hwrenderer/scene/hw_drawinfo.h @@ -68,6 +68,8 @@ enum SectorRenderFlags SSRF_RENDERALL = 7, SSRF_PROCESSED = 8, SSRF_SEEN = 16, + SSRF_PLANEHACK = 32, + SSRF_FLOODHACK = 64 }; enum EPortalClip @@ -160,10 +162,10 @@ struct HWDrawInfo TArray SubsectorHacks; - TArray otherfloorplanes; - TArray otherceilingplanes; - TArray floodfloorsegs; - TArray floodceilingsegs; + TMap otherFloorPlanes; + TMap otherCeilingPlanes; + TMap floodFloorSegs; + TMap floodCeilingSegs; TArray CeilingStacks; TArray FloorStacks; @@ -212,32 +214,6 @@ private: void DrawPSprite(HUDSprite *huds, FRenderState &state); public: - gl_subsectorrendernode * GetOtherFloorPlanes(unsigned int sector) - { - if (sectorvertexindex, section->vertexcount); flatvertices += section->vertexcount; flatprimitives++; - - -#if 0 - //Temporarily disabled until the render hack code can be redone and refactored into its own draw elements - if (!(renderflags&SSRF_RENDER3DPLANES)) - { - // Draw the subsectors assigned to it due to missing textures - gl_subsectorrendernode * node = (renderflags&SSRF_RENDERFLOOR) ? - di->GetOtherFloorPlanes(sector->sectornum) : - di->GetOtherCeilingPlanes(sector->sectornum); - - while (node) - { - state.SetLightIndex(node->lightindex); - auto num = node->sub->numlines; - flatvertices += num; - flatprimitives++; - state.Draw(DT_TriangleFan,node->vertexindex, num); - node = node->next; - } - // Flood gaps with the back side's ceiling/floor texture - // This requires a stencil because the projected plane interferes with - // the depth buffer - gl_floodrendernode * fnode = (renderflags&SSRF_RENDERFLOOR) ? - di->GetFloodFloorSegs(sector->sectornum) : - di->GetFloodCeilingSegs(sector->sectornum); - - state.SetLightIndex(dynlightindex); - while (fnode) - { - flatvertices += 12; - flatprimitives += 3; - - // Push bleeding floor/ceiling textures back a little in the z-buffer - // so they don't interfere with overlapping mid textures. - state.SetDepthBias(1, 128); - - // Create stencil - state.SetEffect(EFF_STENCIL); - state.EnableTexture(false); - state.SetStencil(0, SOP_Increment, SF_ColorMaskOff); - state.Draw(DT_TriangleFan,fnode->vertexindex, 4); - - // Draw projected plane into stencil - state.EnableTexture(true); - state.SetEffect(EFF_NONE); - state.SetStencil(1, SOP_Keep, SF_DepthMaskOff); - state.EnableDepthTest(false); - state.Draw(DT_TriangleFan,fnode->vertexindex + 4, 4); - - // clear stencil - state.SetEffect(EFF_STENCIL); - state.EnableTexture(false); - state.SetStencil(1, SOP_Decrement, SF_ColorMaskOff | SF_DepthMaskOff); - state.Draw(DT_TriangleFan,fnode->vertexindex, 4); - - // restore old stencil op. - state.EnableTexture(true); - state.EnableDepthTest(true); - state.SetEffect(EFF_NONE); - state.SetDepthBias(0, 0); - state.SetStencil(0, SOP_Keep, SF_AllOn); - - fnode = fnode->next; - } - - } -#endif } + +//========================================================================== +// +// Drawer for render hacks +// +//========================================================================== + +void GLFlat::DrawOtherPlanes(HWDrawInfo *di, FRenderState &state) +{ + state.SetMaterial(gltexture, CLAMP_XY, 0, -1); + + // Draw the subsectors assigned to it due to missing textures + auto pNode = (renderflags&SSRF_RENDERFLOOR) ? + di->otherFloorPlanes.CheckKey(sector->sectornum) : di->otherCeilingPlanes.CheckKey(sector->sectornum); + + if (!pNode) return; + auto node = *pNode; + + while (node) + { + state.SetLightIndex(node->lightindex); + auto num = node->sub->numlines; + flatvertices += num; + flatprimitives++; + state.Draw(DT_TriangleFan,node->vertexindex, num); + node = node->next; + } +} + +//========================================================================== +// +// Drawer for render hacks +// +//========================================================================== + +void GLFlat::DrawFloodPlanes(HWDrawInfo *di, FRenderState &state) +{ + // Flood gaps with the back side's ceiling/floor texture + // This requires a stencil because the projected plane interferes with + // the depth buffer + + state.SetMaterial(gltexture, CLAMP_XY, 0, -1); + + // Draw the subsectors assigned to it due to missing textures + auto pNode = (renderflags&SSRF_RENDERFLOOR) ? + di->floodFloorSegs.CheckKey(sector->sectornum) : di->floodCeilingSegs.CheckKey(sector->sectornum); + + if (!pNode) return; + auto node = *pNode; + + while (node) + { + + auto pNode = (renderflags&SSRF_RENDERFLOOR) ? + di->floodFloorSegs.CheckKey(sector->sectornum) : di->floodCeilingSegs.CheckKey(sector->sectornum); + if (!pNode) return; + + auto fnode = *pNode; + + state.SetLightIndex(-1); + while (fnode) + { + flatvertices += 12; + flatprimitives += 3; + + // Push bleeding floor/ceiling textures back a little in the z-buffer + // so they don't interfere with overlapping mid textures. + state.SetDepthBias(1, 128); + + // Create stencil + state.SetEffect(EFF_STENCIL); + state.EnableTexture(false); + state.SetStencil(0, SOP_Increment, SF_ColorMaskOff); + state.Draw(DT_TriangleFan,fnode->vertexindex, 4); + + // Draw projected plane into stencil + state.EnableTexture(true); + state.SetEffect(EFF_NONE); + state.SetStencil(1, SOP_Keep, SF_DepthMaskOff); + state.EnableDepthTest(false); + state.Draw(DT_TriangleFan,fnode->vertexindex + 4, 4); + + // clear stencil + state.SetEffect(EFF_STENCIL); + state.EnableTexture(false); + state.SetStencil(1, SOP_Decrement, SF_ColorMaskOff | SF_DepthMaskOff); + state.Draw(DT_TriangleFan,fnode->vertexindex, 4); + + // restore old stencil op. + state.EnableTexture(true); + state.EnableDepthTest(true); + state.SetEffect(EFF_NONE); + state.SetDepthBias(0, 0); + state.SetStencil(0, SOP_Keep, SF_AllOn); + + fnode = fnode->next; + } + + } +} + + //========================================================================== // // @@ -282,8 +316,7 @@ void GLFlat::DrawFlat(HWDrawInfo *di, FRenderState &state, bool translucent) state.SetColor(lightlevel, rel, di->isFullbrightScene(), Colormap, alpha); state.SetFog(lightlevel, rel, di->isFullbrightScene(), &Colormap, false); - if (!gltexture || !gltexture->tex->isFullbright()) - state.SetObjectColor(FlatColor | 0xff000000); + state.SetObjectColor(FlatColor | 0xff000000); if (!translucent) { @@ -294,7 +327,7 @@ void GLFlat::DrawFlat(HWDrawInfo *di, FRenderState &state, bool translucent) DrawSubsectors(di, state); state.EnableTextureMatrix(false); } - else + else if (!hacktype) { state.SetMaterial(gltexture, CLAMP_XY, 0, -1); state.SetLightIndex(dynlightindex); @@ -302,6 +335,14 @@ void GLFlat::DrawFlat(HWDrawInfo *di, FRenderState &state, bool translucent) flatvertices += 4; flatprimitives++; } + else if (hacktype & SSRF_PLANEHACK) + { + DrawOtherPlanes(di, state); + } + else if (hacktype & SSRF_FLOODHACK) + { + DrawFloodPlanes(di, state); + } state.SetObjectColor(0xffffffff); } else @@ -355,8 +396,6 @@ inline void GLFlat::PutFlat(HWDrawInfo *di, bool fog) //========================================================================== // // This draws one flat -// The passed sector does not indicate the area which is rendered. -// It is only used as source for the plane data. // The whichplane boolean indicates if the flat is a floor(false) or a ceiling(true) // //========================================================================== @@ -394,8 +433,8 @@ void GLFlat::Process(HWDrawInfo *di, sector_t * model, int whichplane, bool fog) iboindex = vert.second; } - - PutFlat(di, fog); + // For hacks this won't go into a render list. + if (hacktype == 0) PutFlat(di, fog); rendered_flats++; } @@ -438,7 +477,7 @@ void GLFlat::SetFrom3DFloor(F3DFloor *rover, bool top, bool underside) // //========================================================================== -void GLFlat::ProcessSector(HWDrawInfo *di, sector_t * frontsector) +void GLFlat::ProcessSector(HWDrawInfo *di, sector_t * frontsector, int which) { lightlist_t * light; FSectorPortal *port; @@ -454,6 +493,7 @@ void GLFlat::ProcessSector(HWDrawInfo *di, sector_t * frontsector) sector = &level.sectors[frontsector->sectornum]; extsector_t::xfloor &x = sector->e->XFloor; dynlightindex = -1; + hacktype = (which & (SSRF_PLANEHACK|SSRF_FLOODHACK)); uint8_t &srf = di->section_renderflags[level.sections.SectionIndex(section)]; const auto &vp = di->Viewpoint; @@ -465,7 +505,7 @@ void GLFlat::ProcessSector(HWDrawInfo *di, sector_t * frontsector) // // // - if (frontsector->floorplane.ZatPoint(vp.Pos) <= vp.Pos.Z) + if ((which & SSRF_RENDERFLOOR) && frontsector->floorplane.ZatPoint(vp.Pos) <= vp.Pos.Z) { // process the original floor first. @@ -477,10 +517,12 @@ void GLFlat::ProcessSector(HWDrawInfo *di, sector_t * frontsector) port = frontsector->ValidatePortal(sector_t::floor); if ((stack = (port != NULL))) { + /* to be redone in a less invasive manner if (port->mType == PORTS_STACKEDSECTORTHING) { di->AddFloorStack(sector); // stacked sector things require visplane merging. } + */ alpha = frontsector->GetAlpha(sector_t::floor); } else @@ -518,7 +560,7 @@ void GLFlat::ProcessSector(HWDrawInfo *di, sector_t * frontsector) // // // - if (frontsector->ceilingplane.ZatPoint(vp.Pos) >= vp.Pos.Z) + if ((which & SSRF_RENDERCEILING) && frontsector->ceilingplane.ZatPoint(vp.Pos) >= vp.Pos.Z) { // process the original ceiling first. @@ -530,10 +572,12 @@ void GLFlat::ProcessSector(HWDrawInfo *di, sector_t * frontsector) port = frontsector->ValidatePortal(sector_t::ceiling); if ((stack = (port != NULL))) { + /* as above for floors if (port->mType == PORTS_STACKEDSECTORTHING) { di->AddCeilingStack(sector); } + */ alpha = frontsector->GetAlpha(sector_t::ceiling); } else @@ -572,7 +616,7 @@ void GLFlat::ProcessSector(HWDrawInfo *di, sector_t * frontsector) // stack = false; - if (x.ffloors.Size()) + if ((which & SSRF_RENDER3DPLANES) && x.ffloors.Size()) { player_t * player = players[consoleplayer].camera->player; diff --git a/src/hwrenderer/scene/hw_renderhacks.cpp b/src/hwrenderer/scene/hw_renderhacks.cpp index 8f3325f2d..6701b0796 100644 --- a/src/hwrenderer/scene/hw_renderhacks.cpp +++ b/src/hwrenderer/scene/hw_renderhacks.cpp @@ -41,6 +41,17 @@ sector_t * hw_FakeFlat(sector_t * sec, sector_t * dest, area_t in_area, bool back); +// Get the nodes from the render data allocator so we don't have to keep track of them ourselves. +static gl_subsectorrendernode *NewSubsectorRenderNode() +{ + return (gl_subsectorrendernode*)RenderDataAllocator.Alloc(sizeof(gl_subsectorrendernode)); +} + +static gl_floodrendernode *NewFloodRenderNode() +{ + return (gl_floodrendernode*)RenderDataAllocator.Alloc(sizeof(gl_floodrendernode)); +} + //========================================================================== // // light setup for render hacks. @@ -110,35 +121,24 @@ int HWDrawInfo::CreateOtherPlaneVertices(subsector_t *sub, const secplane_t *pla void HWDrawInfo::AddOtherFloorPlane(int sector, gl_subsectorrendernode * node) { - int oldcnt = otherfloorplanes.Size(); - - if (oldcnt <= sector) - { - otherfloorplanes.Resize(sector + 1); - for (int i = oldcnt; i <= sector; i++) otherfloorplanes[i] = nullptr; - } - node->next = otherfloorplanes[sector]; + auto pNode = otherFloorPlanes.CheckKey(sector); + + node->next = pNode? *pNode : nullptr; node->lightindex = SetupLightsForOtherPlane(node->sub, lightdata, &level.sectors[sector].floorplane); node->vertexindex = CreateOtherPlaneVertices(node->sub, &level.sectors[sector].floorplane); - otherfloorplanes[sector] = node; + otherFloorPlanes[sector] = node; } void HWDrawInfo::AddOtherCeilingPlane(int sector, gl_subsectorrendernode * node) { - int oldcnt = otherceilingplanes.Size(); - - if (oldcnt <= sector) - { - otherceilingplanes.Resize(sector + 1); - for (int i = oldcnt; i <= sector; i++) otherceilingplanes[i] = nullptr; - } - node->next = otherceilingplanes[sector]; + auto pNode = otherCeilingPlanes.CheckKey(sector); + + node->next = pNode? *pNode : nullptr; node->lightindex = SetupLightsForOtherPlane(node->sub, lightdata, &level.sectors[sector].ceilingplane); node->vertexindex = CreateOtherPlaneVertices(node->sub, &level.sectors[sector].ceilingplane); - otherceilingplanes[sector] = node; + otherCeilingPlanes[sector] = node; } - //========================================================================== // // Collects all sectors that might need a fake ceiling @@ -511,7 +511,7 @@ void HWDrawInfo::HandleMissingTextures(area_t in_area) for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) { - gl_subsectorrendernode * node = new gl_subsectorrendernode; + gl_subsectorrendernode * node = NewSubsectorRenderNode(); node->sub = HandledSubsectors[j]; AddOtherCeilingPlane(sec->sectornum, node); @@ -555,7 +555,7 @@ void HWDrawInfo::HandleMissingTextures(area_t in_area) for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) { - gl_subsectorrendernode * node = new gl_subsectorrendernode; + gl_subsectorrendernode * node = NewSubsectorRenderNode(); node->sub = HandledSubsectors[j]; AddOtherCeilingPlane(fakesector->sectornum, node); } @@ -583,7 +583,7 @@ void HWDrawInfo::HandleMissingTextures(area_t in_area) for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) { - gl_subsectorrendernode * node = new gl_subsectorrendernode; + gl_subsectorrendernode * node = NewSubsectorRenderNode(); node->sub = HandledSubsectors[j]; AddOtherFloorPlane(sec->sectornum, node); } @@ -626,7 +626,7 @@ void HWDrawInfo::HandleMissingTextures(area_t in_area) for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) { - gl_subsectorrendernode * node = new gl_subsectorrendernode; + gl_subsectorrendernode * node = NewSubsectorRenderNode(); node->sub = HandledSubsectors[j]; AddOtherFloorPlane(fakesector->sectornum, node); } @@ -730,19 +730,13 @@ void HWDrawInfo::PrepareUpperGap(seg_t * seg) CreateFloodStencilPoly(&ws, vertices.first); CreateFloodPoly(&ws, vertices.first+4, ws.z2, fakebsector, true); - gl_floodrendernode *node = new gl_floodrendernode; - int oldcnt = floodfloorsegs.Size(); - auto sector = fakebsector->sectornum; - if (oldcnt <= sector) - { - floodfloorsegs.Resize(sector + 1); - for (int i = oldcnt; i <= sector; i++) floodfloorsegs[i] = nullptr; - } + gl_floodrendernode *node = NewFloodRenderNode(); + auto pNode = floodFloorSegs.CheckKey(fakebsector->sectornum); - node->next = floodfloorsegs[sector]; + node->next = pNode? *pNode : nullptr; node->seg = seg; node->vertexindex = vertices.second; - floodfloorsegs[sector] = node; + floodFloorSegs[fakebsector->sectornum] = node; } @@ -794,19 +788,14 @@ void HWDrawInfo::PrepareLowerGap(seg_t * seg) CreateFloodStencilPoly(&ws, vertices.first); CreateFloodPoly(&ws, vertices.first+4, ws.z1, fakebsector, false); - gl_floodrendernode *node = new gl_floodrendernode; - int oldcnt = floodceilingsegs.Size(); - auto sector = fakebsector->sectornum; - if (oldcnt <= sector) - { - floodceilingsegs.Resize(sector + 1); - for (int i = oldcnt; i <= sector; i++) floodceilingsegs[i] = nullptr; - } + gl_floodrendernode *node = NewFloodRenderNode(); + auto pNode = floodCeilingSegs.CheckKey(fakebsector->sectornum); + + node->next = pNode? *pNode : nullptr; - node->next = floodceilingsegs[sector]; node->seg = seg; node->vertexindex = vertices.second; - floodceilingsegs[sector] = node; + floodCeilingSegs[fakebsector->sectornum] = node; } //========================================================================== @@ -1122,8 +1111,7 @@ void HWDrawInfo::HandleHackedSubsectors() { for(unsigned int j=0;jsub = HandledSubsectors[j]; AddOtherFloorPlane(sub->render_sector->sectornum, node); } @@ -1145,8 +1133,7 @@ void HWDrawInfo::HandleHackedSubsectors() { for(unsigned int j=0;jsub = HandledSubsectors[j]; AddOtherCeilingPlane(sub->render_sector->sectornum, node); } @@ -1308,7 +1295,7 @@ void HWDrawInfo::ProcessSectorStacks(area_t in_area) if (sec->GetAlpha(sector_t::ceiling) != 0 && sec->GetTexture(sector_t::ceiling) != skyflatnum) { - gl_subsectorrendernode * node = new gl_subsectorrendernode; + gl_subsectorrendernode * node = NewSubsectorRenderNode(); node->sub = sub; AddOtherCeilingPlane(sec->sectornum, node); } @@ -1353,7 +1340,7 @@ void HWDrawInfo::ProcessSectorStacks(area_t in_area) if (sec->GetAlpha(sector_t::floor) != 0 && sec->GetTexture(sector_t::floor) != skyflatnum) { - gl_subsectorrendernode * node = new gl_subsectorrendernode; + gl_subsectorrendernode * node = NewSubsectorRenderNode(); node->sub = sub; AddOtherFloorPlane(sec->sectornum, node); } From ddc75f7ba5ba18a4db4e41fc57f8dbd47b2ca2b9 Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Tue, 6 Nov 2018 20:31:44 +0100 Subject: [PATCH 14/16] - made the common render hacks functional again as separate render items. --- src/hwrenderer/data/hw_sections.cpp | 8 +- src/hwrenderer/data/hw_sections.h | 17 --- src/hwrenderer/scene/hw_drawinfo.cpp | 2 +- src/hwrenderer/scene/hw_drawinfo.h | 1 + src/hwrenderer/scene/hw_drawlistadd.cpp | 2 +- src/hwrenderer/scene/hw_drawstructs.h | 2 +- src/hwrenderer/scene/hw_flats.cpp | 137 +++++++++++------------- src/hwrenderer/scene/hw_renderhacks.cpp | 61 ++++++++--- src/tarray.h | 5 +- 9 files changed, 122 insertions(+), 113 deletions(-) diff --git a/src/hwrenderer/data/hw_sections.cpp b/src/hwrenderer/data/hw_sections.cpp index 3ef6502c6..c37b37395 100644 --- a/src/hwrenderer/data/hw_sections.cpp +++ b/src/hwrenderer/data/hw_sections.cpp @@ -632,10 +632,9 @@ public: void ConstructOutput(FSectionContainer &output) { output.allSections.Resize(groups.Size()); - output.allIndices.Resize(level.subsectors.Size() + level.sides.Size() + 2*level.sectors.Size()); - output.sectionForSidedefPtr = &output.allIndices[0]; - output.firstSectionForSectorPtr = &output.allIndices[level.sides.Size()]; - output.numberOfSectionForSectorPtr = &output.allIndices[level.sides.Size() + level.sectors.Size()]; + output.allIndices.Resize(2*level.sectors.Size()); + output.firstSectionForSectorPtr = &output.allIndices[0]; + output.numberOfSectionForSectorPtr = &output.allIndices[level.sectors.Size()]; memset(output.firstSectionForSectorPtr, -1, sizeof(int) * level.sectors.Size()); memset(output.numberOfSectionForSectorPtr, 0, sizeof(int) * level.sectors.Size()); @@ -713,7 +712,6 @@ public: while (it.NextPair(pair)) { output.allSides[numsides++] = &level.sides[pair->Key]; - output.sectionForSidedefPtr[pair->Key] = curgroup; } for (auto ssi : group.subsectors) { diff --git a/src/hwrenderer/data/hw_sections.h b/src/hwrenderer/data/hw_sections.h index 668c2ba39..96ab3c250 100644 --- a/src/hwrenderer/data/hw_sections.h +++ b/src/hwrenderer/data/hw_sections.h @@ -102,26 +102,9 @@ public: TArray allSubsectors; TArray allIndices; - int *sectionForSidedefPtr; // also stored inside allIndices; int *firstSectionForSectorPtr; // ditto. int *numberOfSectionForSectorPtr; // ditto. - FSection *SectionForSidedef(side_t *side) - { - return SectionForSidedef(side->Index()); - } - FSection *SectionForSidedef(int sindex) - { - return sindex < 0 ? nullptr : &allSections[sectionForSidedefPtr[sindex]]; - } - int SectionNumForSidedef(side_t *side) - { - return SectionNumForSidedef(side->Index()); - } - int SectionNumForSidedef(int sindex) - { - return sindex < 0 ? -1 : sectionForSidedefPtr[sindex]; - } TArrayView SectionsForSector(sector_t *sec) { return SectionsForSector(sec->Index()); diff --git a/src/hwrenderer/scene/hw_drawinfo.cpp b/src/hwrenderer/scene/hw_drawinfo.cpp index 0dd67634e..2dc9aef04 100644 --- a/src/hwrenderer/scene/hw_drawinfo.cpp +++ b/src/hwrenderer/scene/hw_drawinfo.cpp @@ -441,8 +441,8 @@ void HWDrawInfo::CreateScene() HandleMissingTextures(in_area); // Missing upper/lower textures HandleHackedSubsectors(); // open sector hacks for deep water - ProcessSectorStacks(in_area); // merge visplanes of sector stacks PrepareUnhandledMissingTextures(); + DispatchRenderHacks(); screen->mLights->Unmap(); screen->mVertexData->Unmap(); diff --git a/src/hwrenderer/scene/hw_drawinfo.h b/src/hwrenderer/scene/hw_drawinfo.h index e40c361ef..58951473b 100644 --- a/src/hwrenderer/scene/hw_drawinfo.h +++ b/src/hwrenderer/scene/hw_drawinfo.h @@ -264,6 +264,7 @@ public: void CollectSectorStacksCeiling(subsector_t * sub, sector_t * anchor, area_t in_area); void CollectSectorStacksFloor(subsector_t * sub, sector_t * anchor, area_t in_area); + void DispatchRenderHacks(); void AddUpperMissingTexture(side_t * side, subsector_t *sub, float backheight); void AddLowerMissingTexture(side_t * side, subsector_t *sub, float backheight); void HandleMissingTextures(area_t in_area); diff --git a/src/hwrenderer/scene/hw_drawlistadd.cpp b/src/hwrenderer/scene/hw_drawlistadd.cpp index a1657b396..0ab682bd7 100644 --- a/src/hwrenderer/scene/hw_drawlistadd.cpp +++ b/src/hwrenderer/scene/hw_drawlistadd.cpp @@ -116,7 +116,7 @@ void HWDrawInfo::AddFlat(GLFlat *flat, bool fog) list = GLDL_PLAINFLATS; } } - else + else //if (flat->hacktype != SSRF_FLOODHACK) // The flood hack may later need different treatment but with the current setup can go into the existing render list. { bool masked = flat->gltexture->isMasked() && ((flat->renderflags&SSRF_RENDER3DPLANES) || flat->stack); list = masked ? GLDL_MASKEDFLATS : GLDL_PLAINFLATS; diff --git a/src/hwrenderer/scene/hw_drawstructs.h b/src/hwrenderer/scene/hw_drawstructs.h index dd63e5bd2..35a6d340e 100644 --- a/src/hwrenderer/scene/hw_drawstructs.h +++ b/src/hwrenderer/scene/hw_drawstructs.h @@ -320,7 +320,7 @@ public: void PutFlat(HWDrawInfo *di, bool fog = false); void Process(HWDrawInfo *di, sector_t * model, int whichplane, bool notexture); void SetFrom3DFloor(F3DFloor *rover, bool top, bool underside); - void ProcessSector(HWDrawInfo *di, sector_t * frontsector, int which = SSRF_RENDERALL); + void ProcessSector(HWDrawInfo *di, sector_t * frontsector, int which = 7 /*SSRF_RENDERALL*/); // cannot use constant due to circular dependencies. void DrawSubsectors(HWDrawInfo *di, FRenderState &state); void DrawFlat(HWDrawInfo *di, FRenderState &state, bool translucent); diff --git a/src/hwrenderer/scene/hw_flats.cpp b/src/hwrenderer/scene/hw_flats.cpp index 4872c6e43..553b934bd 100644 --- a/src/hwrenderer/scene/hw_flats.cpp +++ b/src/hwrenderer/scene/hw_flats.cpp @@ -203,7 +203,7 @@ void GLFlat::DrawSubsectors(HWDrawInfo *di, FRenderState &state) void GLFlat::DrawOtherPlanes(HWDrawInfo *di, FRenderState &state) { - state.SetMaterial(gltexture, CLAMP_XY, 0, -1); + state.SetMaterial(gltexture, CLAMP_NONE, 0, -1); // Draw the subsectors assigned to it due to missing textures auto pNode = (renderflags&SSRF_RENDERFLOOR) ? @@ -231,68 +231,58 @@ void GLFlat::DrawOtherPlanes(HWDrawInfo *di, FRenderState &state) void GLFlat::DrawFloodPlanes(HWDrawInfo *di, FRenderState &state) { - // Flood gaps with the back side's ceiling/floor texture - // This requires a stencil because the projected plane interferes with - // the depth buffer - - state.SetMaterial(gltexture, CLAMP_XY, 0, -1); - - // Draw the subsectors assigned to it due to missing textures - auto pNode = (renderflags&SSRF_RENDERFLOOR) ? - di->floodFloorSegs.CheckKey(sector->sectornum) : di->floodCeilingSegs.CheckKey(sector->sectornum); - - if (!pNode) return; - auto node = *pNode; - - while (node) - { + // Flood gaps with the back side's ceiling/floor texture + // This requires a stencil because the projected plane interferes with + // the depth buffer - auto pNode = (renderflags&SSRF_RENDERFLOOR) ? - di->floodFloorSegs.CheckKey(sector->sectornum) : di->floodCeilingSegs.CheckKey(sector->sectornum); - if (!pNode) return; - - auto fnode = *pNode; + state.SetMaterial(gltexture, CLAMP_NONE, 0, -1); + + // Draw the subsectors assigned to it due to missing textures + auto pNode = (renderflags&SSRF_RENDERFLOOR) ? + di->floodFloorSegs.CheckKey(sector->sectornum) : di->floodCeilingSegs.CheckKey(sector->sectornum); + if (!pNode) return; + + auto fnode = *pNode; + + state.SetLightIndex(-1); + while (fnode) + { + flatvertices += 12; + flatprimitives += 3; + + // Push bleeding floor/ceiling textures back a little in the z-buffer + // so they don't interfere with overlapping mid textures. + state.SetDepthBias(1, 128); + + // Create stencil + state.SetEffect(EFF_STENCIL); + state.EnableTexture(false); + state.SetStencil(0, SOP_Increment, SF_ColorMaskOff); + state.Draw(DT_TriangleFan, fnode->vertexindex, 4); + + // Draw projected plane into stencil + state.EnableTexture(true); + state.SetEffect(EFF_NONE); + state.SetStencil(1, SOP_Keep, SF_DepthMaskOff); + state.EnableDepthTest(false); + state.Draw(DT_TriangleFan, fnode->vertexindex + 4, 4); + + // clear stencil + state.SetEffect(EFF_STENCIL); + state.EnableTexture(false); + state.SetStencil(1, SOP_Decrement, SF_ColorMaskOff | SF_DepthMaskOff); + state.Draw(DT_TriangleFan, fnode->vertexindex, 4); + + // restore old stencil op. + state.EnableTexture(true); + state.EnableDepthTest(true); + state.SetEffect(EFF_NONE); + state.SetDepthBias(0, 0); + state.SetStencil(0, SOP_Keep, SF_AllOn); + + fnode = fnode->next; + } - state.SetLightIndex(-1); - while (fnode) - { - flatvertices += 12; - flatprimitives += 3; - - // Push bleeding floor/ceiling textures back a little in the z-buffer - // so they don't interfere with overlapping mid textures. - state.SetDepthBias(1, 128); - - // Create stencil - state.SetEffect(EFF_STENCIL); - state.EnableTexture(false); - state.SetStencil(0, SOP_Increment, SF_ColorMaskOff); - state.Draw(DT_TriangleFan,fnode->vertexindex, 4); - - // Draw projected plane into stencil - state.EnableTexture(true); - state.SetEffect(EFF_NONE); - state.SetStencil(1, SOP_Keep, SF_DepthMaskOff); - state.EnableDepthTest(false); - state.Draw(DT_TriangleFan,fnode->vertexindex + 4, 4); - - // clear stencil - state.SetEffect(EFF_STENCIL); - state.EnableTexture(false); - state.SetStencil(1, SOP_Decrement, SF_ColorMaskOff | SF_DepthMaskOff); - state.Draw(DT_TriangleFan,fnode->vertexindex, 4); - - // restore old stencil op. - state.EnableTexture(true); - state.EnableDepthTest(true); - state.SetEffect(EFF_NONE); - state.SetDepthBias(0, 0); - state.SetStencil(0, SOP_Keep, SF_AllOn); - - fnode = fnode->next; - } - - } } @@ -318,7 +308,15 @@ void GLFlat::DrawFlat(HWDrawInfo *di, FRenderState &state, bool translucent) state.SetFog(lightlevel, rel, di->isFullbrightScene(), &Colormap, false); state.SetObjectColor(FlatColor | 0xff000000); - if (!translucent) + if (hacktype & SSRF_PLANEHACK) + { + DrawOtherPlanes(di, state); + } + else if (hacktype & SSRF_FLOODHACK) + { + DrawFloodPlanes(di, state); + } + else if (!translucent) { if (sector->special != GLSector_Skybox) { @@ -335,14 +333,6 @@ void GLFlat::DrawFlat(HWDrawInfo *di, FRenderState &state, bool translucent) flatvertices += 4; flatprimitives++; } - else if (hacktype & SSRF_PLANEHACK) - { - DrawOtherPlanes(di, state); - } - else if (hacktype & SSRF_FLOODHACK) - { - DrawFloodPlanes(di, state); - } state.SetObjectColor(0xffffffff); } else @@ -385,7 +375,7 @@ inline void GLFlat::PutFlat(HWDrawInfo *di, bool fog) } else if (!screen->BuffersArePersistent()) { - if (level.HasDynamicLights && gltexture != nullptr) + if (level.HasDynamicLights && gltexture != nullptr && !(hacktype & (SSRF_PLANEHACK|SSRF_FLOODHACK)) ) { SetupLights(di, section->lighthead, lightdata, sector->PortalGroup); } @@ -434,7 +424,7 @@ void GLFlat::Process(HWDrawInfo *di, sector_t * model, int whichplane, bool fog) } // For hacks this won't go into a render list. - if (hacktype == 0) PutFlat(di, fog); + PutFlat(di, fog); rendered_flats++; } @@ -495,7 +485,8 @@ void GLFlat::ProcessSector(HWDrawInfo *di, sector_t * frontsector, int which) dynlightindex = -1; hacktype = (which & (SSRF_PLANEHACK|SSRF_FLOODHACK)); - uint8_t &srf = di->section_renderflags[level.sections.SectionIndex(section)]; + uint8_t sink; + uint8_t &srf = hacktype? sink : di->section_renderflags[level.sections.SectionIndex(section)]; const auto &vp = di->Viewpoint; // diff --git a/src/hwrenderer/scene/hw_renderhacks.cpp b/src/hwrenderer/scene/hw_renderhacks.cpp index 6701b0796..82610c792 100644 --- a/src/hwrenderer/scene/hw_renderhacks.cpp +++ b/src/hwrenderer/scene/hw_renderhacks.cpp @@ -41,7 +41,55 @@ sector_t * hw_FakeFlat(sector_t * sec, sector_t * dest, area_t in_area, bool back); +//========================================================================== +// +// Create render list entries from the data generated below +// +//========================================================================== + +void HWDrawInfo::DispatchRenderHacks() +{ + TMap::Pair *pair; + TMap::Pair *fpair; + TMap::Iterator ofi(otherFloorPlanes); + GLFlat glflat; + sector_t fakesec; + glflat.section = nullptr; + while (ofi.NextPair(pair)) + { + auto sec = hw_FakeFlat(&level.sectors[pair->Key], &fakesec, in_area, false); + glflat.ProcessSector(this, sec, SSRF_RENDERFLOOR | SSRF_PLANEHACK); + } + + TMap::Iterator oci(otherCeilingPlanes); + while (ofi.NextPair(pair)) + { + auto sec = hw_FakeFlat(&level.sectors[pair->Key], &fakesec, in_area, false); + glflat.ProcessSector(this, sec, SSRF_RENDERCEILING | SSRF_PLANEHACK); + } + + TMap::Iterator ffi(floodFloorSegs); + while (ffi.NextPair(fpair)) + { + auto sec = hw_FakeFlat(&level.sectors[fpair->Key], &fakesec, in_area, false); + glflat.ProcessSector(this, sec, SSRF_RENDERFLOOR | SSRF_FLOODHACK); + } + + TMap::Iterator fci(floodCeilingSegs); + while (fci.NextPair(fpair)) + { + auto sec = hw_FakeFlat(&level.sectors[fpair->Key], &fakesec, in_area, false); + glflat.ProcessSector(this, sec, SSRF_RENDERCEILING | SSRF_FLOODHACK); + } +} + + +//========================================================================== +// // Get the nodes from the render data allocator so we don't have to keep track of them ourselves. +// +//========================================================================== + static gl_subsectorrendernode *NewSubsectorRenderNode() { return (gl_subsectorrendernode*)RenderDataAllocator.Alloc(sizeof(gl_subsectorrendernode)); @@ -506,9 +554,6 @@ void HWDrawInfo::HandleMissingTextures(area_t in_area) if (DoOneSectorUpper(MissingUpperTextures[i].sub, MissingUpperTextures[i].Planez, in_area)) { sector_t * sec = MissingUpperTextures[i].seg->backsector; - // The mere fact that this seg has been added to the list means that the back sector - // will be rendered so we can safely assume that it is already in the render list - for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) { gl_subsectorrendernode * node = NewSubsectorRenderNode(); @@ -550,9 +595,6 @@ void HWDrawInfo::HandleMissingTextures(area_t in_area) backsub->validcount = validcount; if (DoFakeCeilingBridge(backsub, planez, in_area)) { - // The mere fact that this seg has been added to the list means that the back sector - // will be rendered so we can safely assume that it is already in the render list - for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) { gl_subsectorrendernode * node = NewSubsectorRenderNode(); @@ -578,8 +620,6 @@ void HWDrawInfo::HandleMissingTextures(area_t in_area) if (DoOneSectorLower(MissingLowerTextures[i].sub, MissingLowerTextures[i].Planez, in_area)) { sector_t * sec = MissingLowerTextures[i].seg->backsector; - // The mere fact that this seg has been added to the list means that the back sector - // will be rendered so we can safely assume that it is already in the render list for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) { @@ -621,9 +661,6 @@ void HWDrawInfo::HandleMissingTextures(area_t in_area) backsub->validcount = validcount; if (DoFakeBridge(backsub, planez, in_area)) { - // The mere fact that this seg has been added to the list means that the back sector - // will be rendered so we can safely assume that it is already in the render list - for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) { gl_subsectorrendernode * node = NewSubsectorRenderNode(); @@ -840,8 +877,6 @@ void HWDrawInfo::PrepareUnhandledMissingTextures() if (seg->linedef->validcount == validcount) continue; // already done seg->linedef->validcount = validcount; - int section = level.sections.SectionNumForSidedef(seg->sidedef); - if (!(section_renderflags[section] & SSRF_RENDERFLOOR)) continue; if (seg->frontsector->GetPlaneTexZ(sector_t::floor) > Viewpoint.Pos.Z) continue; // out of sight if (seg->backsector->transdoor) continue; if (seg->backsector->GetTexture(sector_t::floor) == skyflatnum) continue; diff --git a/src/tarray.h b/src/tarray.h index 4a0d1570f..7e8c53f06 100644 --- a/src/tarray.h +++ b/src/tarray.h @@ -536,8 +536,9 @@ public: } }; -// This is not a real dynamic array but just a wrapper around a pointer reference. -// Used for wrapping some memory allocated elsewhere into a VM compatible data structure. +// This is only used for exposing the sector's Lines array to ZScript. +// This also must be trivial so that sector_t remains trivial. +// For other uses TArrayView should be preferred. template class TStaticPointedArray From 085bf0d33f7a180eb901a78fc29c6a5db316d3dd Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Tue, 6 Nov 2018 20:53:45 +0100 Subject: [PATCH 15/16] - fixed Transfer_Heights and 3D floors. --- src/hwrenderer/data/flatvertices.cpp | 14 ++++++++------ src/hwrenderer/data/flatvertices.h | 2 +- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/hwrenderer/data/flatvertices.cpp b/src/hwrenderer/data/flatvertices.cpp index b95e66bdf..6ba517bdf 100644 --- a/src/hwrenderer/data/flatvertices.cpp +++ b/src/hwrenderer/data/flatvertices.cpp @@ -185,20 +185,20 @@ int FFlatVertexBuffer::CreateIndexedSectorVertices(sector_t *sec, const secplane // //========================================================================== -int FFlatVertexBuffer::CreateIndexedVertices(int h, sector_t *sec, const secplane_t &plane, int floor, VertexContainer &verts) +int FFlatVertexBuffer::CreateIndexedVertices(int h, sector_t *sec, const secplane_t &plane, int floor, VertexContainers &verts) { sec->vboindex[h] = vbo_shadowdata.Size(); // First calculate the vertices for the sector itself sec->vboheight[h] = sec->GetPlaneTexZ(h); - sec->ibocount = verts.indices.Size(); - sec->iboindex[h] = CreateIndexedSectorVertices(sec, plane, floor, verts); + sec->ibocount = verts[sec->Index()].indices.Size(); + sec->iboindex[h] = CreateIndexedSectorVertices(sec, plane, floor, verts[sec->Index()]); // Next are all sectors using this one as heightsec TArray &fakes = sec->e->FakeFloor.Sectors; for (unsigned g = 0; g < fakes.Size(); g++) { sector_t *fsec = fakes[g]; - fsec->iboindex[2 + h] = CreateIndexedSectorVertices(fsec, plane, false, verts); + fsec->iboindex[2 + h] = CreateIndexedSectorVertices(fsec, plane, false, verts[fsec->Index()]); } // and finally all attached 3D floors @@ -215,7 +215,7 @@ int FFlatVertexBuffer::CreateIndexedVertices(int h, sector_t *sec, const secplan if (dotop || dobottom) { - auto ndx = CreateIndexedSectorVertices(fsec, plane, false, verts); + auto ndx = CreateIndexedSectorVertices(fsec, plane, false, verts[fsec->Index()]); if (dotop) ffloor->top.vindex = ndx; if (dobottom) ffloor->bottom.vindex = ndx; } @@ -237,6 +237,7 @@ void FFlatVertexBuffer::CreateIndexedFlatVertices() auto verts = BuildVertices(); int i = 0; + /* for (auto &vert : verts) { Printf(PRINT_LOG, "Sector %d\n", i); @@ -253,13 +254,14 @@ void FFlatVertexBuffer::CreateIndexedFlatVertices() i++; } + */ for (int h = sector_t::floor; h <= sector_t::ceiling; h++) { for (auto &sec : level.sectors) { - CreateIndexedVertices(h, &sec, sec.GetSecPlane(h), h == sector_t::floor, verts[sec.Index()]); + CreateIndexedVertices(h, &sec, sec.GetSecPlane(h), h == sector_t::floor, verts); } } diff --git a/src/hwrenderer/data/flatvertices.h b/src/hwrenderer/data/flatvertices.h index 17458e064..890e5580c 100644 --- a/src/hwrenderer/data/flatvertices.h +++ b/src/hwrenderer/data/flatvertices.h @@ -118,7 +118,7 @@ public: private: int CreateIndexedSectionVertices(subsector_t *sub, const secplane_t &plane, int floor, VertexContainer &cont); int CreateIndexedSectorVertices(sector_t *sec, const secplane_t &plane, int floor, VertexContainer &cont); - int CreateIndexedVertices(int h, sector_t *sec, const secplane_t &plane, int floor, VertexContainer &cont); + int CreateIndexedVertices(int h, sector_t *sec, const secplane_t &plane, int floor, VertexContainers &cont); void CreateIndexedFlatVertices(); void UpdatePlaneVertices(sector_t *sec, int plane); From f2e593f8bf358a2324bf8cc61a3de5469ac9f802 Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Tue, 6 Nov 2018 21:41:16 +0100 Subject: [PATCH 16/16] - disabled the hack for fixing the original design of the portal in KDiZD's Z1M1. This portal got fixed in a later re-release of KDiZD and no other portal needs this runtime fix to my knowledge. The main problem here is that this runtime fix requires some manipulation of the render data that does not work anymore. Should other maps need this fix as well they are probably best served with a compatibility entry. --- src/hwrenderer/scene/hw_bsp.cpp | 14 -------------- src/hwrenderer/scene/hw_drawinfo.cpp | 4 ++-- src/hwrenderer/scene/hw_drawinfo.h | 5 ++--- src/hwrenderer/scene/hw_renderhacks.cpp | 6 ++++++ 4 files changed, 10 insertions(+), 19 deletions(-) diff --git a/src/hwrenderer/scene/hw_bsp.cpp b/src/hwrenderer/scene/hw_bsp.cpp index affca42a8..075a93d8f 100644 --- a/src/hwrenderer/scene/hw_bsp.cpp +++ b/src/hwrenderer/scene/hw_bsp.cpp @@ -702,20 +702,6 @@ void HWDrawInfo::DoSubsector(subsector_t * sub) ss_renderflags[sub->Index()] = (sub->numlines > 2) ? SSRF_PROCESSED|SSRF_RENDERALL : SSRF_PROCESSED; if (sub->hacked & 1) AddHackedSubsector(sub); - - FSectorPortalGroup *portal; - - portal = fakesector->GetPortalGroup(sector_t::ceiling); - if (portal != nullptr) - { - AddSubsectorToPortal(portal, sub); - } - - portal = fakesector->GetPortalGroup(sector_t::floor); - if (portal != nullptr) - { - AddSubsectorToPortal(portal, sub); - } } } } diff --git a/src/hwrenderer/scene/hw_drawinfo.cpp b/src/hwrenderer/scene/hw_drawinfo.cpp index 2dc9aef04..40bdb8a7a 100644 --- a/src/hwrenderer/scene/hw_drawinfo.cpp +++ b/src/hwrenderer/scene/hw_drawinfo.cpp @@ -187,8 +187,8 @@ void HWDrawInfo::ClearBuffers() MissingUpperSegs.Clear(); MissingLowerSegs.Clear(); SubsectorHacks.Clear(); - CeilingStacks.Clear(); - FloorStacks.Clear(); + //CeilingStacks.Clear(); + //FloorStacks.Clear(); HandledSubsectors.Clear(); spriteindex = 0; diff --git a/src/hwrenderer/scene/hw_drawinfo.h b/src/hwrenderer/scene/hw_drawinfo.h index 58951473b..33074b0fd 100644 --- a/src/hwrenderer/scene/hw_drawinfo.h +++ b/src/hwrenderer/scene/hw_drawinfo.h @@ -167,8 +167,8 @@ struct HWDrawInfo TMap floodFloorSegs; TMap floodCeilingSegs; - TArray CeilingStacks; - TArray FloorStacks; + //TArray CeilingStacks; + //TArray FloorStacks; TArray HandledSubsectors; @@ -300,7 +300,6 @@ public: void DrawPlayerSprites(bool hudModelStep, FRenderState &state); void ProcessLowerMinisegs(TArray &lowersegs); - void AddSubsectorToPortal(FSectorPortalGroup *portal, subsector_t *sub); void AddWall(GLWall *w); void AddMirrorSurface(GLWall *w); diff --git a/src/hwrenderer/scene/hw_renderhacks.cpp b/src/hwrenderer/scene/hw_renderhacks.cpp index 82610c792..1558b4bba 100644 --- a/src/hwrenderer/scene/hw_renderhacks.cpp +++ b/src/hwrenderer/scene/hw_renderhacks.cpp @@ -1180,6 +1180,11 @@ void HWDrawInfo::HandleHackedSubsectors() SubsectorHacks.Clear(); } +// This code was meant to fix the portal in KDIZD's Z1M1, but later versions of that mod do not need it anymore. +// I am not aware of other portals ever having been set up so badly as this one so it probably is not needed anymore. +// Even if needed this must be done differently because this code depends on hacking the render data in a bad way. +#if 0 + //========================================================================== // // This merges visplanes that lie inside a sector stack together @@ -1406,3 +1411,4 @@ void HWDrawInfo::AddSubsectorToPortal(FSectorPortalGroup *ptg, subsector_t *sub) ptl->AddSubsector(sub); } +#endif