Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
lewa-j committed Mar 21, 2022
0 parents commit f311886
Show file tree
Hide file tree
Showing 16 changed files with 24,767 additions and 0 deletions.
14 changes: 14 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
CMakeLists.txt.user
CMakeCache.txt
CMakeFiles
CMakeScripts
Testing
Makefile
cmake_install.cmake
install_manifest.txt
compile_commands.json
CTestTestfile.cmake
CMakeSettings.json
_deps
out
.vs
18 changes: 18 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Copyright (c) 2022 Alexey Ivanchukov (lewa_j)
cmake_minimum_required (VERSION 3.8)

project ("bsp-converter")

add_executable (bsp-converter
"src/bsp-converter.h"
"src/bsp-converter.cpp"
"src/hlbsp.h"
"src/hlbsp.cpp"
"src/texture.h"
"src/texture.cpp"
"src/lightmap.h"
"src/lightmap.cpp"
"src/gltf_export.h"
"src/gltf_export.cpp")

install(TARGETS bsp-converter DESTINATION bin)
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Alexey Ivanchukov (lewa_j)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# hlbsp-converter

A tool to convert bsp maps (Half-Life and other GoldSrc games) into gltf scenes.

## Key features:

* Export embedded texture
* Lightmaps!
* Option to exclude sky polygons

## Usage

```sh
./bsp-converter map-name.bsp [options]
```

### Options

* `-lm <number>` - set a lightmap atlas size
* `-skip_sky` - exclude polygons with 'sky' texture from export

## Dependencies (already included)

