1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
|
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
#include <cctype>
#include <stdexcept>
#include "S3OParser.h"
#include "s3o.h"
#include "Game/GlobalUnsynced.h"
#include "Rendering/GlobalRendering.h"
#include "Rendering/Textures/S3OTextureHandler.h"
#include "Sim/Misc/CollisionVolume.h"
#include "System/Exceptions.h"
#include "System/SpringMath.h"
#include "System/StringUtil.h"
#include "System/Log/ILog.h"
#include "System/FileSystem/FileHandler.h"
#include "System/Platform/byteorder.h"
void CS3OParser::Init() { numPoolPieces = 0; }
void CS3OParser::Kill() {
LOG_L(L_INFO, "[S3OParser::%s] allocated %u pieces", __func__, numPoolPieces);
// reuse piece innards when reloading
// piecePool.clear();
for (unsigned int i = 0; i < numPoolPieces; i++) {
piecePool[i].Clear();
}
numPoolPieces = 0;
}
S3DModel CS3OParser::Load(const std::string& name)
{
CFileHandler file(name);
std::vector<uint8_t> fileBuf;
if (!file.FileExists())
throw content_error("[S3OParser] could not find model-file " + name);
if (!file.IsBuffered()) {
fileBuf.resize(file.FileSize(), 0);
file.Read(fileBuf.data(), fileBuf.size());
} else {
fileBuf = std::move(file.GetBuffer());
}
if (fileBuf.size() < sizeof(S3OHeader))
throw content_error("[S3OParser] corrupted header for model-file " + name);
S3OHeader header;
memcpy(&header, fileBuf.data(), sizeof(header));
header.swap();
S3DModel model;
model.name = name;
model.type = MODELTYPE_S3O;
model.numPieces = 0;
model.texs[0] = (header.texture1 == 0)? "" : (char*) &fileBuf[header.texture1];
model.texs[1] = (header.texture2 == 0)? "" : (char*) &fileBuf[header.texture2];
model.mins = DEF_MIN_SIZE;
model.maxs = DEF_MAX_SIZE;
textureHandlerS3O.PreloadTexture(&model);
model.FlattenPieceTree(LoadPiece(&model, nullptr, fileBuf, header.rootPiece));
// set after the extrema are known
model.radius = (header.radius <= 0.01f)? model.CalcDrawRadius(): header.radius;
model.height = (header.height <= 0.01f)? model.CalcDrawHeight(): header.height;
model.relMidPos = float3(header.midx, header.midy, header.midz);
return model;
}
SS3OPiece* CS3OParser::AllocPiece()
{
std::lock_guard<spring::mutex> lock(poolMutex);
// lazily reserve pool here instead of during Init
// this way games using only one model-type do not
// cause redundant allocation
if (piecePool.empty())
piecePool.resize(MAX_MODEL_OBJECTS * 16);
if (numPoolPieces >= piecePool.size()) {
throw std::bad_alloc();
return nullptr;
}
return &piecePool[numPoolPieces++];
}
SS3OPiece* CS3OParser::LoadPiece(S3DModel* model, SS3OPiece* parent, std::vector<uint8_t>& buf, int offset)
{
if ((offset + sizeof(Piece)) > buf.size())
throw content_error("[S3OParser] corrupted piece for model-file " + model->name);
model->numPieces++;
// retrieve piece data
Piece* fp = reinterpret_cast<Piece*>(&buf[offset]); fp->swap();
Vertex* vertexList = reinterpret_cast<Vertex*>(&buf[fp->vertices]);
const int* indexList = reinterpret_cast<int*>(&buf[fp->vertexTable]);
const int* childList = reinterpret_cast<int*>(&buf[fp->children]);
// create piece
SS3OPiece* piece = AllocPiece();
piece->offset.x = fp->xoffset;
piece->offset.y = fp->yoffset;
piece->offset.z = fp->zoffset;
piece->primType = fp->primitiveType;
piece->name = (char*) &buf[fp->name];
piece->parent = parent;
// retrieve vertices
piece->SetVertexCount(fp->numVertices);
for (int a = 0; a < fp->numVertices; ++a) {
Vertex* v = vertexList++;
v->swap();
SS3OVertex sv;
sv.pos = float3(v->xpos, v->ypos, v->zpos);
sv.normal = float3(v->xnormal, v->ynormal, v->znormal);
if (sv.normal.CheckNaNs()) {
sv.normal.SafeANormalize();
} else {
sv.normal = ZeroVector;
}
sv.texCoords[0] = float2(v->texu, v->texv);
sv.texCoords[1] = float2(v->texu, v->texv);
sv.pieceIndex = model->numPieces - 1;
piece->SetVertex(a, sv);
}
// retrieve draw indices
piece->SetIndexCount(fp->vertexTableSize);
for (int a = 0; a < fp->vertexTableSize; ++a) {
piece->SetIndex(a, swabDWord(*(indexList++)));
}
// post-process the piece
{
piece->SetGlobalOffset(CMatrix44f::Identity());
piece->Trianglize();
piece->SetVertexTangents();
piece->SetMinMaxExtends();
model->mins = float3::min(piece->goffset + piece->mins, model->mins);
model->maxs = float3::max(piece->goffset + piece->maxs, model->maxs);
piece->SetCollisionVolume(CollisionVolume('b', 'z', piece->maxs - piece->mins, (piece->maxs + piece->mins) * 0.5f));
}
// load children pieces
piece->children.reserve(fp->numchildren);
for (int a = 0; a < fp->numchildren; ++a) {
const int childOffset = swabDWord(*(childList++));
piece->children.push_back(LoadPiece(model, piece, buf, childOffset));
}
return piece;
}
void SS3OPiece::SetMinMaxExtends()
{
for (const SS3OVertex& v: vertices) {
mins = float3::min(mins, v.pos);
maxs = float3::max(maxs, v.pos);
}
}
void SS3OPiece::Trianglize()
{
switch (primType) {
case S3O_PRIMTYPE_TRIANGLES: {
} break;
case S3O_PRIMTYPE_TRIANGLE_STRIP: {
if (indices.size() < 3) {
primType = S3O_PRIMTYPE_TRIANGLES;
indices.clear();
return;
}
decltype(indices) newIndices;
newIndices.resize(indices.size() * 3); // each index (can) create a new triangle
for (size_t i = 0; (i + 2) < indices.size(); ++i) {
// indices can contain end-of-strip markers (-1U)
if (indices[i + 0] == -1 || indices[i + 1] == -1 || indices[i + 2] == -1)
continue;
newIndices.push_back(indices[i + 0]);
newIndices.push_back(indices[i + 1]);
newIndices.push_back(indices[i + 2]);
}
primType = S3O_PRIMTYPE_TRIANGLES;
indices.swap(newIndices);
} break;
case S3O_PRIMTYPE_QUADS: {
if (indices.size() % 4 != 0) {
primType = S3O_PRIMTYPE_TRIANGLES;
indices.clear();
return;
}
decltype(indices) newIndices;
const size_t oldCount = indices.size();
newIndices.resize(oldCount + oldCount / 2); // 4 indices become 6
for (size_t i = 0, j = 0; i < indices.size(); i += 4) {
newIndices[j++] = indices[i + 0];
newIndices[j++] = indices[i + 1];
newIndices[j++] = indices[i + 2];
newIndices[j++] = indices[i + 0];
newIndices[j++] = indices[i + 2];
newIndices[j++] = indices[i + 3];
}
primType = S3O_PRIMTYPE_TRIANGLES;
indices.swap(newIndices);
} break;
default: {
} break;
}
}
void SS3OPiece::SetVertexTangents()
{
if (!HasGeometryData())
return;
unsigned int stride = 0;
switch (primType) {
case S3O_PRIMTYPE_TRIANGLES : { stride = 3; } break;
case S3O_PRIMTYPE_TRIANGLE_STRIP: { stride = 1; } break;
case S3O_PRIMTYPE_QUADS : { return; } break;
}
// set the triangle-level S- and T-tangents
// for triangle strips, the piece vertex _indices_ are defined
// by the draw order of the vertices numbered <v, v + 1, v + 2>
// for v in [0, n - 2]
for (unsigned int i = 0, n = indices.size() - 2 * (stride == 1); i < n; i += stride) {
const bool flipWinding = ((primType == S3O_PRIMTYPE_TRIANGLE_STRIP) && ((i & 1) == 1));
const int v0idx = indices[i ];
const int v1idx = indices[i + (flipWinding? 2: 1)];
const int v2idx = indices[i + (flipWinding? 1: 2)];
if (v1idx == -1 || v2idx == -1) {
// not a valid triangle, skip
// to start of next tri-strip
i += 3; continue;
}
SS3OVertex& v0 = vertices[v0idx];
SS3OVertex& v1 = vertices[v1idx];
SS3OVertex& v2 = vertices[v2idx];
const float3& p0 = v0.pos;
const float3& p1 = v1.pos;
const float3& p2 = v2.pos;
const float2& tc0 = v0.texCoords[0];
const float2& tc1 = v1.texCoords[0];
const float2& tc2 = v2.texCoords[0];
const float3 p10 = p1 - p0;
const float3 p20 = p2 - p0;
const float2 tc10 = tc1 - tc0;
const float2 tc20 = tc2 - tc0;
// if d is 0, texcoors are degenerate
const float d = (tc10.x * tc20.y - tc20.x * tc10.y);
const float r = (d > -0.0001f && d < 0.0001f)? 1.0f: 1.0f / d;
// note: not necessarily orthogonal to each other
// or to vertex normal, only to the triangle plane
const float3 sdir = {tc20.y * p10.x - tc10.y * p20.x, tc20.y * p10.y - tc10.y * p20.y, tc20.y * p10.z - tc10.y * p20.z};
const float3 tdir = {tc10.x * p20.x - tc20.x * p10.x, tc10.x * p20.y - tc20.x * p10.y, tc10.x * p20.z - tc20.x * p10.z};
v0.sTangent += (sdir * r);
v1.sTangent += (sdir * r);
v2.sTangent += (sdir * r);
v0.tTangent += (tdir * r);
v1.tTangent += (tdir * r);
v2.tTangent += (tdir * r);
}
// set the smoothed per-vertex tangents
for (unsigned int i = 0, n = vertices.size(); i < n; i++) {
float3& N = vertices[i].normal;
float3& T = vertices[i].sTangent;
float3& B = vertices[i].tTangent; // bi
N.AssertNaNs();
T.AssertNaNs();
B.AssertNaNs();
const float bitangentAngle = B.dot(N.cross(T)); // dot(B,B')
const float handednessSign = Sign(bitangentAngle);
T = (T - N * N.dot(T));
B = (N.cross(T.SafeANormalize())) * handednessSign;
}
}
|