From 8ee54f4007390101d6d5844b7bace67157033de0 Mon Sep 17 00:00:00 2001 From: Unreal Karaulov Date: Sun, 17 Nov 2024 12:19:03 +0300 Subject: [PATCH] Fix nav stuff. Fix sprites scale (use model bbox), Fix nav stuff. Fix sprites scale (use model bbox), optimizations, bug fixes, bug adding, etc --- resources/languages/language.ini | 2 +- resources/languages/language_ru.ini | 2 +- src/bsp/Bsp.cpp | 80 +++-- src/bsp/BspMerger.cpp | 9 +- src/bsp/Entity.cpp | 2 +- src/bsp/Entity.h | 2 +- src/editor/BspRenderer.cpp | 71 +++-- src/editor/Command.cpp | 5 +- src/editor/Fgd.cpp | 2 +- src/editor/Gui.cpp | 367 ++++++++++++----------- src/editor/Renderer.cpp | 214 +++++++------- src/editor/Settings.cpp | 20 +- src/gl/ShaderProgram.cpp | 436 +++++++++++++--------------- src/gl/Texture.cpp | 309 ++++++++++---------- src/gl/VertexBuffer.cpp | 238 +++++++-------- src/gl/VertexBuffer.h | 4 +- src/main.cpp | 2 +- src/mdl/mdl_studio.cpp | 21 +- src/nav/LeafNavMesh.cpp | 4 +- src/nav/LeafNavMeshGenerator.cpp | 16 +- src/nav/LeafNavMeshGenerator.h | 2 +- src/nav/LeafOctree.cpp | 10 +- src/nav/LeafOctree.h | 4 +- src/nav/NavMeshGenerator.cpp | 4 +- src/nav/NavMeshGenerator.h | 2 +- src/nav/PolyOctree.cpp | 10 +- src/nav/PolyOctree.h | 4 +- src/res/Sprite.cpp | 42 ++- src/res/Sprite.h | 5 +- src/util/Line2D.h | 2 +- src/util/Polygon3D.cpp | 14 +- src/util/Polygon3D.h | 2 +- src/util/quantizer.cpp | 9 +- src/util/quantizer.h | 2 +- src/util/vectors.h | 40 +-- 35 files changed, 979 insertions(+), 979 deletions(-) diff --git a/resources/languages/language.ini b/resources/languages/language.ini index 21badcd8..9ba796f6 100644 --- a/resources/languages/language.ini +++ b/resources/languages/language.ini @@ -279,7 +279,7 @@ LANG_0276 = Loaded {} lightmaps into {} atlases\n LANG_0277 = TODO: Recalculate lightmaps when faces deleted\n LANG_0278 = Added {} empty lightmaps after face added\n LANG_0279 = Added new solid render group.\n -LANG_0280 = Bad model idx\n +LANG_0280 = Bad model idx {} of {}\n LANG_0281 = {} for {} {}\n LANG_0282 = Degenerate clipnode face discarded\n LANG_0283 = Failed to find non-duplicate vert for clipnode face\n diff --git a/resources/languages/language_ru.ini b/resources/languages/language_ru.ini index 85aa64ee..95bcb70d 100644 --- a/resources/languages/language_ru.ini +++ b/resources/languages/language_ru.ini @@ -279,7 +279,7 @@ LANG_0276 = Загружено {} лайтмап в {} атласах\n LANG_0277 = TODO: Перерасчёт лайтмап после удаления фейсов\n LANG_0278 = Добавлено {} пустых лайтмап после добавления фейса\n LANG_0279 = Добавлена новая группа рендерера солидов.\n -LANG_0280 = Некорректный индекс модели\n +LANG_0280 = Некорректный индекс модели {} из {}\n LANG_0281 = {} для {} {}\n LANG_0282 = Удалена деформированная грань клипноды\n LANG_0283 = Не удалось найти уникальную вершину для грани клипноды\n diff --git a/src/bsp/Bsp.cpp b/src/bsp/Bsp.cpp index ed8a69f7..500db376 100644 --- a/src/bsp/Bsp.cpp +++ b/src/bsp/Bsp.cpp @@ -448,7 +448,7 @@ void Bsp::get_model_vertex_bounds(int modelIdx, vec3& mins, vec3& maxs) std::vector solidMeshes; for (int k = 0; k < solidNodes.size(); k++) { - solidMeshes.push_back(clipper.clip(solidNodes[k].cuts)); + solidMeshes.emplace_back(clipper.clip(solidNodes[k].cuts)); } for (int m = 0; m < solidMeshes.size(); m++) { @@ -460,8 +460,6 @@ void Bsp::get_model_vertex_bounds(int modelIdx, vec3& mins, vec3& maxs) continue; } - std::set uniqueFaceVerts; - for (int k = 0; k < mesh.faces[i].edges.size(); k++) { for (int v = 0; v < 2; v++) { int vertIdx = mesh.edges[mesh.faces[i].edges[k]].verts[v]; @@ -870,29 +868,24 @@ bool Bsp::vertex_manipulation_sync(int modelIdx, const std::vector affectedPlanes; - std::map> planeVerts; std::vector allVertPos; - for (size_t i = 0; i < hullVerts.size(); i++) + for (const auto& vert : hullVerts) { - for (size_t k = 0; k < hullVerts[i].iPlanes.size(); k++) { - int iPlane = hullVerts[i].iPlanes[k]; - affectedPlanes.insert(hullVerts[i].iPlanes[k]); - planeVerts[iPlane].push_back(hullVerts[i].pos); + for (int iPlane : vert.iPlanes) + { + affectedPlanes.insert(iPlane); + planeVerts[iPlane].push_back(vert.pos); } - allVertPos.push_back(hullVerts[i].pos); + allVertPos.push_back(vert.pos); } int planeUpdates = 0; std::map newPlanes; std::map shouldFlipChildren; - for (auto it = planeVerts.begin(); it != planeVerts.end(); ++it) + for (const auto& [iPlane, tverts] : planeVerts) { - int iPlane = it->first; - - std::vector& tverts = it->second; - if (tverts.size() < 3) { if (g_settings.verboseLogs) @@ -900,6 +893,12 @@ bool Bsp::vertex_manipulation_sync(int modelIdx, const std::vector= planeCount) + { + print_log("Fatal error sync plane bad {} of {}\n", iPlane, planeCount); + return false; // invalid solid + } + BSPPLANE newPlane; if (!getPlaneFromVerts(tverts, newPlane.vNormal, newPlane.fDist)) { @@ -935,11 +934,8 @@ bool Bsp::vertex_manipulation_sync(int modelIdx, const std::vectorfirst; - BSPPLANE& newPlane = it->second; - planes[iPlane] = newPlane; planeUpdates++; @@ -958,15 +954,13 @@ bool Bsp::vertex_manipulation_sync(int modelIdx, const std::vector newVisitedClipnodes(newClipnodeCount, false); - remappedStuff.visitedClipnodes = newVisitedClipnodes; + remappedStuff.visitedClipnodes = std::move(newVisitedClipnodes); remap_model_structures(modelIdx, &remappedStuff); @@ -2936,7 +2930,7 @@ void Bsp::delete_oob_data(int clipFlags) { int deletedEnts = (int)ents.size() - (int)newEnts.size(); if (deletedEnts) print_log(" Deleted {} entities\n", deletedEnts); - ents = newEnts; + ents = std::move(newEnts); unsigned char* oobFaces = new unsigned char[faceCount]; memset(oobFaces, 0, faceCount * sizeof(bool)); @@ -3034,6 +3028,7 @@ void Bsp::delete_oob_data(int clipFlags) { leaf.iFirstMarkSurface = 0; if (oobCount != leaf.nMarkSurfaces) { + // always true //print_log("leaf {} partially OOB\n", i); } } @@ -3262,7 +3257,7 @@ void Bsp::delete_box_data(vec3 clipMins, vec3 clipMaxs) { int deletedEnts = (int)ents.size() - (int)newEnts.size(); if (deletedEnts) print_log(" Deleted {} entities\n", deletedEnts); - ents = newEnts; + ents = std::move(newEnts); unsigned char* oobFaces = new unsigned char[faceCount]; memset(oobFaces, 0, faceCount * sizeof(bool)); @@ -3353,6 +3348,7 @@ void Bsp::delete_box_data(vec3 clipMins, vec3 clipMaxs) { leaf.iFirstMarkSurface = 0; if (oobCount != leaf.nMarkSurfaces) { + // always true //print_log("leaf {} partially OOB\n", i); } } @@ -8716,12 +8712,12 @@ int Bsp::create_node_box(const vec3& mins, const vec3& maxs, BSPMODEL* targetMod std::vector addPlanes; std::vector addNodes; - addPlanes.push_back({ vec3(1.0f, 0.0f, 0.0f), min.x, PLANE_X }); // left - addPlanes.push_back({ vec3(1.0f, 0.0f, 0.0f), max.x, PLANE_X }); // right - addPlanes.push_back({ vec3(0.0f, 1.0f, 0.0f), min.y, PLANE_Y }); // front - addPlanes.push_back({ vec3(0.0f, 1.0f, 0.0f), max.y, PLANE_Y }); // back - addPlanes.push_back({ vec3(0.0f, 0.0f, 1.0f), min.z, PLANE_Z }); // bottom - addPlanes.push_back({ vec3(0.0f, 0.0f, 1.0f), max.z, PLANE_Z }); // top + addPlanes.emplace_back(vec3(1.0f, 0.0f, 0.0f), min.x, PLANE_X); // left + addPlanes.emplace_back(vec3(1.0f, 0.0f, 0.0f), max.x, PLANE_X); // right + addPlanes.emplace_back(vec3(0.0f, 1.0f, 0.0f), min.y, PLANE_Y); // front + addPlanes.emplace_back(vec3(0.0f, 1.0f, 0.0f), max.y, PLANE_Y); // back + addPlanes.emplace_back(vec3(0.0f, 0.0f, 1.0f), min.z, PLANE_Z); // bottom + addPlanes.emplace_back(vec3(0.0f, 0.0f, 1.0f), max.z, PLANE_Z); // top int solidNodeIdx = 0; @@ -8792,12 +8788,12 @@ int Bsp::create_clipnode_box(const vec3& mins, const vec3& maxs, BSPMODEL* targe int clipnodeIdx = clipnodeCount + (int)addNodes.size(); int planeIdx = planeCount + (int)addPlanes.size(); - addPlanes.push_back({ vec3(1.0f, 0.0f, 0.0f), min.x, PLANE_X }); // left - addPlanes.push_back({ vec3(1.0f, 0.0f, 0.0f), max.x, PLANE_X }); // right - addPlanes.push_back({ vec3(0.0f, 1.0f, 0.0f), min.y, PLANE_Y }); // front - addPlanes.push_back({ vec3(0.0f, 1.0f, 0.0f), max.y, PLANE_Y }); // back - addPlanes.push_back({ vec3(0.0f, 0.0f, 1.0f), min.z, PLANE_Z }); // bottom - addPlanes.push_back({ vec3(0.0f, 0.0f, 1.0f), max.z, PLANE_Z }); // top + addPlanes.emplace_back(vec3(1.0f, 0.0f, 0.0f), min.x, PLANE_X); // left + addPlanes.emplace_back(vec3(1.0f, 0.0f, 0.0f), max.x, PLANE_X); // right + addPlanes.emplace_back(vec3(0.0f, 1.0f, 0.0f), min.y, PLANE_Y); // front + addPlanes.emplace_back(vec3(0.0f, 1.0f, 0.0f), max.y, PLANE_Y); // back + addPlanes.emplace_back(vec3(0.0f, 0.0f, 1.0f), min.z, PLANE_Z); // bottom + addPlanes.emplace_back(vec3(0.0f, 0.0f, 1.0f), max.z, PLANE_Z); // top targetModel->iHeadnodes[i] = clipnodeCount + (int)addNodes.size(); @@ -8902,7 +8898,7 @@ int Bsp::create_clipnode(bool force_reversed, int reversed_id) for (int i = 0; i < clipnodeCount; i++) { if (i == reversed_id) - newNodes.push_back(BSPCLIPNODE32()); + newNodes.emplace_back(BSPCLIPNODE32()); newNodes.push_back(clipnodes[i]); } @@ -8950,7 +8946,7 @@ int Bsp::create_node(bool force_reversed, int reversed_id) for (int i = 0; i < nodeCount; i++) { if (i == reversed_id) - newNodes.push_back(BSPNODE32()); + newNodes.emplace_back(BSPNODE32()); newNodes.push_back(nodes[i]); } @@ -11257,7 +11253,7 @@ void Bsp::ExportToSmdWIP(const std::string& path, bool split, bool oneRoot) } } if (!found) - total_verts.push_back({ t.verts[v],bones_to[t.boneid] }); + total_verts.emplace_back(t.verts[v],bones_to[t.boneid]); } bool found = false; @@ -11845,7 +11841,7 @@ void Bsp::ExportToObjWIP(const std::string& path, int iscale, bool lightmapmode, rndColor.b = 50 + rand() % 206; rndColor.a = 255; - csm_export->vertices.push_back({ org_pos,org_norm,rndColor }); + csm_export->vertices.emplace_back(org_pos,org_norm,rndColor); int cur_faceIdx = (int)(csm_export->faces.size()) - 1; if (cur_faceIdx >= 0) diff --git a/src/bsp/BspMerger.cpp b/src/bsp/BspMerger.cpp index 0be65d14..69e889ec 100644 --- a/src/bsp/BspMerger.cpp +++ b/src/bsp/BspMerger.cpp @@ -103,15 +103,16 @@ MergeResult BspMerger::merge(std::vector maps, const vec3& gap, const std: for (size_t i = 0; i < mapB->ents.size(); i++) { - if (mapB->ents[i]->keyvalues["classname"].find("light") != std::string::npos) + Entity* mapent = mapB->ents[i]; + if (mapent->keyvalues["classname"].find("light") != std::string::npos) { - if (mapB->ents[i]->hasKey("style")) + if (mapent->hasKey("style")) { - int style = str_to_int(mapB->ents[i]->keyvalues["style"]); + int style = str_to_int(mapent->keyvalues["style"]); if (style < 255 && style >= start_toggle_lightstyle && remap_light_styles.find((unsigned char)style) != remap_light_styles.end()) { remapped_lightents++; - mapB->ents[i]->setOrAddKeyvalue("style", std::to_string(remap_light_styles[(unsigned char)style])); + mapent->setOrAddKeyvalue("style", std::to_string(remap_light_styles[(unsigned char)style])); } } } diff --git a/src/bsp/Entity.cpp b/src/bsp/Entity.cpp index bcadb394..202aafc8 100644 --- a/src/bsp/Entity.cpp +++ b/src/bsp/Entity.cpp @@ -69,7 +69,7 @@ void Entity::setOrAddKeyvalue(const std::string& key, const std::string& value) addKeyvalue(key, value); } -void Entity::removeKeyvalue(const std::string key) +void Entity::removeKeyvalue(const std::string& key) { if (!key.size()) return; diff --git a/src/bsp/Entity.h b/src/bsp/Entity.h index 6389b342..0933cf75 100644 --- a/src/bsp/Entity.h +++ b/src/bsp/Entity.h @@ -45,7 +45,7 @@ class Entity setOrAddKeyvalue("classname", _classname); } void addKeyvalue(const std::string& key, const std::string& value, bool multisupport = false); - void removeKeyvalue(const std::string key); + void removeKeyvalue(const std::string& key); bool renameKey(int idx, const std::string& newName); bool renameKey(const std::string& oldName, const std::string& newName); void clearAllKeyvalues(); diff --git a/src/editor/BspRenderer.cpp b/src/editor/BspRenderer.cpp index f171dea9..76bc3b06 100644 --- a/src/editor/BspRenderer.cpp +++ b/src/editor/BspRenderer.cpp @@ -766,7 +766,7 @@ void BspRenderer::loadLightmaps() glLightmapTextures = new Texture * [atlasTextures.size()]; - for (unsigned int i = 0; i < atlasTextures.size(); i++) + for (size_t i = 0; i < atlasTextures.size(); i++) { glLightmapTextures[i] = atlasTextures[i]; delete atlases[i]; @@ -964,7 +964,7 @@ int BspRenderer::refreshModel(int modelIdx, bool refreshClipnodes, bool triangul while (modelIdx >= (int)renderModels.size()) { - print_log(get_localized_string(LANG_0280)); + print_log(get_localized_string(LANG_0280), modelIdx, renderModels.size()); addNewRenderFace(); } @@ -1317,8 +1317,10 @@ bool BspRenderer::refreshModelClipnodes(int modelIdx) } if (modelIdx < 0 || modelIdx >= (int)renderClipnodes.size()) { - print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0280)); - return false; + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0280), modelIdx, renderClipnodes.size()); + if (modelIdx < 0) + return false; + generateClipnodeBuffer(modelIdx); } for (int hullIdx = 0; hullIdx < MAX_MAP_HULLS; hullIdx++) { @@ -1421,8 +1423,8 @@ void BspRenderer::generateNavMeshBuffer() { COLOR4 wireframeColor = { 0, 0, 0, 255 }; for (int k = 0; k < renderVerts.size(); k++) { - wireframeVerts.push_back(cVert(renderVerts[k], wireframeColor)); - wireframeVerts.push_back(cVert(renderVerts[(k + 1) % renderVerts.size()], wireframeColor)); + wireframeVerts.emplace_back(cVert(renderVerts[k], wireframeColor)); + wireframeVerts.emplace_back(cVert(renderVerts[(k + 1) % renderVerts.size()], wireframeColor)); } vec3 lightDir = vec3(1, 1, -1).normalize(); @@ -1463,9 +1465,9 @@ void BspRenderer::generateNavMeshBuffer() { // convert from TRIANGLE_FAN style verts to TRIANGLES for (int k = 2; k < renderVerts.size(); k++) { - allVerts.push_back(cVert(renderVerts[0], faceColor)); - allVerts.push_back(cVert(renderVerts[k - 1], faceColor)); - allVerts.push_back(cVert(renderVerts[k], faceColor)); + allVerts.emplace_back(cVert(renderVerts[0], faceColor)); + allVerts.emplace_back(cVert(renderVerts[k - 1], faceColor)); + allVerts.emplace_back(cVert(renderVerts[k], faceColor)); } } } @@ -1483,6 +1485,8 @@ void BspRenderer::generateNavMeshBuffer() { if (allVerts.size() == 0 || wireframeVerts.size() == 0) { renderClip->clipnodeBuffer[hull] = NULL; renderClip->wireframeClipnodeBuffer[hull] = NULL; + delete[] output; + delete[] wireOutput; return; } @@ -1492,7 +1496,7 @@ void BspRenderer::generateNavMeshBuffer() { renderClip->wireframeClipnodeBuffer[hull] = new VertexBuffer(g_app->colorShader, wireOutput, (int)wireframeVerts.size(), GL_LINES); renderClip->wireframeClipnodeBuffer[hull]->ownData = true; - renderClip->faceMaths[hull] = navFaceMaths; + renderClip->faceMaths[hull] = std::move(navFaceMaths); std::ofstream file(map->bsp_name + "_hull" + std::to_string(hull) + ".obj", std::ios::out | std::ios::trunc); for (int i = 0; i < allVerts.size(); i++) { @@ -1583,8 +1587,8 @@ void BspRenderer::generateLeafNavMeshBuffer() { COLOR4 wireframeColor = { 0, 0, 0, 255 }; for (int k = 0; k < renderVerts.size(); k++) { - wireframeVerts.push_back(cVert(renderVerts[k], wireframeColor)); - wireframeVerts.push_back(cVert(renderVerts[(k + 1) % renderVerts.size()], wireframeColor)); + wireframeVerts.emplace_back(cVert(renderVerts[k], wireframeColor)); + wireframeVerts.emplace_back(cVert(renderVerts[(k + 1) % renderVerts.size()], wireframeColor)); } vec3 lightDir = vec3(1, 1, -1).normalize(); @@ -1596,9 +1600,9 @@ void BspRenderer::generateLeafNavMeshBuffer() { // convert from TRIANGLE_FAN style verts to TRIANGLES for (int k = 2; k < renderVerts.size(); k++) { - allVerts.push_back(cVert(renderVerts[0], faceColor)); - allVerts.push_back(cVert(renderVerts[k - 1], faceColor)); - allVerts.push_back(cVert(renderVerts[k], faceColor)); + allVerts.emplace_back(cVert(renderVerts[0], faceColor)); + allVerts.emplace_back(cVert(renderVerts[k - 1], faceColor)); + allVerts.emplace_back(cVert(renderVerts[k], faceColor)); } } } @@ -1617,6 +1621,8 @@ void BspRenderer::generateLeafNavMeshBuffer() { if (allVerts.size() == 0 || wireframeVerts.size() == 0) { renderClip->clipnodeBuffer[hull] = NULL; renderClip->wireframeClipnodeBuffer[hull] = NULL; + delete[] output; + delete[] wireOutput; return; } @@ -1626,7 +1632,7 @@ void BspRenderer::generateLeafNavMeshBuffer() { renderClip->wireframeClipnodeBuffer[hull] = new VertexBuffer(g_app->colorShader, wireOutput, (int)wireframeVerts.size(), GL_LINES); renderClip->wireframeClipnodeBuffer[hull]->ownData = true; - renderClip->faceMaths[hull] = navFaceMaths; + renderClip->faceMaths[hull] = std::move(navFaceMaths); } @@ -1641,7 +1647,7 @@ void BspRenderer::generateClipnodeBufferForHull(int modelIdx, int hullIdx) vec3 min = vec3(model.nMins.x, model.nMins.y, model.nMins.z); vec3 max = vec3(model.nMaxs.x, model.nMaxs.y, model.nMaxs.z); - if (modelIdx >= (int)renderClipnodes.size()) + while (modelIdx >= (int)renderClipnodes.size()) { addClipnodeModel(modelIdx); } @@ -2208,7 +2214,14 @@ void BspRenderer::refreshEnt(int entIdx) { if (FindPathInAssets(map, modelpath, newModelPath)) { - rendEntity.spr = AddNewSpriteToRender(newModelPath); + if (rendEntity.pointEntCube) + { + rendEntity.spr = AddNewSpriteToRender(newModelPath, rendEntity.pointEntCube->mins, rendEntity.pointEntCube->maxs, 1.0f); + } + else + { + rendEntity.spr = AddNewSpriteToRender(newModelPath); + } } else { @@ -2252,7 +2265,14 @@ void BspRenderer::refreshEnt(int entIdx) { if (FindPathInAssets(map, fgdClass->sprite, newModelPath)) { - rendEntity.spr = AddNewSpriteToRender(newModelPath); + if (rendEntity.pointEntCube) + { + rendEntity.spr = AddNewSpriteToRender(newModelPath, rendEntity.pointEntCube->mins, rendEntity.pointEntCube->maxs, 1.0f); + } + else + { + rendEntity.spr = AddNewSpriteToRender(newModelPath); + } } else { @@ -2293,7 +2313,14 @@ void BspRenderer::refreshEnt(int entIdx) { if (FindPathInAssets(map, fgdClass->model, newModelPath)) { - rendEntity.spr = AddNewSpriteToRender(newModelPath); + if (rendEntity.pointEntCube) + { + rendEntity.spr = AddNewSpriteToRender(newModelPath, rendEntity.pointEntCube->mins, rendEntity.pointEntCube->maxs, 1.0f); + } + else + { + rendEntity.spr = AddNewSpriteToRender(newModelPath); + } } else { @@ -3532,7 +3559,7 @@ bool BspRenderer::pickModelPoly(vec3 start, const vec3& dir, vec3 offset, int mo bool selectWorldClips = modelIdx == 0 && (g_render_flags & RENDER_WORLD_CLIPNODES) && hullIdx != -1; bool selectEntClips = modelIdx > 0 && (g_render_flags & RENDER_ENT_CLIPNODES); - if (hullIdx <= -1 && renderModels[modelIdx]->renderGroups.empty()) + if (hullIdx <= -1 && modelIdx >= 0 && modelIdx < map->modelCount && renderModels[modelIdx]->renderGroups.empty()) { // clipnodes are visible for this model because it has no faces hullIdx = getBestClipnodeHull(modelIdx); @@ -3676,7 +3703,7 @@ void BspRenderer::saveLumpState() void BspRenderer::pushEntityUndoStateDelay(const std::string& actionDesc, int entIdx, Entity* ent) { - delayEntUndoList.push_back({ actionDesc,entIdx,ent }); + delayEntUndoList.emplace_back(actionDesc,entIdx,ent); } void BspRenderer::pushEntityUndoState(const std::string& actionDesc, int entIdx) diff --git a/src/editor/Command.cpp b/src/editor/Command.cpp index efbeffeb..f58b65ed 100644 --- a/src/editor/Command.cpp +++ b/src/editor/Command.cpp @@ -213,8 +213,9 @@ size_t CreateEntityCommand::memoryUsage() // Create Entities From Text // CreateEntityFromTextCommand::CreateEntityFromTextCommand(std::string desc, int mapIdx, std::string textData) : Command(desc, mapIdx) { - this->textData = textData; + this->textData = std::move(textData); this->allowedDuringLoad = true; + createdEnts = 0; } CreateEntityFromTextCommand::~CreateEntityFromTextCommand() { @@ -267,7 +268,7 @@ void CreateEntityFromTextCommand::execute() { ent = NULL; // you can end/start an ent on the same line, you know - if (line.find("{") != std::string::npos) + if (line.find('{') != std::string::npos) { ent = new Entity(); lastBracket = 0; diff --git a/src/editor/Fgd.cpp b/src/editor/Fgd.cpp index 18b0cfa1..d633c3d2 100644 --- a/src/editor/Fgd.cpp +++ b/src/editor/Fgd.cpp @@ -409,7 +409,7 @@ void Fgd::parseClassHeader(FgdClass& fgdClass) std::string mdlpath = getValueInParens(typeParts[i]); if (mdlpath.size()) { - fgdClass.model = mdlpath; + fgdClass.model = std::move(mdlpath); fixupPath(fgdClass.model, FIXUPPATH_SLASH::FIXUPPATH_SLASH_REMOVE, FIXUPPATH_SLASH::FIXUPPATH_SLASH_REMOVE); } fgdClass.isModel = true; diff --git a/src/editor/Gui.cpp b/src/editor/Gui.cpp index dacf6eb6..6afd294b 100644 --- a/src/editor/Gui.cpp +++ b/src/editor/Gui.cpp @@ -1855,8 +1855,7 @@ void Gui::drawMenuBar() ImGuiContext& g = *GImGui; static bool ditheringEnabled = false; Bsp* map = app->getSelectedMap(); - BspRenderer* rend = map ? - rend = map->getBspRender() : NULL; + BspRenderer* rend = map ? map->getBspRender() : NULL; if (ImGui::BeginMainMenuBar()) { @@ -4400,7 +4399,7 @@ void Gui::drawMenuBar() }; for (int i = 0; i < 10; i++) { - if (ImGui::MenuItem(optionNames[i], 0, false, !app->isLoading && app->getSelectedMap())) { + if (ImGui::MenuItem(optionNames[i], 0, false, !app->isLoading && app->getSelectedMap() && app)) { if (map->ents[0]->hasKey("origin")) { vec3 ori = map->ents[0]->origin; print_log("Moved worldspawn origin by {} {} {}\n", ori.x, ori.y, ori.z); @@ -4420,7 +4419,7 @@ void Gui::drawMenuBar() ImGui::EndMenu(); } - if (ImGui::MenuItem("Delete Boxed Data", 0, false, !app->isLoading && app->getSelectedMap())) { + if (ImGui::MenuItem("Delete Boxed Data", 0, false, !app->isLoading && app->getSelectedMap() && rend)) { if (!g_app->hasCullbox) { print_log("Create at least 2 entities with \"cull\" as a classname first!\n"); } @@ -4444,15 +4443,12 @@ void Gui::drawMenuBar() IMGUI_TOOLTIP(g, "Scans for duplicated BSP models and updates entity model keys to reference only one model in set of duplicated models. " "This lowers the model count and allows more game models to be precached.\n\n" "This does not delete BSP data structures unless you run the Clean command afterward."); - if (ImGui::MenuItem("Downscale Invalid Textures", "(WIP)", false, !app->isLoading && app->getSelectedMap())) { + if (ImGui::MenuItem("Downscale Invalid Textures", "(WIP)", false, !app->isLoading && app->getSelectedMap() && rend)) { map->downscale_invalid_textures(); - if (rend) - { - rend->preRenderFaces(); - g_app->gui->refresh(); - reloadLimits(); - } + rend->preRenderFaces(); + g_app->gui->refresh(); + reloadLimits(); } IMGUI_TOOLTIP(g, "Shrinks textures that exceed the max texture size and adjusts texture coordinates accordingly. Does not work with WAD textures yet.\n"); if (ImGui::BeginMenu("Fix Bad Surface Extents", !app->isLoading && app->getSelectedMap())) @@ -4560,35 +4556,36 @@ void Gui::drawMenuBar() for (size_t i = 0; i < map->ents.size(); i++) { - if (!map->ents[i]->origin.IsZero()) + Entity* mapEnt = map->ents[i]; + if (!mapEnt->origin.IsZero()) { - std::swap(map->ents[i]->origin.x, map->ents[i]->origin.y); - map->ents[i]->setOrAddKeyvalue("origin", map->ents[i]->origin.toKeyvalueString()); + std::swap(mapEnt->origin.x, mapEnt->origin.y); + mapEnt->setOrAddKeyvalue("origin", mapEnt->origin.toKeyvalueString()); } - if (map->ents[i]->isBspModel()) + if (mapEnt->isBspModel()) { continue; } - if (map->ents[i]->hasKey("angle")) + if (mapEnt->hasKey("angle")) { - float angle = str_to_float(map->ents[i]->keyvalues["angle"]); + float angle = str_to_float(mapEnt->keyvalues["angle"]); angle = 90.0f - angle; - map->ents[i]->setOrAddKeyvalue("angle", std::to_string(fullnormalizeangle(angle))); + mapEnt->setOrAddKeyvalue("angle", std::to_string(fullnormalizeangle(angle))); } - if (map->ents[i]->hasKey("angles")) + if (mapEnt->hasKey("angles")) { - vec3 angles = parseVector(map->ents[i]->keyvalues["angles"]); + vec3 angles = parseVector(mapEnt->keyvalues["angles"]); angles[1] = 90.0f - angles[1]; - map->ents[i]->setOrAddKeyvalue("angles", angles.normalize_angles().toKeyvalueString()); + mapEnt->setOrAddKeyvalue("angles", angles.normalize_angles().toKeyvalueString()); } - else if (!map->ents[i]->hasKey("angle")) + else if (!mapEnt->hasKey("angle")) { vec3 angles = vec3(); angles[1] = 90.0f - angles[1]; - map->ents[i]->setOrAddKeyvalue("angles", angles.normalize_angles().toKeyvalueString()); + mapEnt->setOrAddKeyvalue("angles", angles.normalize_angles().toKeyvalueString()); } } @@ -7534,214 +7531,214 @@ void Gui::drawKeyvalueEditor_FlagsTab(int entIdx) ImGui::EndChild(); } -void Gui::drawKeyvalueEditor_RawEditTab(int entIdx) +struct InputData { - Bsp* map = app->getSelectedMap(); - if (!map || entIdx < 0) - { - ImGui::Text(get_localized_string(LANG_1176).c_str()); - return; - } - - Entity* ent = map->ents[entIdx]; - ImGuiStyle& style = ImGui::GetStyle(); - - ImGui::Columns(4, get_localized_string(LANG_1106).c_str(), false); - - float butColWidth = smallFont->CalcTextSizeA(GImGui->FontSize, 100, 100, " X ").x + style.FramePadding.x * 4; - float textColWidth = (ImGui::GetWindowWidth() - (butColWidth + style.FramePadding.x * 2) * 2) * 0.5f; - - ImGui::SetColumnWidth(0, butColWidth); - ImGui::SetColumnWidth(1, textColWidth); - ImGui::SetColumnWidth(2, textColWidth); - ImGui::SetColumnWidth(3, butColWidth); - - ImGui::NextColumn(); - ImGui::Text(get_localized_string(LANG_0667).c_str()); ImGui::NextColumn(); - ImGui::Text(get_localized_string(LANG_0668).c_str()); ImGui::NextColumn(); - ImGui::NextColumn(); - - ImGui::Columns(1); - ImGui::BeginChild(get_localized_string(LANG_0669).c_str()); - - ImGui::Columns(4, get_localized_string(LANG_0670).c_str(), false); - - textColWidth -= style.ScrollbarSize; // double space to prevent accidental deletes - - ImGui::SetColumnWidth(0, butColWidth); - ImGui::SetColumnWidth(1, textColWidth); - ImGui::SetColumnWidth(2, textColWidth); - ImGui::SetColumnWidth(3, butColWidth); - - float paddingx = style.WindowPadding.x + style.FramePadding.x; - float inputWidth = (ImGui::GetWindowWidth() - paddingx * 2) * 0.5f; + int idx; +}; - struct InputData +struct TextChangeCallback +{ + static int keyNameChanged(ImGuiInputTextCallbackData* data) { - int idx; - }; + InputData* inputData = (InputData*)data->UserData; - struct TextChangeCallback - { - static int keyNameChanged(ImGuiInputTextCallbackData* data) + Bsp* map = g_app->getSelectedMap(); + if (map) { - InputData* inputData = (InputData*)data->UserData; - - Bsp* map = g_app->getSelectedMap(); - if (map) + BspRenderer* render = map->getBspRender(); + if (render) { - BspRenderer* render = map->getBspRender(); - if (render) + if (g_app->pickInfo.selectedEnts.size() && g_app->pickInfo.selectedEnts[0] >= 0) { - if (g_app->pickInfo.selectedEnts.size() && g_app->pickInfo.selectedEnts[0] >= 0) + std::string key = map->ents[g_app->pickInfo.selectedEnts[0]]->keyOrder[inputData->idx]; + if (key != data->Buf) { - std::string key = map->ents[g_app->pickInfo.selectedEnts[0]]->keyOrder[inputData->idx]; - if (key != data->Buf) + for (auto entId : g_app->pickInfo.selectedEnts) { - for (auto entId : g_app->pickInfo.selectedEnts) + Entity* selent = map->ents[entId]; + if (selent->renameKey(key, data->Buf)) { - Entity* selent = map->ents[entId]; - if (selent->renameKey(key, data->Buf)) + render->refreshEnt((int)entId); + if (key == "model" || std::string(data->Buf) == "model") { - render->refreshEnt((int)entId); - if (key == "model" || std::string(data->Buf) == "model") - { - g_app->reloadBspModels(); - } - - g_app->updateEntConnections(); - map->getBspRender()->pushEntityUndoStateDelay("Rename Keyvalue", (int)entId, selent); + g_app->reloadBspModels(); } + + g_app->updateEntConnections(); + map->getBspRender()->pushEntityUndoStateDelay("Rename Keyvalue", (int)entId, selent); } } } } } - return 1; } + return 1; + } - static int keyValueChanged(ImGuiInputTextCallbackData* data) - { - InputData* inputData = (InputData*)data->UserData; + static int keyValueChanged(ImGuiInputTextCallbackData* data) + { + InputData* inputData = (InputData*)data->UserData; - Bsp* map2 = g_app->getSelectedMap(); - if (map2) + Bsp* map2 = g_app->getSelectedMap(); + if (map2) + { + BspRenderer* render = map2->getBspRender(); + if (render) { - BspRenderer* render = map2->getBspRender(); - if (render) + if (g_app->pickInfo.selectedEnts.size() && g_app->pickInfo.selectedEnts[0] >= 0) { - if (g_app->pickInfo.selectedEnts.size() && g_app->pickInfo.selectedEnts[0] >= 0) - { - bool needreloadmodels = false; - std::string key = map2->ents[g_app->pickInfo.selectedEnts[0]]->keyOrder[inputData->idx]; - int part_vec = -1; + bool needreloadmodels = false; + std::string key = map2->ents[g_app->pickInfo.selectedEnts[0]]->keyOrder[inputData->idx]; + int part_vec = -1; - for (auto entId : g_app->pickInfo.selectedEnts) + for (auto entId : g_app->pickInfo.selectedEnts) + { + Entity* selent = map2->ents[entId]; + if (selent->keyvalues[key] != data->Buf) { - Entity* selent = map2->ents[entId]; - if (selent->keyvalues[key] != data->Buf) + if (part_vec == -1 && g_app->pickInfo.selectedEnts.size() > 1) { - if (part_vec == -1 && g_app->pickInfo.selectedEnts.size() > 1) + if (key == "origin") { - if (key == "origin") - { - vec3 newOrigin = parseVector(data->Buf); - vec3 oldOrigin = parseVector(selent->keyvalues[key]); - vec3 testOrigin = newOrigin - oldOrigin; - if (std::abs(testOrigin.x) > EPSILON2) - { - part_vec = 0; - } - else if (std::abs(testOrigin.y) > EPSILON2) - { - part_vec = 1; - } - else - { - part_vec = 2; - } - } - } - - bool needrefreshmodel = false; - if (key == "model") - { - if (selent->hasKey("model") && selent->keyvalues["model"] != data->Buf) + vec3 newOrigin = parseVector(data->Buf); + vec3 oldOrigin = parseVector(selent->keyvalues[key]); + vec3 testOrigin = newOrigin - oldOrigin; + if (std::abs(testOrigin.x) > EPSILON2) { - selent->setOrAddKeyvalue(key, data->Buf); - render->refreshEnt((int)entId); - needreloadmodels = true; + part_vec = 0; } - } - if (key == "renderamt") - { - if (selent->hasKey("renderamt") && selent->keyvalues["renderamt"] != data->Buf) + else if (std::abs(testOrigin.y) > EPSILON2) { - needrefreshmodel = true; + part_vec = 1; } - } - if (key == "rendermode") - { - if (selent->hasKey("rendermode") && selent->keyvalues["rendermode"] != data->Buf) + else { - needrefreshmodel = true; + part_vec = 2; } } - if (key == "renderfx") + } + + bool needrefreshmodel = false; + if (key == "model") + { + if (selent->hasKey("model") && selent->keyvalues["model"] != data->Buf) { - if (selent->hasKey("renderfx") && selent->keyvalues["renderfx"] != data->Buf) - { - needrefreshmodel = true; - } + selent->setOrAddKeyvalue(key, data->Buf); + render->refreshEnt((int)entId); + needreloadmodels = true; } - if (key == "rendercolor") + } + if (key == "renderamt") + { + if (selent->hasKey("renderamt") && selent->keyvalues["renderamt"] != data->Buf) { - if (selent->hasKey("rendercolor") && selent->keyvalues["rendercolor"] != data->Buf) - { - needrefreshmodel = true; - } + needrefreshmodel = true; } - if (key == "origin" && part_vec != -1) + } + if (key == "rendermode") + { + if (selent->hasKey("rendermode") && selent->keyvalues["rendermode"] != data->Buf) { - vec3 newOrigin = parseVector(data->Buf); - vec3 oldOrigin = parseVector(selent->keyvalues[key]); - oldOrigin[part_vec] = newOrigin[part_vec]; - selent->setOrAddKeyvalue("origin", oldOrigin.toKeyvalueString()); + needrefreshmodel = true; } - else + } + if (key == "renderfx") + { + if (selent->hasKey("renderfx") && selent->keyvalues["renderfx"] != data->Buf) { - selent->setOrAddKeyvalue(key, data->Buf); + needrefreshmodel = true; } - render->refreshEnt((int)entId); - pickCount++; - vertPickCount++; - g_app->updateEntConnections(); - if (needrefreshmodel) + } + if (key == "rendercolor") + { + if (selent->hasKey("rendercolor") && selent->keyvalues["rendercolor"] != data->Buf) { - if (map2 && selent->getBspModelIdx() > 0) - { - map2->getBspRender()->refreshModel(selent->getBspModelIdx()); - g_app->updateEntConnections(); - } + needrefreshmodel = true; } - map2->getBspRender()->pushEntityUndoStateDelay("Edit Keyvalue RAW", (int)entId, selent); } - } - - if (needreloadmodels) - { + if (key == "origin" && part_vec != -1) + { + vec3 newOrigin = parseVector(data->Buf); + vec3 oldOrigin = parseVector(selent->keyvalues[key]); + oldOrigin[part_vec] = newOrigin[part_vec]; + selent->setOrAddKeyvalue("origin", oldOrigin.toKeyvalueString()); + } + else + { + selent->setOrAddKeyvalue(key, data->Buf); + } + render->refreshEnt((int)entId); pickCount++; vertPickCount++; g_app->updateEntConnections(); - g_app->reloadBspModels(); + if (needrefreshmodel) + { + if (map2 && selent->getBspModelIdx() > 0) + { + map2->getBspRender()->refreshModel(selent->getBspModelIdx()); + g_app->updateEntConnections(); + } + } + map2->getBspRender()->pushEntityUndoStateDelay("Edit Keyvalue RAW", (int)entId, selent); } } + + if (needreloadmodels) + { + pickCount++; + vertPickCount++; + g_app->updateEntConnections(); + g_app->reloadBspModels(); + } } } - - return 1; } - }; + + return 1; + } +}; +void Gui::drawKeyvalueEditor_RawEditTab(int entIdx) +{ + Bsp* map = app->getSelectedMap(); + if (!map || entIdx < 0) + { + ImGui::Text(get_localized_string(LANG_1176).c_str()); + return; + } + + Entity* ent = map->ents[entIdx]; + ImGuiStyle& style = ImGui::GetStyle(); + + ImGui::Columns(4, get_localized_string(LANG_1106).c_str(), false); + + float butColWidth = smallFont->CalcTextSizeA(GImGui->FontSize, 100, 100, " X ").x + style.FramePadding.x * 4; + float textColWidth = (ImGui::GetWindowWidth() - (butColWidth + style.FramePadding.x * 2) * 2) * 0.5f; + + ImGui::SetColumnWidth(0, butColWidth); + ImGui::SetColumnWidth(1, textColWidth); + ImGui::SetColumnWidth(2, textColWidth); + ImGui::SetColumnWidth(3, butColWidth); + + ImGui::NextColumn(); + ImGui::Text(get_localized_string(LANG_0667).c_str()); ImGui::NextColumn(); + ImGui::Text(get_localized_string(LANG_0668).c_str()); ImGui::NextColumn(); + ImGui::NextColumn(); + + ImGui::Columns(1); + ImGui::BeginChild(get_localized_string(LANG_0669).c_str()); + + ImGui::Columns(4, get_localized_string(LANG_0670).c_str(), false); + + textColWidth -= style.ScrollbarSize; // double space to prevent accidental deletes + + ImGui::SetColumnWidth(0, butColWidth); + ImGui::SetColumnWidth(1, textColWidth); + ImGui::SetColumnWidth(2, textColWidth); + ImGui::SetColumnWidth(3, butColWidth); + + float paddingx = style.WindowPadding.x + style.FramePadding.x; + float inputWidth = (ImGui::GetWindowWidth() - paddingx * 2) * 0.5f; + static InputData keyIds[MAX_KEYS_PER_ENT]; static InputData valueIds[MAX_KEYS_PER_ENT]; @@ -8459,7 +8456,7 @@ void Gui::drawTransformWidget() ImGui::Text(fmt::format("Entity origin: {:.2f} {:.2f} {:.2f}", ent->origin.x, ent->origin.y, ent->origin.z).c_str()); - if (modelIdx >= 0) + if (modelIdx >= 0 && map) { ImGui::Text(fmt::format("Model origin: {:.2f} {:.2f} {:.2f}", map->models[modelIdx].vOrigin.x, map->models[modelIdx].vOrigin.y, map->models[modelIdx].vOrigin.z).c_str()); vec3 modelCenter = getCenter(map->models[modelIdx].nMins, map->models[modelIdx].nMaxs); @@ -9031,7 +9028,7 @@ void Gui::drawSettings() if (ImGui::Button(get_localized_string(LANG_0741).c_str())) { - g_settings.fgdPaths.push_back({ std::string(),true }); + g_settings.fgdPaths.emplace_back(std::string(),true); } } else if (settingsTab == 2) @@ -9078,7 +9075,7 @@ void Gui::drawSettings() if (ImGui::Button(get_localized_string(LANG_0742).c_str())) { - g_settings.resPaths.push_back({ std::string(), true }); + g_settings.resPaths.emplace_back(std::string(), true); } } else if (settingsTab == 3) @@ -9690,7 +9687,7 @@ void Gui::drawMergeWindow() if (inPaths.size() < 1) { - inPaths.push_back(std::string("")); + inPaths.emplace_back(""); } if (ImGui::Begin(fmt::format("{}###MERGE_WIDGET", get_localized_string(LANG_0825)).c_str(), &showMergeMapWidget)) @@ -12497,10 +12494,12 @@ void Gui::drawFaceEditorWidget() ImGui::TextUnformatted(fmt::format("Leaf list. Leaf:{}", last_leaf).c_str()); ImGui::TextUnformatted(fmt::format("Leaf model id:{}", last_leaf_mdl).c_str()); - float flContents = map->leaves[last_leaf].nContents * 1.0f; + float flContents = 0.0f; if (last_leaf >= 0 && last_leaf < map->leafCount) { + flContents = map->leaves[last_leaf].nContents * 1.0f; + ImGui::TextUnformatted(fmt::format("Vis offset:{}", map->leaves[last_leaf].nVisOffset).c_str()); ImGui::TextUnformatted("Contents:"); ImGui::SameLine(); diff --git a/src/editor/Renderer.cpp b/src/editor/Renderer.cpp index 68414344..ab28a814 100644 --- a/src/editor/Renderer.cpp +++ b/src/editor/Renderer.cpp @@ -219,6 +219,7 @@ Renderer::Renderer() glHint(GL_POLYGON_SMOOTH_HINT, GL_FASTEST); glHint(GL_TEXTURE_COMPRESSION_HINT, GL_FASTEST); + unsigned char* img_dat = NULL; unsigned int w, h; @@ -543,7 +544,7 @@ void Renderer::renderLoop() if (SelectedMap && (tmpPickIdx != pickCount || tmpVertPickIdx != vertPickCount || transformTarget != tmpTransformTarget || tmpModelIdx != modelIdx)) { - if ((!modelVerts.size() && !modelFaceVerts.size()) || tmpModelIdx != modelIdx || tmpPickIdx != pickCount) + if ((modelVerts.empty() && modelFaceVerts.empty()) || tmpModelIdx != modelIdx || tmpPickIdx != pickCount) { updateModelVerts(); } @@ -553,11 +554,11 @@ void Renderer::renderLoop() pickInfo.selectedEnts.clear(); for (auto& f : pickInfo.selectedFaces) { - int mdl = SelectedMap->get_model_from_face((int)f); + int mdl = SelectedMap->get_model_from_face(static_cast(f)); if (mdl > 0 && mdl < SelectedMap->modelCount) { int mdl_ent = SelectedMap->get_ent_from_model(mdl); - if (mdl_ent >= 0 && mdl_ent < (int)SelectedMap->ents.size()) + if (mdl_ent >= 0 && mdl_ent < static_cast(SelectedMap->ents.size())) { pickInfo.AddSelectedEnt(mdl_ent); } @@ -566,11 +567,11 @@ void Renderer::renderLoop() } updatePickCount = true; - isTransformableSolid = modelIdx > 0 || (entIdx.size() && SelectedMap->ents[entIdx[0]]->getBspModelIdx() < 0); + isTransformableSolid = modelIdx > 0 || (!entIdx.empty() && SelectedMap->ents[entIdx[0]]->getBspModelIdx() < 0); - if (!isTransformableSolid && pickInfo.selectedEnts.size()) + if (!isTransformableSolid && !pickInfo.selectedEnts.empty()) { - if (SelectedMap && ent && ent->hasKey("classname") && + if (ent && ent->hasKey("classname") && ent->keyvalues["classname"] == "worldspawn") { isTransformableSolid = true; @@ -583,7 +584,7 @@ void Renderer::renderLoop() isMovingOrigin = transformMode == TRANSFORM_MODE_MOVE && transformTarget == TRANSFORM_ORIGIN && modelIdx >= 0; isTransformingValid = (!modelUsesSharedStructures || (transformMode == TRANSFORM_MODE_MOVE && transformTarget != TRANSFORM_VERTEX)) || (isTransformableSolid && isScalingObject); - isTransformingWorld = modelIdx == 0 || ent && ent->isWorldSpawn(); + isTransformingWorld = modelIdx == 0 || (ent && ent->isWorldSpawn()); invalidSolid = false; @@ -827,17 +828,20 @@ void Renderer::renderLoop() } { - colorShader->bind(); matmodel.loadIdentity(); colorShader->updateMatrixes(); + GLfloat currentLineWidth; + glGetFloatv(GL_LINE_WIDTH, ¤tLineWidth); glDisable(GL_CULL_FACE); + if (debugTraceStart != vec3()) + { + glLineWidth(128.0f); + drawLine(debugLine0, debugLine1, { 255, 0, 0, 255 }); + drawLine(debugTraceStart, debugTrace.vecEndPos, COLOR4(255, 0, 0, 255)); + } - glLineWidth(128.0f); - drawLine(debugLine0, debugLine1, { 255, 0, 0, 255 }); - - drawLine(debugTraceStart, debugTrace.vecEndPos, COLOR4(255, 0, 0, 255)); - - if (debugNavMesh && debugNavPoly != -1) { + if (debugNavMesh && debugNavPoly != -1) + { glLineWidth(1); NavNode& node = debugNavMesh->nodes[debugNavPoly]; Polygon3D& poly = debugNavMesh->polys[debugNavPoly]; @@ -885,7 +889,7 @@ void Renderer::renderLoop() vec3 inwardDir = crossProduct(poly.plane_z, delta1.normalize()); vec3 testOffset = (isBelow ? inwardDir : inwardDir * -1) + vec3(0, 0, 1.0f); - float flatLen = (vec2(e2.x,e2.y) - vec2(e1.x,e1.y)).length(); + float flatLen = (vec2(e2.x, e2.y) - vec2(e1.x, e1.y)).length(); float stepUnits = 1.0f; float step = stepUnits / flatLen; TraceResult tr; @@ -1066,8 +1070,12 @@ void Renderer::renderLoop() colorShader->popMatrix(MAT_VIEW); */ } + if (debugTraceStart != vec3()) + { + glLineWidth(currentLineWidth); + } - glLineWidth(1); + glEnable(GL_CULL_FACE); } @@ -1437,26 +1445,23 @@ void Renderer::drawModelOrigin(int modelIdx) void Renderer::drawTransformAxes() { - if (showDragAxes && SelectedMap && pickInfo.selectedEnts.size() == 1 && transformMode == TRANSFORM_MODE_SCALE && transformTarget == TRANSFORM_OBJECT && !modelUsesSharedStructures && !invalidSolid) + if (showDragAxes && transformMode == TRANSFORM_MODE_SCALE && transformTarget == TRANSFORM_OBJECT) { - if (SelectedMap->ents[pickInfo.selectedEnts[0]]->getBspModelIdx() > 0) - { - matmodel.loadIdentity(); - glDepthMask(GL_FALSE); - glDepthFunc(GL_ALWAYS); - updateDragAxes(); - vec3 ori = scaleAxes.origin; - matmodel.translate(ori.x, ori.z, -ori.y); - colorShader->updateMatrixes(); - glDisable(GL_CULL_FACE); - scaleAxes.buffer->drawFull(); - glEnable(GL_CULL_FACE); - glDepthMask(GL_TRUE); - glDepthFunc(GL_LESS); - drawingScaleAxes = true; - } + matmodel.loadIdentity(); + glDepthMask(GL_FALSE); + glDepthFunc(GL_ALWAYS); + updateDragAxes(); + vec3 ori = scaleAxes.origin; + matmodel.translate(ori.x, ori.z, -ori.y); + colorShader->updateMatrixes(); + glDisable(GL_CULL_FACE); + scaleAxes.buffer->drawFull(); + glEnable(GL_CULL_FACE); + glDepthMask(GL_TRUE); + glDepthFunc(GL_LESS); + drawingScaleAxes = true; } - if (showDragAxes && SelectedMap && pickInfo.selectedEnts.size() > 0 && (transformMode == TRANSFORM_MODE_MOVE || (transformMode == TRANSFORM_MODE_SCALE && transformTarget == TRANSFORM_VERTEX))) + else if (showDragAxes) { matmodel.loadIdentity(); glDepthMask(GL_FALSE); @@ -1596,12 +1601,14 @@ void Renderer::cameraPickingControls() if (!pickClickHeld) { - if ((curLeftMouse == GLFW_PRESS || oldLeftMouse == GLFW_PRESS) && + bool canTransform = (curLeftMouse == GLFW_PRESS || oldLeftMouse == GLFW_PRESS) && pickMode == pick_modes::PICK_OBJECT && !movingEnt && !isTransformingWorld && !entIdx.empty() && - (isTransformingValid || isMovingOrigin)) + (isTransformingValid || isMovingOrigin); + + if (canTransform) { transforming = transformAxisControls(); } @@ -1614,6 +1621,7 @@ void Renderer::cameraPickingControls() if (curLeftMouse == GLFW_PRESS && oldLeftMouse != GLFW_PRESS && !pickClickHeld) { bool anyHover = (hoverVert != -1) || (hoverEdge != -1); + if (transformTarget == TRANSFORM_VERTEX && isTransformableSolid && anyHover) { if (!anyCtrlPressed) @@ -1628,11 +1636,11 @@ void Renderer::cameraPickingControls() } } - if (hoverVert != -1 && hoverVert < (int)modelVerts.size()) + if (hoverVert != -1 && hoverVert < static_cast(modelVerts.size())) { modelVerts[hoverVert].selected = anyCtrlPressed ? !modelVerts[hoverVert].selected : true; } - else if (hoverEdge != -1 && hoverEdge < (int)modelEdges.size()) + else if (hoverEdge != -1 && hoverEdge < static_cast(modelEdges.size())) { modelEdges[hoverEdge].selected = anyCtrlPressed ? !modelEdges[hoverEdge].selected : true; for (int i = 0; i < 2; ++i) @@ -1653,16 +1661,15 @@ void Renderer::cameraPickingControls() } // object picking - if (!transforming) + if (!transforming && hoverAxis == -1) { - if (hoverAxis == -1 || (!drawingScaleAxes && !drawingMoveAxes)) + bool shouldPickObject = ((curLeftMouse == GLFW_PRESS && oldLeftMouse == GLFW_RELEASE) || + (pickMode != pick_modes::PICK_OBJECT && curLeftMouse == GLFW_PRESS && facePickTime > 0.0 && curTime - facePickTime > 0.05)); + + if (shouldPickObject) { - if ((curLeftMouse == GLFW_PRESS && oldLeftMouse == GLFW_RELEASE) || - (pickMode != pick_modes::PICK_OBJECT && curLeftMouse == GLFW_PRESS && facePickTime > 0.0 && curTime - facePickTime > 0.05)) - { - facePickTime = -1.0; - pickObject(); - } + facePickTime = -1.0; + pickObject(); } } @@ -1679,22 +1686,22 @@ void Renderer::cameraPickingControls() void Renderer::revertInvalidSolid(Bsp* map, int modelIdx) { - for (size_t i = 0; i < modelVerts.size(); i++) + for (auto& vert : modelVerts) { - modelVerts[i].pos = modelVerts[i].startPos = modelVerts[i].undoPos; - if (modelVerts[i].ptr) - *modelVerts[i].ptr = modelVerts[i].pos; + vert.pos = vert.startPos = vert.undoPos; + if (vert.ptr) + *vert.ptr = vert.pos; } - for (size_t i = 0; i < modelFaceVerts.size(); i++) + for (auto& faceVert : modelFaceVerts) { - modelFaceVerts[i].pos = modelFaceVerts[i].startPos = modelFaceVerts[i].undoPos; - if (modelFaceVerts[i].ptr) - *modelFaceVerts[i].ptr = modelFaceVerts[i].pos; + faceVert.pos = faceVert.startPos = faceVert.undoPos; + if (faceVert.ptr) + *faceVert.ptr = faceVert.pos; } if (map && modelIdx >= 0) { map->vertex_manipulation_sync(modelIdx, modelVerts, false); - BSPMODEL& model = map->models[modelIdx]; + auto& model = map->models[modelIdx]; map->get_model_vertex_bounds(modelIdx, model.nMins, model.nMaxs); map->getBspRender()->refreshModel(modelIdx); } @@ -2809,7 +2816,7 @@ void Renderer::drawLine(vec3& start, vec3& end, COLOR4 color) } void Renderer::drawLine2D(vec2 start, vec2 end, COLOR4 color) { - line_verts[0].pos = vec3(start.x,start.y,0.0f).flip(); + line_verts[0].pos = vec3(start.x, start.y, 0.0f).flip(); line_verts[0].c = color; line_verts[1].pos = vec3(end.x, end.y, 0.0f).flip(); @@ -2843,7 +2850,7 @@ void Renderer::drawPolygon3D(Polygon3D& poly, COLOR4 color) { for (int i = 0; i < poly.verts.size() && i < 64; i++) { vec3 pos = poly.verts[i]; - verts[i].pos = vec3(pos.x,pos.z,-pos.y); + verts[i].pos = vec3(pos.x, pos.z, -pos.y); verts[i].c = color; } @@ -3699,16 +3706,16 @@ void Renderer::scaleSelectedObject(Bsp* map, vec3 dir, const vec3& fromDir, bool bool scaleFromOrigin = std::abs(fromDir.x) < EPSILON && std::abs(fromDir.y) < EPSILON && std::abs(fromDir.z) < EPSILON; - vec3 minDist = vec3(FLT_MAX_COORD, FLT_MAX_COORD, FLT_MAX_COORD); - vec3 maxDist = vec3(-FLT_MAX_COORD, -FLT_MAX_COORD, -FLT_MAX_COORD); + vec3 minDist(FLT_MAX_COORD, FLT_MAX_COORD, FLT_MAX_COORD); + vec3 maxDist(-FLT_MAX_COORD, -FLT_MAX_COORD, -FLT_MAX_COORD); - for (size_t i = 0; i < modelVerts.size(); i++) + for (const auto& vert : modelVerts) { - expandBoundingBox(modelVerts[i].startPos, minDist, maxDist); + expandBoundingBox(vert.startPos, minDist, maxDist); } - for (size_t i = 0; i < modelFaceVerts.size(); i++) + for (const auto& faceVert : modelFaceVerts) { - expandBoundingBox(modelFaceVerts[i].startPos, minDist, maxDist); + expandBoundingBox(faceVert.startPos, minDist, maxDist); } vec3 distRange = maxDist - minDist; @@ -3737,47 +3744,41 @@ void Renderer::scaleSelectedObject(Bsp* map, vec3 dir, const vec3& fromDir, bool } } - // scale planes - for (size_t i = 0; i < modelVerts.size(); i++) + // Scale planes + for (auto& vert : modelVerts) { - vec3 stretchFactor = (modelVerts[i].startPos - scaleFromDist) / distRange; - modelVerts[i].pos += dir * stretchFactor; + vec3 stretchFactor = (vert.startPos - scaleFromDist) / distRange; + vert.pos += dir * stretchFactor; if (gridSnappingEnabled) { - modelVerts[i].pos = snapToGrid(modelVerts[i].pos); + vert.pos = snapToGrid(vert.pos); } - /*if (modelVerts[i].ptr) - *modelVerts[i].ptr = modelVerts[i].pos;*/ } - // scale visible faces - for (size_t i = 0; i < modelFaceVerts.size(); i++) + // Scale visible faces + for (auto& faceVert : modelFaceVerts) { - vec3 stretchFactor = (modelFaceVerts[i].startPos - scaleFromDist) / distRange; - modelFaceVerts[i].pos += dir * stretchFactor; + vec3 stretchFactor = (faceVert.startPos - scaleFromDist) / distRange; + faceVert.pos += dir * stretchFactor; if (gridSnappingEnabled) { - modelFaceVerts[i].pos = snapToGrid(modelFaceVerts[i].pos); + faceVert.pos = snapToGrid(faceVert.pos); } - if (modelFaceVerts[i].ptr) - *modelFaceVerts[i].ptr = modelFaceVerts[i].pos; + if (faceVert.ptr) + *faceVert.ptr = faceVert.pos; } map->vertex_manipulation_sync(modelTransform, modelVerts, false); updateSelectionSize(); - // - // TODO: I have no idea what I'm doing but this code scales axis-aligned texture coord axes correctly. - // Rewrite all of this after understanding texture axes. - // if (textureLock) { minDist = vec3(FLT_MAX_COORD, FLT_MAX_COORD, FLT_MAX_COORD); maxDist = vec3(-FLT_MAX_COORD, -FLT_MAX_COORD, -FLT_MAX_COORD); - for (size_t i = 0; i < modelFaceVerts.size(); i++) + for (const auto& faceVert : modelFaceVerts) { - expandBoundingBox(modelFaceVerts[i].pos, minDist, maxDist); + expandBoundingBox(faceVert.pos, minDist, maxDist); } vec3 newDistRange = maxDist - minDist; vec3 scaleFactor = distRange / newDistRange; @@ -3786,10 +3787,9 @@ void Renderer::scaleSelectedObject(Bsp* map, vec3 dir, const vec3& fromDir, bool scaleMat.loadIdentity(); scaleMat.scale(scaleFactor.x, scaleFactor.y, scaleFactor.z); - for (size_t i = 0; i < scaleTexinfos.size(); i++) + for (auto& oldinfo : scaleTexinfos) { - ScalableTexinfo& oldinfo = scaleTexinfos[i]; - BSPTEXTUREINFO& info = map->texinfos[scaleTexinfos[i].texinfoIdx]; + BSPTEXTUREINFO& info = map->texinfos[oldinfo.texinfoIdx]; info.vS = (scaleMat * vec4(oldinfo.oldS, 1)).xyz(); info.vT = (scaleMat * vec4(oldinfo.oldT, 1)).xyz(); @@ -3797,8 +3797,6 @@ void Renderer::scaleSelectedObject(Bsp* map, vec3 dir, const vec3& fromDir, bool float shiftS = oldinfo.oldShiftS; float shiftT = oldinfo.oldShiftT; - // magic guess-and-check code that somehow works some of the time - // also its shit for (int k = 0; k < 3; k++) { vec3 stretchDir; @@ -3822,7 +3820,6 @@ void Renderer::scaleSelectedObject(Bsp* map, vec3 dir, const vec3& fromDir, bool float dotSm = dotProduct(texFromDir, info.vS) < 0 ? 1.0f : -1.0f; float dotTm = dotProduct(texFromDir, info.vT) < 0 ? 1.0f : -1.0f; - // hurr dur oh god im fucking retarded huurr if (k == 0 && dotProduct(texFromDir, fromDir) < 0 != fromDir.x < 0) { dotSm *= -1.0f; @@ -4122,17 +4119,17 @@ void Renderer::scaleSelectedVerts(Bsp* map, float x, float y, float z) vec3 min(FLT_MAX_COORD, FLT_MAX_COORD, FLT_MAX_COORD); vec3 max(-FLT_MAX_COORD, -FLT_MAX_COORD, -FLT_MAX_COORD); int selectTotal = 0; - for (size_t i = 0; i < modelVerts.size(); i++) + for (const auto& vert : modelVerts) { - if (modelVerts[i].selected) + if (vert.selected) { - vec3 v = modelVerts[i].pos; - if (v.x < min.x) min.x = v.x; - if (v.y < min.y) min.y = v.y; - if (v.z < min.z) min.z = v.z; - if (v.x > max.x) max.x = v.x; - if (v.y > max.y) max.y = v.y; - if (v.z > max.z) max.z = v.z; + vec3 v = vert.pos; + min.x = std::min(min.x, v.x); + min.y = std::min(min.y, v.y); + min.z = std::min(min.z, v.z); + max.x = std::max(max.x, v.x); + max.y = std::max(max.y, v.y); + max.z = std::max(max.z, v.z); selectTotal++; } } @@ -4141,24 +4138,23 @@ void Renderer::scaleSelectedVerts(Bsp* map, float x, float y, float z) debugVec1 = fromOrigin; - for (size_t i = 0; i < modelVerts.size(); i++) + for (auto& vert : modelVerts) { - if (modelVerts[i].selected) + if (vert.selected) { - vec3 delta = modelVerts[i].startPos - fromOrigin; - modelVerts[i].pos = fromOrigin + delta * vec3(x, y, z); + vec3 delta = vert.startPos - fromOrigin; + vert.pos = fromOrigin + delta * vec3(x, y, z); if (gridSnappingEnabled) - modelVerts[i].pos = snapToGrid(modelVerts[i].pos); - if (modelVerts[i].ptr) - *modelVerts[i].ptr = modelVerts[i].pos; + vert.pos = snapToGrid(vert.pos); + if (vert.ptr) + *vert.ptr = vert.pos; } } map->vertex_manipulation_sync(modelTransform, modelVerts, false); - if (entIdx.size()) + if (!entIdx.empty()) { - //modelIdx = map->ents[entIdx]->getBspModelIdx(); Entity* ent = map->ents[entIdx[0]]; map->getBspRender()->refreshModel(ent->getBspModelIdx()); } @@ -4679,7 +4675,7 @@ Texture* Renderer::giveMeTexture(const std::string& texname, const std::string& return missingTex; } -void Renderer::merge(std::string fpath) +void Renderer::merge(std::string fpath) { Bsp* thismap = SelectedMap; if (!thismap) @@ -4702,7 +4698,7 @@ void Renderer::merge(std::string fpath) maps.push_back(map2); BspMerger merger; - mergeResult = merger.merge(maps, vec3(), thismap->bsp_name, true, true, true,false); + mergeResult = merger.merge(maps, vec3(), thismap->bsp_name, true, true, true, false); if (!mergeResult.map || !mergeResult.map->bsp_valid) { delete map2; diff --git a/src/editor/Settings.cpp b/src/editor/Settings.cpp index e283d701..f34af578 100644 --- a/src/editor/Settings.cpp +++ b/src/editor/Settings.cpp @@ -156,11 +156,11 @@ void AppSettings::reset() loadDefault(); fgdPaths.clear(); - fgdPaths.push_back({ "/moddir/GameDefinitionFile.fgd",true }); + fgdPaths.emplace_back("/moddir/GameDefinitionFile.fgd",true); resPaths.clear(); - resPaths.push_back({ "/moddir/",true }); - resPaths.push_back({ "/moddir_addon/",true }); + resPaths.emplace_back("/moddir/",true); + resPaths.emplace_back("/moddir_addon/",true); conditionalPointEntTriggers.clear(); conditionalPointEntTriggers.emplace_back("trigger_once"); @@ -515,26 +515,26 @@ void AppSettings::load() else if (key == "fgd") { if (val.find('?') == std::string::npos) - fgdPaths.push_back({ val,true }); + fgdPaths.emplace_back(val,true); else { auto vals = splitString(val, "?"); if (vals.size() == 2) { - fgdPaths.push_back({ vals[1],vals[0] == "enabled" }); + fgdPaths.emplace_back(vals[1],vals[0] == "enabled"); } } } else if (key == "res") { if (val.find('?') == std::string::npos) - resPaths.push_back({ val,true }); + resPaths.emplace_back(val,true); else { auto vals = splitString(val, "?"); if (vals.size() == 2) { - resPaths.push_back({ vals[1],vals[0] == "enabled" }); + resPaths.emplace_back(vals[1],vals[0] == "enabled"); } } } @@ -707,13 +707,13 @@ void AppSettings::load() if (defaultIsEmpty && fgdPaths.empty()) { - fgdPaths.push_back({ "/moddir/GameDefinitionFile.fgd",true }); + fgdPaths.emplace_back("/moddir/GameDefinitionFile.fgd",true); } if (defaultIsEmpty && resPaths.empty()) { - resPaths.push_back({ "/moddir/",true }); - resPaths.push_back({ "/moddir_addon/",true }); + resPaths.emplace_back("/moddir/",true); + resPaths.emplace_back("/moddir_addon/",true); } if (entListReload || defaultIsEmpty) diff --git a/src/gl/ShaderProgram.cpp b/src/gl/ShaderProgram.cpp index 1ad1a093..42f6a446 100644 --- a/src/gl/ShaderProgram.cpp +++ b/src/gl/ShaderProgram.cpp @@ -6,296 +6,274 @@ static unsigned int g_active_shader_program = 0xFFFFFFFF; - VertexAttr commonAttr[VBUF_FLAGBITS] = { - VertexAttr(2, GL_BYTE, -1, GL_FALSE, ""), // TEX_2B - VertexAttr(2, GL_SHORT, -1, GL_FALSE, ""), // TEX_2S - VertexAttr(2, GL_FLOAT, -1, GL_FALSE, ""), // TEX_2F - VertexAttr(3, GL_UNSIGNED_BYTE, -1, GL_TRUE, ""), // COLOR_3B - VertexAttr(3, GL_FLOAT, -1, GL_TRUE, ""), // COLOR_3F - VertexAttr(4, GL_UNSIGNED_BYTE, -1, GL_TRUE, ""), // COLOR_4B - VertexAttr(4, GL_FLOAT, -1, GL_TRUE, ""), // COLOR_4F - VertexAttr(3, GL_BYTE, -1, GL_TRUE, ""), // NORM_3B - VertexAttr(3, GL_FLOAT, -1, GL_TRUE, ""), // NORM_3F - VertexAttr(2, GL_BYTE, -1, GL_FALSE, ""), // POS_2B - VertexAttr(2, GL_SHORT, -1, GL_FALSE, ""), // POS_2S - VertexAttr(2, GL_INT, -1, GL_FALSE, ""), // POS_2I - VertexAttr(2, GL_FLOAT, -1, GL_FALSE, ""), // POS_2F - VertexAttr(3, GL_SHORT, -1, GL_FALSE, ""), // POS_3S - VertexAttr(3, GL_FLOAT, -1, GL_FALSE, ""), // POS_3F + VertexAttr(2, GL_BYTE, -1, GL_FALSE, ""), // TEX_2B + VertexAttr(2, GL_SHORT, -1, GL_FALSE, ""), // TEX_2S + VertexAttr(2, GL_FLOAT, -1, GL_FALSE, ""), // TEX_2F + VertexAttr(3, GL_UNSIGNED_BYTE, -1, GL_TRUE, ""), // COLOR_3B + VertexAttr(3, GL_FLOAT, -1, GL_TRUE, ""), // COLOR_3F + VertexAttr(4, GL_UNSIGNED_BYTE, -1, GL_TRUE, ""), // COLOR_4B + VertexAttr(4, GL_FLOAT, -1, GL_TRUE, ""), // COLOR_4F + VertexAttr(3, GL_BYTE, -1, GL_TRUE, ""), // NORM_3B + VertexAttr(3, GL_FLOAT, -1, GL_TRUE, ""), // NORM_3F + VertexAttr(2, GL_BYTE, -1, GL_FALSE, ""), // POS_2B + VertexAttr(2, GL_SHORT, -1, GL_FALSE, ""), // POS_2S + VertexAttr(2, GL_INT, -1, GL_FALSE, ""), // POS_2I + VertexAttr(2, GL_FLOAT, -1, GL_FALSE, ""), // POS_2F + VertexAttr(3, GL_SHORT, -1, GL_FALSE, ""), // POS_3S + VertexAttr(3, GL_FLOAT, -1, GL_FALSE, ""), // POS_3F }; - - VertexAttr::VertexAttr(int numValues, int valueType, int handle, int normalized, const char* varName) - : numValues(numValues), valueType(valueType), handle(handle), normalized(normalized), varName(varName) + : numValues(numValues), valueType(valueType), handle(handle), normalized(normalized), varName(varName), size(0) { - switch (valueType) - { - case(GL_BYTE): - case(GL_UNSIGNED_BYTE): - size = numValues; - break; - case(GL_SHORT): - case(GL_UNSIGNED_SHORT): - size = numValues * 2; - break; - case(GL_FLOAT): - case(GL_INT): - case(GL_UNSIGNED_INT): - size = numValues * 4; - break; - default: - print_log(get_localized_string(LANG_0972), valueType); - handle = -1; - size = 0; - } + switch (valueType) + { + case(GL_BYTE): + case(GL_UNSIGNED_BYTE): + size = numValues; + break; + case(GL_SHORT): + case(GL_UNSIGNED_SHORT): + size = numValues * 2; + break; + case(GL_FLOAT): + case(GL_INT): + case(GL_UNSIGNED_INT): + size = numValues * 4; + break; + default: + print_log(get_localized_string(LANG_0972), valueType); + handle = -1; + } } ShaderProgram::ShaderProgram(const char* vshaderSource, const char* fshaderSource) + : elementSize(0), modelViewID(-1), modelViewProjID(-1), ID(0xFFFFFFFF), + vposID(0), vcolorID(0), vtexID(0), modelViewMat(nullptr), modelViewProjMat(nullptr), attributesBound(false) { - elementSize = 0; - modelViewID = modelViewProjID = -1; - ID = 0xFFFFFFFF; - vposID = vcolorID = vtexID = 0; - vShader = new Shader(vshaderSource, GL_VERTEX_SHADER); - fShader = new Shader(fshaderSource, GL_FRAGMENT_SHADER); - modelViewProjMat = modelViewMat = NULL; - attribs = std::vector(); - link(); + vShader = new Shader(vshaderSource, GL_VERTEX_SHADER); + fShader = new Shader(fshaderSource, GL_FRAGMENT_SHADER); + link(); } + void ShaderProgram::link() { - // Create Shader And Program Objects - ID = glCreateProgram(); - // Attach The Shader Objects To The Program Object - glAttachShader(ID, vShader->ID); - glAttachShader(ID, fShader->ID); - - glLinkProgram(ID); - - int success; - glGetProgramiv(ID, GL_LINK_STATUS, &success); - if (success != GL_TRUE) - { - char* log = new char[1024]; - int len; - glGetProgramInfoLog(ID, 1024, &len, log); - print_log(get_localized_string(LANG_0961)); - print_log(log); - if (len > 1024) - print_log(get_localized_string(LANG_0962)); - delete[] log; - } + ID = glCreateProgram(); + glAttachShader(ID, vShader->ID); + glAttachShader(ID, fShader->ID); + + glLinkProgram(ID); + + int success; + glGetProgramiv(ID, GL_LINK_STATUS, &success); + if (success != GL_TRUE) + { + char log[1024]; + int len; + glGetProgramInfoLog(ID, 1024, &len, log); + print_log(get_localized_string(LANG_0961)); + print_log(log); + if (len > 1024) + print_log(get_localized_string(LANG_0962)); + } } - -ShaderProgram::~ShaderProgram(void) +ShaderProgram::~ShaderProgram() { - glDeleteProgram(ID); - delete vShader; - delete fShader; + glDeleteProgram(ID); + delete vShader; + delete fShader; } void ShaderProgram::bind() { - if (g_active_shader_program != ID) - { - g_active_shader_program = ID; - glUseProgram(ID); - updateMatrixes(); - } -} - -void ShaderProgram::removeShader(int shaderID) -{ - glDetachShader(ID, shaderID); + if (g_active_shader_program != ID) + { + g_active_shader_program = ID; + glUseProgram(ID); + updateMatrixes(); + } } void ShaderProgram::setMatrixes(mat4x4* modelView, mat4x4* modelViewProj) { - modelViewMat = modelView; - modelViewProjMat = modelViewProj; + modelViewMat = modelView; + modelViewProjMat = modelViewProj; } void ShaderProgram::updateMatrixes() { - if (g_active_shader_program != ID) - { - g_active_shader_program = ID; - glUseProgram(ID); - } - - *modelViewMat = g_app->matview * g_app->matmodel; - *modelViewProjMat = g_app->projection * *modelViewMat; - - *modelViewMat = modelViewMat->transpose(); - *modelViewProjMat = modelViewProjMat->transpose(); - - if (modelViewID != -1) - glUniformMatrix4fv(modelViewID, 1, false, (float*)&modelViewMat->m[0]); - if (modelViewProjID != -1) - glUniformMatrix4fv(modelViewProjID, 1, false, (float*)&modelViewProjMat->m[0]); + if (g_active_shader_program != ID) + { + g_active_shader_program = ID; + glUseProgram(ID); + } + + *modelViewMat = g_app->matview * g_app->matmodel; + *modelViewProjMat = g_app->projection * *modelViewMat; + + *modelViewMat = modelViewMat->transpose(); + *modelViewProjMat = modelViewProjMat->transpose(); + + if (modelViewID != -1) + glUniformMatrix4fv(modelViewID, 1, GL_FALSE, &modelViewMat->m[0]); + if (modelViewProjID != -1) + glUniformMatrix4fv(modelViewProjID, 1, GL_FALSE, &modelViewProjMat->m[0]); } void ShaderProgram::updateMatrixes(const mat4x4& viewMat, const mat4x4& viewProjMat) { - if (g_active_shader_program != ID) - { - g_active_shader_program = ID; - glUseProgram(ID); - } - *modelViewMat = viewMat; - *modelViewProjMat = viewProjMat; - - if (modelViewID != -1) - glUniformMatrix4fv(modelViewID, 1, false, (float*)&modelViewMat->m[0]); - if (modelViewProjID != -1) - glUniformMatrix4fv(modelViewProjID, 1, false, (float*)&modelViewProjMat->m[0]); -} - -void calcMatrixes(mat4x4 & outViewMat, mat4x4 & outViewProjMat) -{ - outViewMat = g_app->matview * g_app->matmodel; - outViewProjMat = g_app->projection * outViewMat; - - outViewMat = outViewMat.transpose(); - outViewProjMat = outViewProjMat.transpose(); + if (g_active_shader_program != ID) + { + g_active_shader_program = ID; + glUseProgram(ID); + } + *modelViewMat = viewMat; + *modelViewProjMat = viewProjMat; + + if (modelViewID != -1) + glUniformMatrix4fv(modelViewID, 1, GL_FALSE, &modelViewMat->m[0]); + if (modelViewProjID != -1) + glUniformMatrix4fv(modelViewProjID, 1, GL_FALSE, &modelViewProjMat->m[0]); } void ShaderProgram::setMatrixNames(const char* _modelViewMat, const char* _modelViewProjMat) { - if (_modelViewMat) - { - modelViewID = glGetUniformLocation(ID, _modelViewMat); - if (modelViewID == -1) - print_log(get_localized_string(LANG_0963),_modelViewMat); - } - if (_modelViewProjMat) - { - modelViewProjID = glGetUniformLocation(ID, _modelViewProjMat); - if (modelViewProjID == -1) - print_log(get_localized_string(LANG_0964),_modelViewProjMat); - } + if (_modelViewMat) + { + modelViewID = glGetUniformLocation(ID, _modelViewMat); + if (modelViewID == -1) + print_log(get_localized_string(LANG_0963), _modelViewMat); + } + if (_modelViewProjMat) + { + modelViewProjID = glGetUniformLocation(ID, _modelViewProjMat); + if (modelViewProjID == -1) + print_log(get_localized_string(LANG_0964), _modelViewProjMat); + } } void ShaderProgram::setVertexAttributeNames(const char* posAtt, const char* colorAtt, const char* texAtt, int attFlags) { - if (posAtt) - { - vposID = glGetAttribLocation(ID, posAtt); - if (vposID == -1) print_log(get_localized_string(LANG_0965),posAtt); - } - if (colorAtt) - { - vcolorID = glGetAttribLocation(ID, colorAtt); - if (vcolorID == -1) print_log(get_localized_string(LANG_0966),colorAtt); - } - if (texAtt) - { - vtexID = glGetAttribLocation(ID, texAtt); - if (vtexID == -1) print_log(get_localized_string(LANG_0967),texAtt); - } - - addAttributes(attFlags); + if (posAtt) + { + vposID = glGetAttribLocation(ID, posAtt); + if (vposID == -1) print_log(get_localized_string(LANG_0965), posAtt); + } + if (colorAtt) + { + vcolorID = glGetAttribLocation(ID, colorAtt); + if (vcolorID == -1) print_log(get_localized_string(LANG_0966), colorAtt); + } + if (texAtt) + { + vtexID = glGetAttribLocation(ID, texAtt); + if (vtexID == -1) print_log(get_localized_string(LANG_0967), texAtt); + } + + addAttributes(attFlags); } void ShaderProgram::pushMatrix(int matType) { - if (matType & MAT_MODEL) matStack[0].push_back(g_app->matmodel); - if (matType & MAT_VIEW) matStack[1].push_back(g_app->matview); - if (matType & MAT_PROJECTION) matStack[2].push_back(g_app->projection); + if (matType & MAT_MODEL) matStack[0].push_back(g_app->matmodel); + if (matType & MAT_VIEW) matStack[1].push_back(g_app->matview); + if (matType & MAT_PROJECTION) matStack[2].push_back(g_app->projection); } void ShaderProgram::popMatrix(int matType) { - mat4x4 * targets[3] = { &g_app->matmodel, &g_app->matview, &g_app->projection}; - for (int idx = 0, mask = 1; idx < 3; ++idx, mask <<= 1) - { - if (matType & mask) - { - std::vector& stack = matStack[idx]; - if (!stack.empty()) - { - *targets[idx] = stack[stack.size() - 1]; - stack.pop_back(); - break; - } - else - print_log(get_localized_string(LANG_0968)); - } - } + mat4x4* targets[3] = { &g_app->matmodel, &g_app->matview, &g_app->projection }; + for (int idx = 0, mask = 1; idx < 3; ++idx, mask <<= 1) + { + if (matType & mask) + { + std::vector& stack = matStack[idx]; + if (!stack.empty()) + { + *targets[idx] = stack.back(); + stack.pop_back(); + } + else + print_log(get_localized_string(LANG_0968)); + } + } } void ShaderProgram::addAttributes(int attFlags) { - elementSize = 0; - for (int i = 0; i < VBUF_FLAGBITS; i++) - { - if (attFlags & (1 << i)) - { - if (i >= VBUF_POS_START) - commonAttr[i].handle = vposID; - else if (i >= VBUF_COLOR_START) - commonAttr[i].handle = vcolorID; - else if (i >= VBUF_TEX_START) - commonAttr[i].handle = vtexID; - else - print_log(get_localized_string(LANG_0973), i); - - attribs.emplace_back(commonAttr[i]); - elementSize += commonAttr[i].size; - } - } + elementSize = 0; + for (int i = 0; i < VBUF_FLAGBITS; i++) + { + if (attFlags & (1 << i)) + { + if (i >= VBUF_POS_START) + commonAttr[i].handle = vposID; + else if (i >= VBUF_COLOR_START) + commonAttr[i].handle = vcolorID; + else if (i >= VBUF_TEX_START) + commonAttr[i].handle = vtexID; + else + print_log(get_localized_string(LANG_0973), i); + + attribs.emplace_back(commonAttr[i]); + elementSize += commonAttr[i].size; + } + } } -void ShaderProgram::addAttribute(int numValues, int valueType, int normalized, const char* varName) { - VertexAttr attribute(numValues, valueType, -1, normalized, varName); +void ShaderProgram::addAttribute(int numValues, int valueType, int normalized, const char* varName) +{ + VertexAttr attribute(numValues, valueType, -1, normalized, varName); - attribs.emplace_back(attribute); - elementSize += attribute.size; + attribs.emplace_back(attribute); + elementSize += attribute.size; } -void ShaderProgram::addAttribute(int type, const char* varName) { - if (!varName || varName[0] == '\0') - { - print_log(PRINT_RED | PRINT_INTENSITY, "VertexBuffer::addAttribute -> varName is null"); - return; - } - int idx = 0; - while (type >>= 1) // unroll for more speed... - { - idx++; - } - - if (idx >= VBUF_FLAGBITS) { - print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0974)); - return; - } - - VertexAttr attribute = commonAttr[idx]; - attribute.handle = -1; - attribute.varName = varName; - - attribs.emplace_back(attribute); - elementSize += attribute.size; +void ShaderProgram::addAttribute(int type, const char* varName) +{ + if (!varName || varName[0] == '\0') + { + print_log(PRINT_RED | PRINT_INTENSITY, "VertexBuffer::addAttribute -> varName is null"); + return; + } + int idx = 0; + while (type >>= 1) // unroll for more speed... + { + idx++; + } + + if (idx >= VBUF_FLAGBITS) + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0974)); + return; + } + + VertexAttr attribute = commonAttr[idx]; + attribute.handle = -1; + attribute.varName = varName; + + attribs.emplace_back(attribute); + elementSize += attribute.size; } -void ShaderProgram::bindAttributes(bool hideErrors) { - if (attributesBound) - return; +void ShaderProgram::bindAttributes(bool hideErrors) +{ + if (attributesBound) + return; - for (size_t i = 0; i < attribs.size(); i++) - { - if (attribs[i].handle != -1) - continue; + for (size_t i = 0; i < attribs.size(); i++) + { + if (attribs[i].handle != -1) + continue; - attribs[i].handle = glGetAttribLocation(ID, attribs[i].varName); + attribs[i].handle = glGetAttribLocation(ID, attribs[i].varName); - if ((!hideErrors || g_verbose) && attribs[i].handle == -1) - print_log(get_localized_string(LANG_0975), attribs[i].varName); - } + if ((!hideErrors || g_verbose) && attribs[i].handle == -1) + print_log(get_localized_string(LANG_0975), attribs[i].varName); + } - attributesBound = true; + attributesBound = true; } \ No newline at end of file diff --git a/src/gl/Texture.cpp b/src/gl/Texture.cpp index 53a4a0d5..d418abb4 100644 --- a/src/gl/Texture.cpp +++ b/src/gl/Texture.cpp @@ -11,183 +11,178 @@ std::vector g_all_Textures; Texture::Texture(GLsizei _width, GLsizei _height, unsigned char* data, const std::string& name, bool rgba, bool _owndata) { - tex_owndata = _owndata; - wad_name = ""; - this->width = _width; - this->height = _height; - - if (!(g_render_flags & RENDER_TEXTURES_NOFILTER)) - { - nearFilter = GL_LINEAR; - farFilter = GL_LINEAR; - } - else - { - nearFilter = GL_NEAREST; - farFilter = GL_NEAREST; - } - this->data = data; - dataLen = (unsigned int)(width * height) * (rgba ? sizeof(COLOR4) : sizeof(COLOR3)); - id = 0xFFFFFFFF; - format = rgba ? GL_RGBA : GL_RGB; - this->texName = name; - uploaded = false; - - type = -1; - - if (g_settings.verboseLogs) - print_log(get_localized_string(LANG_0970), name, width, height); - - this->transparentMode = IsTextureTransparent(name) ? 1 : 0; - - if (name.size() && name[0] == '{') - { - this->transparentMode = 2; - } - g_all_Textures.push_back(this); + tex_owndata = _owndata; + wad_name = ""; + this->width = _width; + this->height = _height; + + if (!(g_render_flags & RENDER_TEXTURES_NOFILTER)) + { + nearFilter = GL_LINEAR; + farFilter = GL_LINEAR; + } + else + { + nearFilter = GL_NEAREST; + farFilter = GL_NEAREST; + } + this->data = data; + dataLen = static_cast(width * height * (rgba ? sizeof(COLOR4) : sizeof(COLOR3))); + id = 0xFFFFFFFF; + format = rgba ? GL_RGBA : GL_RGB; + this->texName = name; + uploaded = false; + + type = -1; + + if (g_settings.verboseLogs) + print_log(get_localized_string(LANG_0970), name, width, height); + + this->transparentMode = IsTextureTransparent(name) ? 1 : 0; + + if (!name.empty() && name[0] == '{') + { + this->transparentMode = 2; + } + g_all_Textures.push_back(this); } Texture::~Texture() { - this->wad_name = ""; - - if (id != 0xFFFFFFFF) - glDeleteTextures(1, &id); - - if (this->tex_owndata && data != NULL) - delete[] data; - - std::vector::iterator it = std::remove(g_all_Textures.begin(), g_all_Textures.end(), this); - if (it != g_all_Textures.end()) - { - g_all_Textures.erase(it); - } - else - { - if (g_verbose) - { - print_log(PRINT_RED, "MISSING TEX BUFF IN TOTAL TEXTURES BUFF!\n"); - } - } + wad_name.clear(); + + if (id != 0xFFFFFFFF) + glDeleteTextures(1, &id); + + if (tex_owndata && data != nullptr) + delete[] data; + + auto it = std::remove(g_all_Textures.begin(), g_all_Textures.end(), this); + if (it != g_all_Textures.end()) + { + g_all_Textures.erase(it); + } + else if (g_verbose) + { + print_log(PRINT_RED, "MISSING TEX BUFF IN TOTAL TEXTURES BUFF!\n"); + } } unsigned char* Texture::get_data() { - if (data == NULL) - { - tex_owndata = true; - data = new unsigned char[dataLen]; - if (id != 0xFFFFFFFF) - { - memset(binded_tex, 0, sizeof(binded_tex)); - glBindTexture(GL_TEXTURE_2D, id); - glPixelStorei(GL_PACK_ALIGNMENT, 1); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glGetTexImage(GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, data); - //glReadPixels(0,0, width,height,format, GL_UNSIGNED_BYTE, data); - } - else - { - memset(data, 255, dataLen); - } - } - return data; + if (data == nullptr) + { + tex_owndata = true; + data = new unsigned char[dataLen]; + if (id != 0xFFFFFFFF) + { + std::fill(std::begin(binded_tex), std::end(binded_tex), nullptr); + glBindTexture(GL_TEXTURE_2D, id); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glGetTexImage(GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, data); + } + else + { + std::fill_n(data, dataLen, (unsigned char)255); + } + } + return data; } void Texture::upload(int _type) { - this->type = _type; - g_mutex_list[3].lock(); - get_data(); - - if (id != 0xFFFFFFFF) - { - glDeleteTextures(1, &id); - } - - glGenTextures(1, &id); - glBindTexture(GL_TEXTURE_2D, id); // Binds this texture handle so we can load the data into it - - // Set up filters and wrap mode - if (type == TYPE_LIGHTMAP) - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - } - else if (type == TYPE_TEXTURE) - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, this->nearFilter); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, this->farFilter); - } - else if (type == TYPE_DECAL) - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, this->nearFilter); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, this->farFilter); - } - - if (texName[0] == '{') - { - if (format == GL_RGB) - { - format = GL_RGBA; - COLOR3* rgbData = (COLOR3*)data; - int pixelCount = width * height; - COLOR4* rgbaData = new COLOR4[pixelCount]; - for (int i = 0; i < pixelCount; i++) - { - rgbaData[i] = rgbData[i]; - if (rgbaData[i].r == 0 && rgbaData[i].g == 0 && rgbaData[i].b > 250) - { - rgbaData[i] = COLOR4(0, 0, 0, 0); - } - } - delete[] data; - data = (unsigned char*)rgbaData; - dataLen = (unsigned int)(width * height) * sizeof(COLOR4); - } - } - - glPixelStorei(GL_PACK_ALIGNMENT, 1); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); - - if (g_settings.verboseLogs) - print_log(get_localized_string(LANG_0971), texName, width, height); - - if (tex_owndata) - { - delete[] data; - data = NULL; - } - g_mutex_list[3].unlock(); + this->type = _type; + g_mutex_list[3].lock(); + get_data(); + + if (id != 0xFFFFFFFF) + { + glDeleteTextures(1, &id); + } + + glGenTextures(1, &id); + glBindTexture(GL_TEXTURE_2D, id); + + // Set up filters and wrap mode + switch (type) + { + case TYPE_LIGHTMAP: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + break; + case TYPE_TEXTURE: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, this->nearFilter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, this->farFilter); + break; + case TYPE_DECAL: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, this->nearFilter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, this->farFilter); + break; + default: + break; + } + + if (texName[0] == '{' && format == GL_RGB) + { + format = GL_RGBA; + auto* rgbData = reinterpret_cast(data); + auto pixelCount = width * height; + auto* rgbaData = new COLOR4[pixelCount]; + for (int i = 0; i < pixelCount; i++) + { + rgbaData[i] = rgbData[i]; + if (rgbaData[i].r == 0 && rgbaData[i].g == 0 && rgbaData[i].b > 250) + { + rgbaData[i] = COLOR4(0, 0, 0, 0); + } + } + delete[] data; + data = reinterpret_cast(rgbaData); + dataLen = static_cast(width * height * sizeof(COLOR4)); + } + + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); + + if (g_settings.verboseLogs) + print_log(get_localized_string(LANG_0971), texName, width, height); + + if (tex_owndata) + { + delete[] data; + data = nullptr; + } + g_mutex_list[3].unlock(); } Texture* binded_tex[64]; void Texture::bind(GLuint texnum) { - if (binded_tex[texnum] != this) - { - glActiveTexture(GL_TEXTURE0 + texnum); - glBindTexture(GL_TEXTURE_2D, id); - binded_tex[texnum] = this; - } + if (binded_tex[texnum] != this) + { + glActiveTexture(GL_TEXTURE0 + texnum); + glBindTexture(GL_TEXTURE_2D, id); + binded_tex[texnum] = this; + } } bool IsTextureTransparent(const std::string& texname) { - if (!texname.size()) - return false; - for (auto const& s : g_settings.transparentTextures) - { - if (s == texname) - return true; - } - return false; + if (texname.empty()) + return false; + for (const auto& s : g_settings.transparentTextures) + { + if (s == texname) + return true; + } + return false; } \ No newline at end of file diff --git a/src/gl/VertexBuffer.cpp b/src/gl/VertexBuffer.cpp index d1d10fe5..30da273d 100644 --- a/src/gl/VertexBuffer.cpp +++ b/src/gl/VertexBuffer.cpp @@ -5,147 +5,153 @@ VertexBuffer::VertexBuffer(ShaderProgram* shaderProgram, void* dat, int _numVerts, int primitive) { - frameId = (int)-1; - uploaded = false; - vboId = 0xFFFFFFFF; - vaoId = 0xFFFFFFFF; - ownData = false; - this->shaderProgram = shaderProgram; - this->primitive = primitive; - setData(dat, _numVerts); + frameId = -1; + uploaded = false; + vboId = 0xFFFFFFFF; + vaoId = 0xFFFFFFFF; + ownData = false; + this->shaderProgram = shaderProgram; + this->primitive = primitive; + setData(dat, _numVerts); } -VertexBuffer::~VertexBuffer() { - - deleteBuffer(); - if (ownData && data) { - delete[] data; - } - data = NULL; - numVerts = 0; +VertexBuffer::~VertexBuffer() +{ + deleteBuffer(); + if (ownData && data) + { + delete[] data; + } + data = nullptr; + numVerts = 0; } void VertexBuffer::setData(void* _data, int _numVerts) { - data = (unsigned char*)_data; - numVerts = _numVerts; - uploaded = false; + data = static_cast(_data); + numVerts = _numVerts; + uploaded = false; } unsigned char* VertexBuffer::get_data() { - if (data == NULL) - { - glBindBuffer(GL_ARRAY_BUFFER, vboId); - glBindVertexArray(vaoId); - GLint bufferSize; - glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &bufferSize); - data = new unsigned char[bufferSize]; - glGetBufferSubData(GL_ARRAY_BUFFER, 0, bufferSize, data); - } - return data; + if (data == nullptr) + { + glBindBuffer(GL_ARRAY_BUFFER, vboId); + glBindVertexArray(vaoId); + GLint bufferSize; + glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &bufferSize); + data = new unsigned char[bufferSize]; + glGetBufferSubData(GL_ARRAY_BUFFER, 0, bufferSize, data); + } + return data; } void VertexBuffer::upload(bool hideErrors, bool forceReupload) { - if (!shaderProgram || (uploaded && !forceReupload)) - return; - - if (data == NULL) - { - get_data(); - } - - deleteBuffer(); - - glGenVertexArrays(1, &vaoId); - glBindVertexArray(vaoId); - - glGenBuffers(1, &vboId); - glBindBuffer(GL_ARRAY_BUFFER, vboId); - - glBufferData(GL_ARRAY_BUFFER, shaderProgram->elementSize * numVerts, data, GL_STATIC_DRAW); - - GLuint64 offset = 0; - for (const VertexAttr& a : shaderProgram->attribs) - { - if (a.handle == -1) - continue; - - glEnableVertexAttribArray(a.handle); - glVertexAttribPointer(a.handle, a.numValues, a.valueType, a.normalized != 0, shaderProgram->elementSize, (const GLvoid*)(offset)); - if (glGetError() != GL_NO_ERROR && !hideErrors) - { - std::cout << "Error! Name: " << a.varName << std::endl; - } - offset += a.size; - } - - - if (ownData) { - delete[] data; - data = NULL; - } - uploaded = true; + if (!shaderProgram || (uploaded && !forceReupload)) + return; + + if (data == nullptr) + { + get_data(); + } + + deleteBuffer(); + + glGenVertexArrays(1, &vaoId); + glBindVertexArray(vaoId); + + glGenBuffers(1, &vboId); + glBindBuffer(GL_ARRAY_BUFFER, vboId); + + glBufferData(GL_ARRAY_BUFFER, shaderProgram->elementSize * numVerts, data, GL_STATIC_DRAW); + + GLuint64 offset = 0; + for (const VertexAttr& a : shaderProgram->attribs) + { + if (a.handle == -1) + continue; + + glEnableVertexAttribArray(a.handle); + glVertexAttribPointer(a.handle, a.numValues, a.valueType, a.normalized != 0, shaderProgram->elementSize, reinterpret_cast(offset)); + if (!hideErrors && glGetError() != GL_NO_ERROR) + { + std::cout << "Error! Name: " << a.varName << std::endl; + } + offset += a.size; + } + + if (ownData) + { + delete[] data; + data = nullptr; + } + uploaded = true; } -void VertexBuffer::deleteBuffer() { - if (vboId != 0xFFFFFFFF) - glDeleteBuffers(1, &vboId); - if (vaoId != 0xFFFFFFFF) - glDeleteVertexArrays(1, &vaoId); - vboId = 0xFFFFFFFF; - vaoId = 0xFFFFFFFF; +void VertexBuffer::deleteBuffer() +{ + if (vboId != 0xFFFFFFFF) + { + glDeleteBuffers(1, &vboId); + } + if (vaoId != 0xFFFFFFFF) + { + glDeleteVertexArrays(1, &vaoId); + } + vboId = 0xFFFFFFFF; + vaoId = 0xFFFFFFFF; } void VertexBuffer::drawRange(int _primitive, int start, int end, bool hideErrors) { - if (frameId != (int)-1) - { - if (frameId == g_drawFrameId) - { - return; - } - frameId = g_drawFrameId; - } - shaderProgram->bind(); - upload(true, false); - - if (start < 0 || start > numVerts || numVerts == 0) - { - if (g_verbose) - print_log(get_localized_string(LANG_0976), start, numVerts); - return; - } - else if (end > numVerts || end < 0) - { - if (g_verbose) - print_log(get_localized_string(LANG_0977), end); - return; - } - else if (end - start <= 0) - { - if (g_verbose) - print_log(get_localized_string(LANG_0978), start, end); - return; - } - glBindBuffer(GL_ARRAY_BUFFER, vboId); - glBindVertexArray(vaoId); - glDrawArrays(_primitive, (GLint)start, (GLint)(end - start)); + if (frameId != -1) + { + if (frameId == g_drawFrameId) + { + return; + } + frameId = g_drawFrameId; + } + shaderProgram->bind(); + upload(true, false); + + if (start < 0 || start > numVerts || numVerts == 0) + { + if (g_verbose) + print_log(get_localized_string(LANG_0976), start, numVerts); + return; + } + else if (end > numVerts || end < 0) + { + if (g_verbose) + print_log(get_localized_string(LANG_0977), end); + return; + } + else if (end - start <= 0) + { + if (g_verbose) + print_log(get_localized_string(LANG_0978), start, end); + return; + } + glBindBuffer(GL_ARRAY_BUFFER, vboId); + glBindVertexArray(vaoId); + glDrawArrays(_primitive, start, end - start); } void VertexBuffer::draw(int _primitive) { - if (numVerts > 0) - { - drawRange(_primitive, 0, numVerts); - } + if (numVerts > 0) + { + drawRange(_primitive, 0, numVerts); + } } void VertexBuffer::drawFull() { - if (numVerts > 0) - { - drawRange(primitive, 0, numVerts); - } -} + if (numVerts > 0) + { + drawRange(primitive, 0, numVerts); + } +} \ No newline at end of file diff --git a/src/gl/VertexBuffer.h b/src/gl/VertexBuffer.h index de730373..119ea119 100644 --- a/src/gl/VertexBuffer.h +++ b/src/gl/VertexBuffer.h @@ -7,12 +7,12 @@ class VertexBuffer { public: + ShaderProgram* shaderProgram; // for getting handles to vertex attributes + int numVerts; int primitive; int frameId; - ShaderProgram* shaderProgram; // for getting handles to vertex attributes - // Specify which common attributes to use. They will be located in the // shader program. If passing data, note that data is not copied, but referenced VertexBuffer(ShaderProgram* shaderProgram, void* dat, int numVerts, int primitive = 0); diff --git a/src/main.cpp b/src/main.cpp index 30e7097f..20dc6421 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -27,7 +27,7 @@ // Solve: // Create empty hull 0 box ? -std::string g_version_string = "NewBSPGuy v4.28"; +std::string g_version_string = "NewBSPGuy v4.29"; bool g_verbose = false; diff --git a/src/mdl/mdl_studio.cpp b/src/mdl/mdl_studio.cpp index 03b3e195..d0ceeec6 100644 --- a/src/mdl/mdl_studio.cpp +++ b/src/mdl/mdl_studio.cpp @@ -267,28 +267,23 @@ void StudioModel::SlerpBones(vec4 q1[], vec3 pos1[], vec4 q2[], vec3 pos2[], flo } -void StudioModel::AdvanceFrame(float dt) +void StudioModel::AdvanceFrame(float dt) { - if (!m_pstudiohdr) - return; - mstudioseqdesc_t* pseqdesc = (mstudioseqdesc_t*)((unsigned char*)m_pstudiohdr + m_pstudiohdr->seqindex) + m_sequence; + if (!m_pstudiohdr) return; + auto* pseqdesc = reinterpret_cast( + reinterpret_cast(m_pstudiohdr) + m_pstudiohdr->seqindex) + m_sequence; m_frame += dt * pseqdesc->fps; - if (pseqdesc->numframes <= 1) - { - m_frame = 0.0f; - } - else - { - m_frame += (int)(m_frame / (pseqdesc->numframes - 1)) * (pseqdesc->numframes - 1); + if (pseqdesc->numframes > 1) { + m_frame = std::fmod(m_frame, pseqdesc->numframes - 1); } - if (m_frame >= pseqdesc->numframes) + if (m_frame >= pseqdesc->numframes) { m_frame = 0; + } } - void StudioModel::SetUpBones(void) { // valve diff --git a/src/nav/LeafNavMesh.cpp b/src/nav/LeafNavMesh.cpp index c42233e9..8fade7a4 100644 --- a/src/nav/LeafNavMesh.cpp +++ b/src/nav/LeafNavMesh.cpp @@ -80,7 +80,7 @@ void LeafNavMesh::clear() { LeafNavMesh::LeafNavMesh(std::vector inleaves, LeafOctree* octree) { clear(); - this->nodes = inleaves; + this->nodes = std::move(inleaves); this->octree = octree; } @@ -174,7 +174,7 @@ int LeafNavMesh::getNodeIdx(Bsp* map, Entity* ent) { for (int k = 0; k < mesh.leafFaces.size(); k++) { Polygon3D& leafFace = mesh.leafFaces[k]; - for (int n = 0; n < 6; k++) { + for (int n = 0; n < 6; n++) { if (leafFace.intersects(boxPolys[n])) { return i; } diff --git a/src/nav/LeafNavMeshGenerator.cpp b/src/nav/LeafNavMeshGenerator.cpp index fcdf11d7..034fe16f 100644 --- a/src/nav/LeafNavMeshGenerator.cpp +++ b/src/nav/LeafNavMeshGenerator.cpp @@ -31,13 +31,15 @@ LeafNavMesh* LeafNavMeshGenerator::generate(Bsp* map) { size_t totalSz = 0; for (int i = 0; i < navmesh->nodes.size(); i++) { - totalSz += sizeof(LeafNode) + (sizeof(LeafLink) * navmesh->nodes[i].links.size()); + auto & navnode = navmesh->nodes[i]; - for (int k = 0; k < navmesh->nodes[i].links.size(); k++) { - totalSz += navmesh->nodes[i].links[k].linkArea.sizeBytes() - sizeof(Polygon3D); + totalSz += sizeof(LeafNode) + (sizeof(LeafLink) * navnode.links.size()); + + for (int k = 0; k < navnode.links.size(); k++) { + totalSz += navnode.links[k].linkArea.sizeBytes() - sizeof(Polygon3D); } - for (int k = 0; k < navmesh->nodes[i].leafFaces.size(); k++) { - totalSz += navmesh->nodes[i].leafFaces[k].sizeBytes(); + for (int k = 0; k < navnode.leafFaces.size(); k++) { + totalSz += navnode.leafFaces[k].sizeBytes(); } } @@ -60,7 +62,7 @@ std::vector LeafNavMeshGenerator::getHullLeaves(Bsp* map, int modelIdx std::vector emptyMeshes; for (int k = 0; k < emptyNodes.size(); k++) { - emptyMeshes.push_back(clipper.clip(emptyNodes[k].cuts)); + emptyMeshes.emplace_back(clipper.clip(emptyNodes[k].cuts)); } // GET FACES FROM MESHES @@ -176,7 +178,7 @@ void LeafNavMeshGenerator::setLeafOrigins(Bsp* map, LeafNavMesh* mesh) { vec3 testBottom = node.center - vec3(0, 0, 4096); node.origin = node.center; int bottomFaceIdx = -1; - for (int n = 0; n < node.leafFaces.size(); i++) { + for (int n = 0; n < node.leafFaces.size(); n++) { Polygon3D& face = node.leafFaces[n]; if (face.intersect(node.center, testBottom, node.origin)) { bottomFaceIdx = n; diff --git a/src/nav/LeafNavMeshGenerator.h b/src/nav/LeafNavMeshGenerator.h index 4f8c17c9..00f94c57 100644 --- a/src/nav/LeafNavMeshGenerator.h +++ b/src/nav/LeafNavMeshGenerator.h @@ -8,7 +8,7 @@ class LeafOctree; // generates a navigation mesh for a BSP class LeafNavMeshGenerator { public: - LeafNavMeshGenerator() {} + LeafNavMeshGenerator() = default; // generate a nav mesh from the bsp // returns polygons used to construct the mesh diff --git a/src/nav/LeafOctree.cpp b/src/nav/LeafOctree.cpp index 5a967262..554e91bc 100644 --- a/src/nav/LeafOctree.cpp +++ b/src/nav/LeafOctree.cpp @@ -4,8 +4,8 @@ #include LeafOctant::LeafOctant(vec3 min, vec3 max) { - this->min = min; - this->max = max; + this->mins = min; + this->maxs = max; memset(children, NULL, sizeof(LeafOctant*) * 8); } @@ -37,8 +37,8 @@ void LeafOctree::buildOctree(LeafOctant* node, int currentDepth) { if (currentDepth >= maxDepth) { return; } - const vec3& min = node->min; - const vec3& max = node->max; + const vec3& min = node->mins; + const vec3& max = node->maxs; vec3 mid((min.x + max.x) / 2, (min.y + max.y) / 2, (min.z + max.z) / 2); // Define eight child octants using the min and max values @@ -78,7 +78,7 @@ void LeafOctree::removeLeaf(LeafNode* leaf) { bool LeafOctree::isLeafInOctant(LeafNode* leaf, LeafOctant* node) { vec3 epsilon = vec3(1, 1, 1); // in case leaves are touching right on the border of an octree leaf - return boxesIntersect(leaf->mins - epsilon, leaf->maxs + epsilon, node->min, node->max); + return boxesIntersect(leaf->mins - epsilon, leaf->maxs + epsilon, node->mins, node->maxs); } void LeafOctree::getLeavesInRegion(LeafNode* leaf, std::vector& regionLeaves) { diff --git a/src/nav/LeafOctree.h b/src/nav/LeafOctree.h index 578782fd..1bc31064 100644 --- a/src/nav/LeafOctree.h +++ b/src/nav/LeafOctree.h @@ -4,8 +4,8 @@ #include "LeafNavMesh.h" struct LeafOctant { - vec3 min; - vec3 max; + vec3 mins; + vec3 maxs; std::vector leaves; LeafOctant* children[8]; // Eight children octants diff --git a/src/nav/NavMeshGenerator.cpp b/src/nav/NavMeshGenerator.cpp index 8c56c0a6..0cd6f095 100644 --- a/src/nav/NavMeshGenerator.cpp +++ b/src/nav/NavMeshGenerator.cpp @@ -42,7 +42,7 @@ std::vector NavMeshGenerator::getHullFaces(Bsp* map, int hull) { std::vector solidMeshes; for (int k = 0; k < solidNodes.size(); k++) { - solidMeshes.push_back(clipper.clip(solidNodes[k].cuts)); + solidMeshes.emplace_back(clipper.clip(solidNodes[k].cuts)); } // GET FACES FROM MESHES @@ -310,7 +310,7 @@ void NavMeshGenerator::mergeFaces(Bsp* map, std::vector& faces) { break; } else { - mergedFaces = newMergedFaces; + mergedFaces = std::move(newMergedFaces); } } diff --git a/src/nav/NavMeshGenerator.h b/src/nav/NavMeshGenerator.h index 64573a93..1a27d980 100644 --- a/src/nav/NavMeshGenerator.h +++ b/src/nav/NavMeshGenerator.h @@ -8,7 +8,7 @@ class PolygonOctree; // generates a navigation mesh for a BSP class NavMeshGenerator { public: - NavMeshGenerator() {} + NavMeshGenerator() = default; // generate a nav mesh from the bsp // returns polygons used to construct the mesh diff --git a/src/nav/PolyOctree.cpp b/src/nav/PolyOctree.cpp index f4e27c0a..664b83b0 100644 --- a/src/nav/PolyOctree.cpp +++ b/src/nav/PolyOctree.cpp @@ -4,8 +4,8 @@ #include PolyOctant::PolyOctant(vec3 min, vec3 max) { - this->min = min; - this->max = max; + this->mins = min; + this->maxs = max; memset(children, NULL, sizeof(PolyOctant*) * 8); } @@ -37,8 +37,8 @@ void PolygonOctree::buildOctree(PolyOctant* node, int currentDepth) { if (currentDepth >= maxDepth) { return; } - const vec3& min = node->min; - const vec3& max = node->max; + const vec3& min = node->mins; + const vec3& max = node->maxs; vec3 mid((min.x + max.x) / 2, (min.y + max.y) / 2, (min.z + max.z) / 2); // Define eight child octants using the min and max values @@ -77,7 +77,7 @@ void PolygonOctree::removePolygon(Polygon3D* polygon) { } bool PolygonOctree::isPolygonInOctant(Polygon3D* polygon, PolyOctant* node) { - return boxesIntersect(polygon->worldMins, polygon->worldMaxs, node->min, node->max); + return boxesIntersect(polygon->worldMins, polygon->worldMaxs, node->mins, node->maxs); } void PolygonOctree::getPolysInRegion(Polygon3D* poly, std::vector& regionPolys) { diff --git a/src/nav/PolyOctree.h b/src/nav/PolyOctree.h index 8955a7af..5dacdbf0 100644 --- a/src/nav/PolyOctree.h +++ b/src/nav/PolyOctree.h @@ -3,8 +3,8 @@ #include struct PolyOctant { - vec3 min; - vec3 max; + vec3 mins; + vec3 maxs; std::vector polygons; PolyOctant* children[8]; // Eight children octants diff --git a/src/res/Sprite.cpp b/src/res/Sprite.cpp index a24b5054..2b61373e 100644 --- a/src/res/Sprite.cpp +++ b/src/res/Sprite.cpp @@ -29,6 +29,7 @@ Sprite::~Sprite() void Sprite::DrawSprite() { animate_frame(); + sprite_groups[current_group].sprites [sprite_groups[current_group].current_spr].texture->bind(0); sprite_groups[current_group].sprites @@ -102,7 +103,7 @@ void Sprite::set_missing_sprite() tmpSpriteImage.texture->upload(Texture::TEXTURE_TYPE::TYPE_DECAL); } -Sprite::Sprite(const std::string& filename) +Sprite::Sprite(const std::string& filename, const vec3& mins , const vec3& maxs , float scale, bool useOwnSettigns) { current_group = 0; colors = 0; @@ -215,10 +216,21 @@ Sprite::Sprite(const std::string& filename) } tmpSpriteImage.spriteCube = new EntCube(); - tmpSpriteImage.spriteCube->mins = { -5.0f, 0.0f, 0.0f }; - tmpSpriteImage.spriteCube->maxs = { 5.0f, tmpSpriteImage.frameinfo.width * 1.0f, tmpSpriteImage.frameinfo.height * 1.0f }; - tmpSpriteImage.spriteCube->mins += vec3(0.0f, tmpSpriteImage.frameinfo.origin[0] * 1.0f, tmpSpriteImage.frameinfo.origin[1] * -1.0f); - tmpSpriteImage.spriteCube->maxs += vec3(0.0f, tmpSpriteImage.frameinfo.origin[0] * 1.0f, tmpSpriteImage.frameinfo.origin[1] * -1.0f); + + if (!useOwnSettigns) + { + tmpSpriteImage.spriteCube->mins = { -5.0f, 0.0f, 0.0f }; + tmpSpriteImage.spriteCube->maxs = { 5.0f, tmpSpriteImage.frameinfo.width * 1.0f, tmpSpriteImage.frameinfo.height * 1.0f }; + + tmpSpriteImage.spriteCube->mins += vec3(0.0f, tmpSpriteImage.frameinfo.origin[0] * 1.0f, tmpSpriteImage.frameinfo.origin[1] * -1.0f); + tmpSpriteImage.spriteCube->maxs += vec3(0.0f, tmpSpriteImage.frameinfo.origin[0] * 1.0f, tmpSpriteImage.frameinfo.origin[1] * -1.0f); + } + else + { + tmpSpriteImage.spriteCube->mins = (mins * scale); + tmpSpriteImage.spriteCube->maxs = (maxs * scale); + } + tmpSpriteImage.spriteCube->Textured = true; g_app->pointEntRenderer->genCubeBuffers(tmpSpriteImage.spriteCube); @@ -243,7 +255,7 @@ std::map spr_models; Sprite* AddNewSpriteToRender(const std::string& path, unsigned int sum) { - unsigned int crc32 = GetCrc32InMemory((unsigned char*)path.data(), (unsigned int) path.size(), sum); + unsigned int crc32 = GetCrc32InMemory((unsigned char*)path.data(), (unsigned int)path.size(), sum); if (spr_models.find(crc32) != spr_models.end()) { @@ -258,6 +270,24 @@ Sprite* AddNewSpriteToRender(const std::string& path, unsigned int sum) } +Sprite* AddNewSpriteToRender(const std::string& path, vec3 mins, vec3 maxs, float scale) +{ + auto sum = (mins + maxs * scale).toString(); + + unsigned int crc32 = GetCrc32InMemory((unsigned char*)path.data(), (unsigned int)path.size(), + GetCrc32InMemory((unsigned char*)sum.data(), (unsigned int)sum.size(), 0)); + + if (spr_models.find(crc32) != spr_models.end()) + { + return spr_models[crc32]; + } + else + { + Sprite* newModel = new Sprite(path, mins, maxs, scale, true); + spr_models[crc32] = newModel; + return newModel; + } +} void TestSprite() { diff --git a/src/res/Sprite.h b/src/res/Sprite.h index feb27900..9c883d3c 100644 --- a/src/res/Sprite.h +++ b/src/res/Sprite.h @@ -68,7 +68,7 @@ struct SpriteGroup class Sprite { public: - Sprite(const std::string& filename); + Sprite(const std::string& filename, const vec3 & mins = vec3(), const vec3 & maxs = vec3(), float scale = 1.0f, bool useOwnSettigns = false); ~Sprite(); std::string name; SPRITE_HEADER header; @@ -89,4 +89,5 @@ class Sprite { void TestSprite(); extern std::map spr_models; -Sprite* AddNewSpriteToRender(const std::string & path, unsigned int sum = 0); \ No newline at end of file +Sprite* AddNewSpriteToRender(const std::string & path, unsigned int sum = 0); +Sprite* AddNewSpriteToRender(const std::string& path, vec3 mins, vec3 maxs, float scale); \ No newline at end of file diff --git a/src/util/Line2D.h b/src/util/Line2D.h index 28a052da..8fa70ab3 100644 --- a/src/util/Line2D.h +++ b/src/util/Line2D.h @@ -6,7 +6,7 @@ struct Line2D { vec2 end; vec2 dir; - Line2D() {} + Line2D() = default; Line2D(vec2 start, vec2 end); diff --git a/src/util/Polygon3D.cpp b/src/util/Polygon3D.cpp index a8f27642..8f3c078f 100644 --- a/src/util/Polygon3D.cpp +++ b/src/util/Polygon3D.cpp @@ -75,7 +75,7 @@ void Polygon3D::init() { for (int e = 0; e < verts.size(); e++) { vec2 localPoint = project(verts[e]); localVerts.push_back(localPoint); - topdownVerts.push_back(vec2(verts[e].x, verts[e].y)); + topdownVerts.emplace_back(vec2(verts[e].x, verts[e].y)); expandBoundingBox(localPoint, localMins, localMaxs); expandBoundingBox(verts[e], worldMins, worldMaxs); center += verts[e]; @@ -191,8 +191,8 @@ std::vector> Polygon3D::cut(Line2D cutLine) { } - splitPolys.push_back(std::vector()); - splitPolys.push_back(std::vector()); + splitPolys.emplace_back(std::vector()); + splitPolys.emplace_back(std::vector()); // get new verts with intersection points included @@ -316,7 +316,7 @@ void Polygon3D::removeDuplicateVerts(float epsilon) { } if (verts.size() != newVerts.size()) { //print_log("Removed {} duplicate verts\n", verts.size() - newVerts.size()); - verts = newVerts; + verts = std::move(newVerts); init(); } } @@ -357,7 +357,7 @@ void Polygon3D::removeColinearVerts() { if (verts.size() != newVerts.size()) { //print_log("Removed {} colinear verts\n", verts.size() - newVerts.size()); - verts = newVerts; + verts = std::move(newVerts); init(); } } @@ -520,7 +520,7 @@ Polygon3D Polygon3D::coplanerIntersectArea(Polygon3D otherPoly) { // project other polys verts onto the same coordinate system as this face std::vector otherLocalVerts; for (int i = 0; i < otherPoly.verts.size(); i++) { - otherLocalVerts.push_back(project(otherPoly.verts[i])); + otherLocalVerts.emplace_back(project(otherPoly.verts[i])); } otherPoly.localVerts = otherLocalVerts; @@ -559,7 +559,7 @@ Polygon3D Polygon3D::coplanerIntersectArea(Polygon3D otherPoly) { localOutVerts = GrahamScan::findConvexHull(&localOutVerts[0], (int) localOutVerts.size()); for (int i = 0; i < localOutVerts.size(); i++) { - outVerts.push_back(unproject(localOutVerts[i])); + outVerts.emplace_back(unproject(localOutVerts[i])); } return outVerts; diff --git a/src/util/Polygon3D.h b/src/util/Polygon3D.h index 0755bdf7..cef77651 100644 --- a/src/util/Polygon3D.h +++ b/src/util/Polygon3D.h @@ -39,7 +39,7 @@ class Polygon3D { int idx = -1; // for octree lookup - Polygon3D() {} + Polygon3D() = default; Polygon3D(const std::vector& verts); diff --git a/src/util/quantizer.cpp b/src/util/quantizer.cpp index f95357e2..7d15934b 100644 --- a/src/util/quantizer.cpp +++ b/src/util/quantizer.cpp @@ -75,7 +75,7 @@ void Quantizer::ProcessImage(COLOR3* image, unsigned int size) m_nLeafCount = 0; m_lastIndex = 0; - for (unsigned int i = 0; i < size; i++) + for (size_t i = 0; i < size; i++) { AddColor(&m_pTree, image[i], 0, &m_nLeafCount, m_pReducibleNodes); @@ -123,7 +123,8 @@ unsigned int Quantizer::GetNearestIndex(COLOR3 c, COLOR3* pal) if (ColorsAreEqual(c, pal[m_lastIndex])) return m_lastIndex; unsigned int cur = 0; - for (unsigned int i = 0, k = 0, distance = 2147483647; i < m_nLeafCount; i++) + unsigned distance = INT_MAX; + for (unsigned int i = 0, k = 0; i < m_nLeafCount; i++) { k = (unsigned int)((pal[i].r - c.r) * (pal[i].r - c.r) + (pal[i].g - c.g) * (pal[i].g - c.g) + (pal[i].b - c.b) * (pal[i].b - c.b)); if (k <= 0) @@ -518,8 +519,8 @@ void Quantizer::GenColorTable() unsigned int j, k, nr, ng, nb, ns, a, b; for (j = 0; j < m_nMaxColors; j++) { - a = (j * m_nLeafCount) / m_nMaxColors; - b = ((j + 1) * m_nLeafCount) / m_nMaxColors; + a = (j * m_nLeafCount) / (unsigned int)m_nMaxColors; + b = ((j + 1) * m_nLeafCount) / (unsigned int)m_nMaxColors; nr = ng = nb = ns = 0; for (k = a; k < b; k++) { diff --git a/src/util/quantizer.h b/src/util/quantizer.h index 39539da6..ad8b9481 100644 --- a/src/util/quantizer.h +++ b/src/util/quantizer.h @@ -28,7 +28,7 @@ class Quantizer Node* m_pTree; unsigned int m_nLeafCount; Node* m_pReducibleNodes[256]; - unsigned int m_nMaxColors; + size_t m_nMaxColors; unsigned char m_nColorBits; unsigned int m_lastIndex; COLOR3* m_pPalette; diff --git a/src/util/vectors.h b/src/util/vectors.h index 83151566..bc694630 100644 --- a/src/util/vectors.h +++ b/src/util/vectors.h @@ -134,35 +134,8 @@ struct vec3 return *this; } - float operator [] (const size_t i) const - { - switch (i) - { - case 0: - return x; - case 1: - return y; - case 2: - return z; - } - return z; - } - - float& operator [] (const size_t i) - { - switch (i) - { - case 0: - return x; - case 1: - return y; - case 2: - return z; - } - return z; - } - float operator [] (const int i) const + float& operator [] (ptrdiff_t i) { switch (i) { @@ -176,7 +149,7 @@ struct vec3 return z; } - float& operator [] (const int i) + float operator [] (ptrdiff_t i) const { switch (i) { @@ -189,12 +162,11 @@ struct vec3 } return z; } - }; struct vec3Hash { size_t operator()(const vec3(&v)) const { - size_t seed = 0; + size_t seed = 1; std::hash hasher; seed ^= hasher(v[0]) + 0x9e3779b9 + (seed << 6) + (seed >> 2); seed ^= hasher(v[1]) + 0x9e3779b9 + (seed << 6) + (seed >> 2); @@ -206,7 +178,7 @@ struct vec3Hash { struct pairHash { template size_t operator()(const std::pair& p) const { - size_t seed = 0; + size_t seed = 2; vec3Hash hasher; seed ^= hasher(p.first) + 0x9e3779b9 + (seed << 6) + (seed >> 2); seed ^= hasher(p.second) + 0x9e3779b9 + (seed << 6) + (seed >> 2); @@ -339,7 +311,7 @@ struct vec4 std::string toKeyvalueString(bool truncate = false, const std::string& suffix_x = " ", const std::string& suffix_y = " ", const std::string& suffix_z = " " , const std::string& suffix_w = ""); - float operator [] (const int i) const + float operator [] (ptrdiff_t i) const { switch (i) { @@ -353,7 +325,7 @@ struct vec4 return w; } - float& operator [] (const int i) + float& operator [] (ptrdiff_t i) { switch (i) {