/
RenderablePicoSurface.cpp
428 lines (361 loc) · 11.3 KB
/
RenderablePicoSurface.cpp
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
#include "RenderablePicoSurface.h"
#include "itextstream.h"
#include "modelskin.h"
#include "math/Frustum.h"
#include "math/Ray.h"
#include "iselectiontest.h"
#include "irenderable.h"
#include <boost/algorithm/string/replace.hpp>
namespace model {
// Constructor. Copy the provided picoSurface_t structure into this object
RenderablePicoSurface::RenderablePicoSurface(picoSurface_t* surf,
const std::string& fExt)
: _shaderName(""),
_dlRegular(0),
_dlProgramVcol(0),
_dlProgramNoVCol(0)
{
// Get the shader from the picomodel struct. If this is a LWO model, use
// the material name to select the shader, while for an ASE model the
// bitmap path should be used.
picoShader_t* shader = PicoGetSurfaceShader(surf);
std::string rawName = "";
if (shader != 0)
{
if (fExt == "lwo")
{
_shaderName = PicoGetShaderName(shader);
}
else if (fExt == "ase")
{
rawName = PicoGetShaderName(shader);
std::string rawMapName = PicoGetShaderMapName(shader);
_shaderName = cleanupShaderName(rawMapName);
}
else // if extension is not handled explicitly, use at least something
{
_shaderName = PicoGetShaderName(shader);
}
}
// If shader not found, fallback to alternative if available
// _shaderName is empty if the ase material has no BITMAP
// materialIsValid is false if _shaderName is not an existing shader
if ((_shaderName.empty() || !GlobalMaterialManager().materialExists(_shaderName)) &&
!rawName.empty())
{
_shaderName = cleanupShaderName(rawName);
}
// Capturing the shader happens later on when we have a RenderSystem reference
// Get the number of vertices and indices, and reserve capacity in our
// vectors in advance by populating them with empty structs.
int nVerts = PicoGetSurfaceNumVertexes(surf);
_nIndices = PicoGetSurfaceNumIndexes(surf);
_vertices.resize(nVerts);
_indices.resize(_nIndices);
// Stream in the vertex data from the raw struct, expanding the local AABB
// to include each vertex.
for (int vNum = 0; vNum < nVerts; ++vNum) {
// Get the vertex position and colour
Vertex3f vertex(PicoGetSurfaceXYZ(surf, vNum));
Normal3f normal = PicoGetSurfaceNormal(surf, vNum);
// Expand the AABB to include this new vertex
_localAABB.includePoint(vertex);
_vertices[vNum].vertex = vertex;
_vertices[vNum].normal = normal;
_vertices[vNum].texcoord = TexCoord2f(PicoGetSurfaceST(surf, 0, vNum));
_vertices[vNum].colour =
getColourVector(PicoGetSurfaceColor(surf, 0, vNum));
}
// Stream in the index data
picoIndex_t* ind = PicoGetSurfaceIndexes(surf, 0);
for (unsigned int i = 0; i < _nIndices; i++)
_indices[i] = ind[i];
// Calculate the tangent and bitangent vectors
calculateTangents();
// Construct the DLs
createDisplayLists();
}
RenderablePicoSurface::RenderablePicoSurface(const RenderablePicoSurface& other) :
_shaderName(other._shaderName),
_vertices(other._vertices),
_indices(other._indices),
_nIndices(other._nIndices),
_localAABB(other._localAABB),
_dlRegular(0),
_dlProgramVcol(0),
_dlProgramNoVCol(0)
{
createDisplayLists();
}
std::string RenderablePicoSurface::cleanupShaderName(const std::string& inName)
{
const std::string baseFolder = "base"; //FIXME: should be from game.xml
std::size_t basePos;
std::string mapName = boost::algorithm::replace_all_copy(inName, "\\", "/");
// for paths given relative, start from the beginning
if (mapName.substr(0,6) == "models" || mapName.substr(0,8) == "textures")
{
basePos = 0;
}
else
{
// Take off the everything before "base/", and everything after
// the first period if it exists (i.e. strip off ".tga")
basePos = mapName.find(baseFolder);
if (basePos == std::string::npos)
{
// Unrecognised shader path, no base folder.
// Try the original incase it was already given relative.
basePos = 0;
}
else
{
// Increment for for the length of "base/", the / is the +1
basePos += (baseFolder.size() + 1);
}
}
std::size_t dotPos = mapName.find(".");
if (dotPos != std::string::npos)
{
return mapName.substr(basePos, dotPos - basePos);
}
else
{
return mapName.substr(basePos);
}
}
// Destructor. Release the GL display lists.
RenderablePicoSurface::~RenderablePicoSurface()
{
glDeleteLists(_dlRegular, 1);
glDeleteLists(_dlProgramNoVCol, 1);
glDeleteLists(_dlProgramVcol, 1);
}
// Convert byte pointers to colour vector
Vector3 RenderablePicoSurface::getColourVector(unsigned char* array) {
if (array) {
return Vector3(array[0] / 255.0f, array[1] / 255.0f, array[2] / 255.0f);
}
else {
return Vector3(1.0f, 1.0f, 1.0f); // white
}
}
// Tangent calculation
void RenderablePicoSurface::calculateTangents() {
// Calculate the tangents and bitangents using the indices into the vertex
// array.
for (Indices::iterator i = _indices.begin();
i != _indices.end();
i += 3)
{
ArbitraryMeshVertex& a = _vertices[*i];
ArbitraryMeshVertex& b = _vertices[*(i + 1)];
ArbitraryMeshVertex& c = _vertices[*(i + 2)];
// Call the tangent calculation function
ArbitraryMeshTriangle_sumTangents(a, b, c);
}
// Normalise all of the tangent and bitangent vectors
for (VertexVector::iterator j = _vertices.begin();
j != _vertices.end();
++j)
{
j->tangent.normalise();
j->bitangent.normalise();
}
}
// Front-end renderable submission
void RenderablePicoSurface::submitRenderables(RenderableCollector& rend,
const Matrix4& localToWorld,
const ShaderPtr& shader,
const IRenderEntity& entity)
{
// Submit geometry
rend.SetState(shader, RenderableCollector::eFullMaterials);
rend.addRenderable(*this, localToWorld, entity);
}
// Back-end render function
void RenderablePicoSurface::render(const RenderInfo& info) const
{
// Invoke appropriate display list
if (info.checkFlag(RENDER_PROGRAM))
{
if (info.checkFlag(RENDER_VERTEX_COLOUR))
{
glCallList(_dlProgramVcol);
}
else
{
glCallList(_dlProgramNoVCol);
}
}
else
{
glCallList(_dlRegular);
}
}
// Construct a list for GLProgram mode, either with or without vertex colour
GLuint RenderablePicoSurface::compileProgramList(bool includeColour)
{
GLuint list = glGenLists(1);
assert(list != 0); // check if we run out of display lists
glNewList(list, GL_COMPILE);
glBegin(GL_TRIANGLES);
for (Indices::const_iterator i = _indices.begin();
i != _indices.end();
++i)
{
// Get the vertex for this index
ArbitraryMeshVertex& v = _vertices[*i];
// Submit the vertex attributes and coordinate
if (GLEW_ARB_vertex_program)
{
glVertexAttrib2dvARB(ATTR_TEXCOORD, v.texcoord);
glVertexAttrib3dvARB(ATTR_TANGENT, v.tangent);
glVertexAttrib3dvARB(ATTR_BITANGENT, v.bitangent);
glVertexAttrib3dvARB(ATTR_NORMAL, v.normal);
}
// Optional vertex colour
if (includeColour)
{
glColor3dv(v.colour);
}
// Submit the vertex itself
glVertex3dv(v.vertex);
}
glEnd();
glEndList();
return list;
}
// Construct the two display lists
void RenderablePicoSurface::createDisplayLists()
{
// Generate the lists for lighting mode
_dlProgramNoVCol = compileProgramList(false);
_dlProgramVcol = compileProgramList(true);
// Generate the list for flat-shaded (unlit) mode
_dlRegular = glGenLists(1);
assert(_dlRegular != 0); // check if we run out of display lists
glNewList(_dlRegular, GL_COMPILE);
glBegin(GL_TRIANGLES);
for (Indices::const_iterator i = _indices.begin();
i != _indices.end();
++i)
{
// Get the vertex for this index
ArbitraryMeshVertex& v = _vertices[*i];
// Submit attributes
glNormal3dv(v.normal);
glTexCoord2dv(v.texcoord);
glVertex3dv(v.vertex);
}
glEnd();
glEndList();
}
// Perform selection test for this surface
void RenderablePicoSurface::testSelect(Selector& selector,
SelectionTest& test,
const Matrix4& localToWorld) const
{
if (!_vertices.empty() && !_indices.empty())
{
// Test for triangle selection
test.BeginMesh(localToWorld);
SelectionIntersection result;
test.TestTriangles(
VertexPointer(&_vertices[0].vertex, sizeof(ArbitraryMeshVertex)),
IndexPointer(&_indices[0],
IndexPointer::index_type(_indices.size())),
result
);
// Add the intersection to the selector if it is valid
if(result.isValid()) {
selector.addIntersection(result);
}
}
}
int RenderablePicoSurface::getNumVertices() const
{
return static_cast<int>(_vertices.size());
}
int RenderablePicoSurface::getNumTriangles() const
{
return static_cast<int>(_indices.size() / 3); // 3 indices per triangle
}
const ArbitraryMeshVertex& RenderablePicoSurface::getVertex(int vertexIndex) const
{
assert(vertexIndex >= 0 && vertexIndex < static_cast<int>(_vertices.size()));
return _vertices[vertexIndex];
}
ModelPolygon RenderablePicoSurface::getPolygon(int polygonIndex) const
{
assert(polygonIndex >= 0 && polygonIndex*3 < static_cast<int>(_indices.size()));
ModelPolygon poly;
poly.a = _vertices[_indices[polygonIndex*3]];
poly.b = _vertices[_indices[polygonIndex*3 + 1]];
poly.c = _vertices[_indices[polygonIndex*3 + 2]];
return poly;
}
const std::string& RenderablePicoSurface::getDefaultMaterial() const
{
return _shaderName;
}
void RenderablePicoSurface::setDefaultMaterial(const std::string& defaultMaterial)
{
_shaderName = defaultMaterial;
}
bool RenderablePicoSurface::getIntersection(const Ray& ray, Vector3& intersection, const Matrix4& localToWorld)
{
Vector3 bestIntersection = ray.origin;
Vector3 triIntersection;
for (Indices::const_iterator i = _indices.begin();
i != _indices.end();
i += 3)
{
// Get the vertices for this triangle
const ArbitraryMeshVertex& p1 = _vertices[*(i)];
const ArbitraryMeshVertex& p2 = _vertices[*(i+1)];
const ArbitraryMeshVertex& p3 = _vertices[*(i+2)];
if (ray.intersectTriangle(localToWorld.transformPoint(p1.vertex),
localToWorld.transformPoint(p2.vertex), localToWorld.transformPoint(p3.vertex), triIntersection))
{
intersection = triIntersection;
// Test if this surface intersection is better than what we currently have
float oldDistSquared = (bestIntersection - ray.origin).getLengthSquared();
float newDistSquared = (triIntersection - ray.origin).getLengthSquared();
if ((oldDistSquared == 0 && newDistSquared > 0) || newDistSquared < oldDistSquared)
{
bestIntersection = triIntersection;
}
}
}
if ((bestIntersection - ray.origin).getLengthSquared() > 0)
{
intersection = bestIntersection;
return true;
}
else
{
return false;
}
}
void RenderablePicoSurface::applyScale(const Vector3& scale, const RenderablePicoSurface& originalSurface)
{
if (scale.x() == 0 || scale.y() == 0 || scale.z() == 0)
{
rMessage() << "RenderablePicoSurface: Cannot apply scale with a zero diagonal element" << std::endl;
return;
}
Matrix4 scaleMatrix = Matrix4::getScale(scale);
Matrix4 invTranspScale = Matrix4::getScale(Vector3(1/scale.x(), 1/scale.y(), 1/scale.z()));
assert(originalSurface.getNumVertices() == getNumVertices());
for (std::size_t i = 0; i < _vertices.size(); ++i)
{
_vertices[i].vertex = scaleMatrix.transformPoint(originalSurface._vertices[i].vertex);
_vertices[i].normal = invTranspScale.transformPoint(originalSurface._vertices[i].normal);
}
glDeleteLists(_dlRegular, 1);
glDeleteLists(_dlProgramNoVCol, 1);
glDeleteLists(_dlProgramVcol, 1);
createDisplayLists();
}
} // namespace model