* [nlohmann/json](https://github.com/nlohmann/json)
* [stb_image_write](https://github.com/nothings/stb)

## Acknowledgments

* id for [Quake 2](https://github.com/id-Software/Quake-2)
* UnkleMike and FWGS for [Xash3D](https://github.com/FWGS/xash3d-fwgs)

## License

This project is licensed under the MIT License - see the LICENSE file for details
72 changes: 72 additions & 0 deletions src/bsp-converter.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright (c) 2022 Alexey Ivanchukov (lewa_j)
#include "bsp-converter.h"
#include "hlbsp.h"
#include "gltf_export.h"

int main(int argc, const char *argv[])
{
printf("bsp-converter by lewa_j v0.6 - 2022\n");
if (argc < 2 || !strcmp(argv[1], "-h"))
{
printf("Usage: bsp-converter map.bsp [-lm <lightmap atlas size>] [-skip_sky]\n");
return -1;
}

std::string mapName = argv[1];
std::string rootPath;
{
int p = mapName.find_last_of("/\\");
if (p != std::string::npos) {
rootPath = mapName.substr(0, p + 1);
mapName = mapName.substr(p + 1);
}
auto l = mapName.find_last_of('.');
if (l)
mapName = mapName.substr(0, l);
}

hlbsp::LoadConfig config;

for (int i = 2; i < argc; i++)
{
if (!strcmp(argv[i], "-lm"))
{
if (argc > i + 1)
{
i++;
config.lightmapSize = atoi(argv[i]);
}
else
{
printf("Warning: '-lm' parameter requires a number - lightmap atlas resolution\n");
}
}
else if (!strcmp(argv[i], "-skip_sky"))
{
config.skipSky = true;
printf("Sky polygons will be excluded from export\n");
}
else
{
printf("Warning: unknown parameter \"%s\"\n", argv[i]);
}
}
if (!config.lightmapSize)
config.lightmapSize = 1024;

hlbsp::Map map;
if (!map.load(argv[1], mapName.c_str(), &config))
{
fprintf(stderr, "Can't load map\n");
return -1;
}

if (!gltf::ExportMap(mapName, map))
{
fprintf(stderr, "Export failed\n");
return -1;
}

printf("Success\n");
return 0;
}
2 changes: 2 additions & 0 deletions src/bsp-converter.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Copyright (c) 2022 Alexey Ivanchukov (lewa_j)
#pragma once
120 changes: 120 additions & 0 deletions src/gltf_export.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// Copyright (c) 2022 Alexey Ivanchukov (lewa_j)
#include "gltf_export.h"
#include "nlohmann/json.hpp"
#include <fstream>
#include <direct.h>

namespace gltf
{

bool ExportMap(const std::string &name, hlbsp::Map &map)
{
using nlohmann::json;
json j;
j["asset"] = { {"version", "2.0"} };
j["scene"] = 0;
j["scenes"] = { { { "nodes", {0} } } };
auto &nodes = j["nodes"];
nodes[0] = {
{"name",name},
{"rotation",{-sqrt(0.5f),0,0,sqrt(0.5f)}},
{"scale",{0.03,0.03,0.03}}
};
auto &meshes = j["meshes"];
auto &accessors = j["accessors"];
auto &bufferViews = j["bufferViews"];
int accessorId = 0;
int modelAccessorId = 0;
int bufferViewId = 0;
const int indsBufferOffset = map.vertices.size() * sizeof(map.vertices[0]);
for (int i = 0; i < map.models.size(); i++)
{
nodes[0]["children"].push_back(i + 1);
nodes[i + 1] = { {"mesh", i}, {"name",std::string("*") + std::to_string(i)} };

bufferViews[bufferViewId + 0] = { {"buffer", 0}, {"byteOffset", indsBufferOffset + map.models[i].offset * sizeof(map.indices[0])}, {"byteLength", map.models[i].count * sizeof(map.indices[0])}, {"target", ELEMENT_ARRAY_BUFFER} };
bufferViews[bufferViewId + 1] = { {"buffer", 0}, {"byteOffset", map.models[i].vertOffset * sizeof(map.vertices[0])}, {"byteLength", map.models[i].vertCount * sizeof(map.vertices[0])},{"byteStride", 28}, {"target", ARRAY_BUFFER} };
hlbsp::vec3_t bmin{ FLT_MAX, FLT_MAX, FLT_MAX };
hlbsp::vec3_t bmax{ -FLT_MAX, -FLT_MAX, -FLT_MAX };
for (int j = 0; j < map.models[i].vertCount; j++)
{
hlbsp::vec3_t v = map.vertices[map.models[i].vertOffset + j].pos;
bmin.x = fmin(bmin.x, v.x);
bmin.y = fmin(bmin.y, v.y);
bmin.z = fmin(bmin.z, v.z);
bmax.x = fmax(bmax.x, v.x);
bmax.y = fmax(bmax.y, v.y);
bmax.z = fmax(bmax.z, v.z);
}
accessors[accessorId + 0] = { {"bufferView",bufferViewId + 1},{"byteOffset",0},{"componentType",FLOAT},{"count",map.models[i].vertCount},{"type","VEC3"}, {"min",{bmin.x, bmin.y, bmin.z}}, {"max",{bmax.x, bmax.y, bmax.z}} };
accessors[accessorId + 1] = { {"bufferView",bufferViewId + 1},{"byteOffset",12},{"componentType",FLOAT},{"count",map.models[i].vertCount},{"type","VEC2"} };
accessors[accessorId + 2] = { {"bufferView",bufferViewId + 1},{"byteOffset",20},{"componentType",FLOAT},{"count",map.models[i].vertCount},{"type","VEC2"} };
modelAccessorId = accessorId;
accessorId += 3;

meshes[i] = { {"name", name + "_mesh" + std::to_string(i)}, {"primitives",json::array()} };
for (int j = 0; j < map.models[i].submeshes.size(); j++)
{
meshes[i]["primitives"][j] = {
{"attributes", {{"POSITION",modelAccessorId + 0}, {"TEXCOORD_0",modelAccessorId + 1}, {"TEXCOORD_1",modelAccessorId + 2}}},
{"indices", accessorId},
{"material", map.models[i].submeshes[j].material}
};
accessors[accessorId] = { {"bufferView", bufferViewId}, { "byteOffset", (map.models[i].submeshes[j].offset - map.models[i].offset) * sizeof(map.indices[0]) }, { "componentType", UNSIGNED_INT }, { "count", map.models[i].submeshes[j].count }, { "type","SCALAR" } };
accessorId++;
}
bufferViewId += 2;
}

_mkdir("textures");

auto &materials = j["materials"];
auto &textures = j["textures"];
auto &images = j["images"];
//TODO: write only used textures
int lmapTexIndex = map.textures.size();
for (int i = 0; i < map.textures.size(); i++)
{
std::string texturePath = std::string("textures/") + map.textures[i].name + ".png";
if (map.textures[i].data.size())
map.textures[i].save(texturePath.c_str());

images[i] = { {"uri", texturePath} };
textures[i] = { {"source", i} };
materials[i] = {
{"name", map.textures[i].name},
{"pbrMetallicRoughness",{
{"baseColorTexture",{{"index",i}}},
{"metallicFactor", 0}
}}
//,{"emissiveTexture", {{"index", lmapTexIndex}, {"texCoord", 1}}},
//{"emissiveFactor", {1,1,1}}
};
}

images[lmapTexIndex] = { {"uri", name + "_lightmap0.png"} };
textures[lmapTexIndex] = { {"source", lmapTexIndex} };

std::string bufferName = name + ".bin";

int vertsLen = map.vertices.size() * sizeof(map.vertices[0]);
int indsLen = map.indices.size() * sizeof(map.indices[0]);
j["buffers"] = { { {"uri", bufferName}, {"byteLength", vertsLen + indsLen} } };

printf("Writing: %s\n", bufferName.c_str());
std::ofstream verts(bufferName, std::ios_base::binary);
verts.write((char *)&map.vertices[0], vertsLen);
verts.write((char *)&map.indices[0], indsLen);
verts.close();

printf("Writing: %s.gltf\n", name.c_str());
std::ofstream o(name + ".gltf");
// enable 'pretty printing'
o << std::setw(4);
o << j << std::endl;
o.close();

return true;
}

}//gltf
19 changes: 19 additions & 0 deletions src/gltf_export.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright (c) 2022 Alexey Ivanchukov (lewa_j)
#pragma once

#include "hlbsp.h"

namespace gltf
{
enum
{
UNSIGNED_SHORT = 0x1403,
UNSIGNED_INT = 0x1405,
FLOAT = 0x1406,

ARRAY_BUFFER = 0x8892,
ELEMENT_ARRAY_BUFFER = 0x8893
};

bool ExportMap(const std::string &name, hlbsp::Map &map);
}
Loading

0 comments on commit f311886

Please # to comment.