Oolite
Loading...
Searching...
No Matches
OOMesh Class Reference

#include <OOMesh.h>

Inheritance diagram for OOMesh:
Collaboration diagram for OOMesh:

Instance Methods

(NSString *) - modelName
(void) - rebindMaterials
(NSDictionary *) - materials
(NSDictionary *) - shaders
(size_t) - vertexCount
(size_t) - faceCount
(Octree *) - octree
(BoundingBox) - findBoundingBoxRelativeToPosition:ri:rj:rk:selfPosition:si:sj:sk:
(BoundingBox) - findSubentityBoundingBoxWithPosition:rotMatrix:
(OOMesh *) - meshRescaledBy:
(id) - init [implementation]
(void) - dealloc [implementation]
(NSString *) - descriptionComponents [implementation]
(id) - copyWithZone: [implementation]
(void) - renderOpaqueParts [implementation]
(BOOL) - hasOpaqueParts [implementation]
(unsigned) - octreeDepth [implementation]
(void) - setBindingTarget: [implementation]
(BOOL) - suppressClangStuff [implementation]
(id) - initWithName:cacheKey:materialDictionary:shadersDictionary:smooth:shaderMacros:shaderBindingTarget:scaleFactor:cacheWriteable: [implementation]
(BOOL) - loadData:scaleFactor: [implementation]
(void) - checkNormalsAndAdjustWinding [implementation]
(void) - generateFaceTangents [implementation]
(void) - calculateVertexNormalsAndTangentsWithFaceRefs: [implementation]
(void) - calculateVertexTangentsWithFaceRefs: [implementation]
(void) - deleteDisplayLists [implementation]
(NSDictionary *) - modelData [implementation]
(BOOL) - setModelFromModelData:name: [implementation]
(void) - getNormal:andTangent:forVertex:inSmoothGroup: [implementation]
(BOOL) - setUpVertexArrays [implementation]
(void) - calculateBoundingVolumes [implementation]
(void) - rescaleByFactor: [implementation]
(void) - setRetainedObject:forKey: [implementation]
(void *) - allocateBytesWithSize:count:key: [implementation]
(BOOL) - allocateVertexBuffersWithCount: [implementation]
(BOOL) - allocateNormalBuffersWithCount: [implementation]
(BOOL) - allocateFaceBuffersWithCount: [implementation]
(BOOL) - allocateVertexArrayBuffersWithCount: [implementation]
(void) - renameTexturesFrom:to: [implementation]
(id) - mutableCopyWithZone: [implementation]
(void) - resetGraphicsState [implementation]
Instance Methods inherited from OODrawable
(void) - renderTranslucentParts
(BOOL) - hasTranslucentParts
(GLfloat) - collisionRadius
(GLfloat) - maxDrawDistance
(BoundingBox) - boundingBox
(void) - dumpSelfState

Class Methods

(instancetype) + meshWithName:cacheKey:materialDictionary:shadersDictionary:smooth:shaderMacros:shaderBindingTarget:
(instancetype) + meshWithName:cacheKey:materialDictionary:shadersDictionary:smooth:shaderMacros:shaderBindingTarget:scaleFactor:cacheWriteable:
(OOMaterial *) + placeholderMaterial
(static NSString *) + NormalModeDescription [implementation]
(static float) + FaceArea [implementation]
(static float) + FaceAreaCorrect [implementation]

Private Attributes

uint8_t _normalMode: 2
uint8_t brokenInRender: 1
uint8_t listsReady: 1
OOMeshMaterialCount materialCount
OOMeshVertexCount vertexCount
OOMeshFaceCount faceCount
NSString * baseFile
NSString * baseFileOctreeCacheRef
BOOL _cacheWriteable
Vector * _vertices
Vector * _normals
Vector * _tangents
OOMeshFace * _faces
OOMeshDisplayLists _displayLists
NSRange triangle_range [kOOMeshMaxMaterials]
NSString * materialKeys [kOOMeshMaxMaterials]
OOMaterial * materials [kOOMeshMaxMaterials]
GLuint displayList0
GLfloat collisionRadius
GLfloat maxDrawDistance
BoundingBox boundingBox
Octree * octree
NSMutableDictionary * _retainedObjects
NSDictionary * _materialDict
NSDictionary * _shadersDict
NSString * _cacheKey
NSDictionary * _shaderMacros
id _shaderBindingTarget
Vector _lastPosition
OOMatrix _lastRotMatrix
BoundingBox _lastBoundingBox

Detailed Description

Definition at line 82 of file OOMesh.h.

Method Documentation

◆ allocateBytesWithSize:count:key:

- (void *) allocateBytesWithSize: (size_t) size
count: (NSUInteger) count
key: (NSString*) key 
implementation

Provided by category OOMesh(Private).

Definition at line 1941 of file OOMesh.m.

1941 :(size_t)size count:(NSUInteger)count key:(NSString*)key
1942{
1943 if (count == 0) {
1944 count = 1;
1945 }
1946 size *= count;
1947 void* bytes = malloc(size);
1948 if (bytes != NULL) {
1949 Scribble(bytes, size);
1950 NSData* holder = [NSData dataWithBytesNoCopy:bytes length:size freeWhenDone:YES];
1951 [self setRetainedObject:holder forKey:key];
1952 }
1953 return bytes;
1954}
#define Scribble(bytes, size)
Definition OOMesh.m:1933
unsigned count
voidpf void uLong size
Definition ioapi.h:126

Referenced by OOMesh(Private)::allocateFaceBuffersWithCount:, OOMesh(Private)::allocateNormalBuffersWithCount:, OOMesh(Private)::allocateVertexArrayBuffersWithCount:, and OOMesh(Private)::allocateVertexBuffersWithCount:.

Here is the caller graph for this function:

◆ allocateFaceBuffersWithCount:

- (BOOL) allocateFaceBuffersWithCount: (NSUInteger) count
implementation

Provided by category OOMesh(Private).

Definition at line 1969 of file OOMesh.m.

1969 :(NSUInteger)count
1970{
1971 _faces = [self allocateBytesWithSize:sizeof *_faces count:faceCount key:@"faces"];
1972 return _faces != NULL;
1973}
OOMeshFace * _faces
Definition OOMesh.h:99

◆ allocateNormalBuffersWithCount:

- (BOOL) allocateNormalBuffersWithCount: (NSUInteger) count
implementation

Provided by category OOMesh(Private).

Definition at line 1962 of file OOMesh.m.

1962 :(NSUInteger)count
1963{
1964 _normals = [self allocateBytesWithSize:sizeof *_normals count:vertexCount key:@"normals"];
1965 _tangents = [self allocateBytesWithSize:sizeof *_tangents count:vertexCount key:@"tangents"];
1966 return _normals != NULL && _tangents != NULL;
1967}
Vector * _tangents
Definition OOMesh.h:98
Vector * _normals
Definition OOMesh.h:97

◆ allocateVertexArrayBuffersWithCount:

- (BOOL) allocateVertexArrayBuffersWithCount: (NSUInteger) count
implementation

Provided by category OOMesh(Private).

Definition at line 1975 of file OOMesh.m.

1975 :(NSUInteger)count
1976{
1977 _displayLists.indexArray = [self allocateBytesWithSize:sizeof *_displayLists.indexArray count:count * 3 key:@"indexArray"];
1978 _displayLists.textureUVArray = [self allocateBytesWithSize:sizeof *_displayLists.textureUVArray count:count * 6 key:@"textureUVArray"];
1979 _displayLists.vertexArray = [self allocateBytesWithSize:sizeof *_displayLists.vertexArray count:count * 3 key:@"vertexArray"];
1980 _displayLists.normalArray = [self allocateBytesWithSize:sizeof *_displayLists.normalArray count:count * 3 key:@"normalArray"];
1981 _displayLists.tangentArray = [self allocateBytesWithSize:sizeof *_displayLists.tangentArray count:count * 3 key:@"tangentArray"];
1982
1983 return _faces != NULL && _displayLists.indexArray != NULL && _displayLists.textureUVArray != NULL && _displayLists.vertexArray != NULL && _displayLists.normalArray != NULL && _displayLists.tangentArray != NULL;
1984}
OOMeshDisplayLists _displayLists
Definition OOMesh.h:102

◆ allocateVertexBuffersWithCount:

- (BOOL) allocateVertexBuffersWithCount: (NSUInteger) count
implementation

Provided by category OOMesh(Private).

Definition at line 1956 of file OOMesh.m.

1956 :(NSUInteger)count
1957{
1958 _vertices = [self allocateBytesWithSize:sizeof *_vertices count:vertexCount key:@"vertices"];
1959 return _vertices != NULL;
1960}
Vector * _vertices
Definition OOMesh.h:96

◆ calculateBoundingVolumes

- (void) calculateBoundingVolumes
implementation

Provided by category OOMesh(Private).

Definition at line 1786 of file OOMesh.m.

1787{
1789
1791 float d_squared, length_longest_axis, length_shortest_axis;
1792 GLfloat result;
1793
1794 result = 0.0f;
1795 if (vertexCount)
1797 else
1799
1800 for (i = 0; i < vertexCount; i++) {
1801 d_squared = magnitude2(_vertices[i]);
1802 if (d_squared > result)
1803 result = d_squared;
1805 }
1806
1807 length_longest_axis = boundingBox.max.x - boundingBox.min.x;
1808 if (boundingBox.max.y - boundingBox.min.y > length_longest_axis)
1809 length_longest_axis = boundingBox.max.y - boundingBox.min.y;
1810 if (boundingBox.max.z - boundingBox.min.z > length_longest_axis)
1811 length_longest_axis = boundingBox.max.z - boundingBox.min.z;
1812
1813 length_shortest_axis = boundingBox.max.x - boundingBox.min.x;
1814 if (boundingBox.max.y - boundingBox.min.y < length_shortest_axis)
1815 length_shortest_axis = boundingBox.max.y - boundingBox.min.y;
1816 if (boundingBox.max.z - boundingBox.min.z < length_shortest_axis)
1817 length_shortest_axis = boundingBox.max.z - boundingBox.min.z;
1818
1819 d_squared = (length_longest_axis + length_shortest_axis) * (length_longest_axis + length_shortest_axis) * 0.25; // square of average length
1820 maxDrawDistance = d_squared * NO_DRAW_DISTANCE_FACTOR * NO_DRAW_DISTANCE_FACTOR; // no longer based on the collision radius
1821
1822 collisionRadius = sqrtf(result);
1823
1825}
#define NO_DRAW_DISTANCE_FACTOR
Definition Entity.h:49
OOINLINE void bounding_box_reset_to_vector(BoundingBox *box, Vector vec) ALWAYS_INLINE_FUNC NONNULL_FUNC
OOINLINE void bounding_box_add_vector(BoundingBox *box, Vector vec) ALWAYS_INLINE_FUNC NONNULL_FUNC
OOINLINE void bounding_box_reset(BoundingBox *box) NONNULL_FUNC
#define OOJS_PROFILE_EXIT_VOID
#define OOJS_PROFILE_ENTER
uint32_t OOMeshVertexCount
Definition OOMesh.h:55
float x
OOINLINE OOScalar magnitude2(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:237
GLfloat maxDrawDistance
Definition OOMesh.m:585
BoundingBox boundingBox
Definition OOMesh.h:111
OOMeshVertexCount vertexCount
Definition OOMesh.m:358
GLfloat collisionRadius
Definition OOMesh.m:580

Referenced by OOMesh(Private)::initWithName:cacheKey:materialDictionary:shadersDictionary:smooth:shaderMacros:shaderBindingTarget:scaleFactor:cacheWriteable:, OOMesh(Private)::loadData:scaleFactor:, and OOMesh(Private)::rescaleByFactor:.

Here is the caller graph for this function:

◆ calculateVertexNormalsAndTangentsWithFaceRefs:

- (void) calculateVertexNormalsAndTangentsWithFaceRefs: (VertexFaceRef*) faceRefs
implementation

Provided by category OOMesh(Private).

Definition at line 1580 of file OOMesh.m.

1580 :(VertexFaceRef*)faceRefs
1581{
1583
1584 NSParameterAssert(faceRefs != NULL);
1585
1586 NSUInteger i, j;
1587 float triangle_area[faceCount];
1588
1589 NSAssert1(_normals != NULL && _tangents != NULL, @"Normal/tangent buffers not allocated in %s", __PRETTY_FUNCTION__);
1590
1591 for (i = 0; i < faceCount; i++) {
1592 triangle_area[i] = FaceArea(_faces[i].vertex, _vertices);
1593 }
1594 for (i = 0; i < vertexCount; i++) {
1595 Vector normal_sum = kZeroVector;
1596 Vector tangent_sum = kZeroVector;
1597
1598 VertexFaceRef* vfr = &faceRefs[i];
1599 NSUInteger fIter, fCount = VFRGetCount(vfr);
1600 for (fIter = 0; fIter < fCount; fIter++) {
1601 j = VFRGetFaceAtIndex(vfr, fIter);
1602
1603 float t = triangle_area[j]; // weight sum by area
1604 normal_sum = vector_add(normal_sum, vector_multiply_scalar(_faces[j].normal, t));
1605 tangent_sum = vector_add(tangent_sum, vector_multiply_scalar(_faces[j].tangent, t));
1606 }
1607
1608 normal_sum = vector_normal_or_fallback(normal_sum, kBasisZVector);
1609 tangent_sum = vector_subtract(tangent_sum, vector_multiply_scalar(normal_sum, dot_product(tangent_sum, normal_sum)));
1610 tangent_sum = vector_normal_or_fallback(tangent_sum, kBasisXVector);
1611
1612 _normals[i] = normal_sum;
1613 _tangents[i] = tangent_sum;
1614 }
1615
1617}
static NSUInteger VFRGetCount(VertexFaceRef *vfr)
struct VertexFaceRef VertexFaceRef
static NSUInteger VFRGetFaceAtIndex(VertexFaceRef *vfr, NSUInteger index)
OOINLINE Vector vector_add(Vector a, Vector b) INLINE_CONST_FUNC
Definition OOVector.h:195
OOINLINE Vector vector_subtract(Vector a, Vector b) INLINE_CONST_FUNC
Definition OOVector.h:218
struct Vector Vector
OOINLINE OOScalar dot_product(Vector first, Vector second) INLINE_CONST_FUNC
Definition OOVector.h:299
OOINLINE Vector vector_normal_or_fallback(Vector vec, Vector fallback) INLINE_CONST_FUNC
Definition OOVector.h:247
const Vector kZeroVector
Definition OOVector.m:27
const Vector kBasisZVector
Definition OOVector.h:47
const Vector kBasisXVector
Definition OOVector.h:45
OOINLINE Vector vector_multiply_scalar(Vector v, OOScalar s) INLINE_CONST_FUNC
Definition OOVector.h:180
OOMeshFaceCount faceCount
Definition OOMesh.m:363
static float FaceArea(GLuint *vertIndices, Vector *vertices)
Definition OOMesh.m:1571

Referenced by OOMesh(Private)::loadData:scaleFactor:.

Here is the caller graph for this function:

◆ calculateVertexTangentsWithFaceRefs:

- (void) calculateVertexTangentsWithFaceRefs: (VertexFaceRef*) faceRefs
implementation

Provided by category OOMesh(Private).

Definition at line 1634 of file OOMesh.m.

1634 :(VertexFaceRef*)faceRefs
1635{
1637
1638 NSParameterAssert(faceRefs != NULL);
1639
1640 /* This is conceptually broken.
1641 At the moment, it's calculating one tangent per "input" vertex. It should
1642 be calculating one tangent per "real" vertex, where a "real" vertex is
1643 defined as a combination of position, normal, material and texture
1644 coordinates.
1645 Currently, we don't have a format with unique "real" vertices.
1646 This basically means explicit-normal models without explicit tangents
1647 can't usefully be normal mapped.
1648 I don't intend to do anything about this pre-MSNR, although it might be
1649 possible to fix it by moving tangent generation to the same stage as
1650 smooth-grouped normal generation.
1651 -- Ahruman 2010-05-22
1652 */
1653 NSUInteger i, j;
1654 float triangle_area[faceCount];
1655 for (i = 0; i < faceCount; i++) {
1656 triangle_area[i] = FaceAreaCorrect(_faces[i].vertex, _vertices);
1657 }
1658 for (i = 0; i < vertexCount; i++) {
1659 Vector tangent_sum = kZeroVector;
1660
1661 VertexFaceRef* vfr = &faceRefs[i];
1662 NSUInteger fIter, fCount = VFRGetCount(vfr);
1663 for (fIter = 0; fIter < fCount; fIter++) {
1664 j = VFRGetFaceAtIndex(vfr, fIter);
1665
1666 float t = triangle_area[j]; // weight sum by area
1667 tangent_sum = vector_add(tangent_sum, vector_multiply_scalar(_faces[j].tangent, t));
1668 }
1669
1670 tangent_sum = vector_subtract(tangent_sum, vector_multiply_scalar(_normals[i], dot_product(_normals[i], tangent_sum)));
1671 tangent_sum = vector_normal_or_fallback(tangent_sum, kBasisXVector);
1672
1673 _tangents[i] = tangent_sum;
1674 }
1675
1677}
static float FaceAreaCorrect(GLuint *vertIndices, Vector *vertices)
Definition OOMesh.m:1619

Referenced by OOMesh(Private)::loadData:scaleFactor:.

Here is the caller graph for this function:

◆ checkNormalsAndAdjustWinding

- (void) checkNormalsAndAdjustWinding
implementation

Provided by category OOMesh(Private).

Definition at line 1488 of file OOMesh.m.

1489{
1491
1492 Vector calculatedNormal;
1494
1495 NSParameterAssert(_normalMode != kNormalModeExplicit);
1496
1497 for (i = 0; i < faceCount; i++) {
1498 Vector v0, v1, v2, norm;
1499 v0 = _vertices[_faces[i].vertex[0]];
1500 v1 = _vertices[_faces[i].vertex[1]];
1501 v2 = _vertices[_faces[i].vertex[2]];
1502 norm = _faces[i].normal;
1503
1504 calculatedNormal = normal_to_surface(v2, v1, v0);
1505 if (vector_equal(norm, kZeroVector)) {
1506 norm = vector_flip(calculatedNormal);
1507 _faces[i].normal = norm;
1508 }
1509
1510 /* FIXME: for 2.0, either require explicit normals for every model
1511 or change to: if (dot_product(norm, calculatedNormal) < 0.0f)
1512 -- Ahruman 2010-01-23
1513 */
1514 if (norm.x * calculatedNormal.x < 0 || norm.y * calculatedNormal.y < 0 || norm.z * calculatedNormal.z < 0) {
1515 // normal lies in the WRONG direction!
1516 // reverse the winding
1517 int v0 = _faces[i].vertex[0];
1518 _faces[i].vertex[0] = _faces[i].vertex[2];
1519 _faces[i].vertex[2] = v0;
1520
1521 GLfloat f0 = _faces[i].s[0];
1522 _faces[i].s[0] = _faces[i].s[2];
1523 _faces[i].s[2] = f0;
1524
1525 f0 = _faces[i].t[0];
1526 _faces[i].t[0] = _faces[i].t[2];
1527 _faces[i].t[2] = f0;
1528 }
1529 }
1530
1532}
uint32_t OOMeshFaceCount
Definition OOMesh.h:56
@ kNormalModeExplicit
Definition OOMesh.m:76
OOINLINE Vector vector_flip(Vector v) INLINE_CONST_FUNC
Definition OOVector.h:227
OOINLINE Vector normal_to_surface(Vector v1, Vector v2, Vector v3) CONST_FUNC
Definition OOVector.h:309
OOINLINE bool vector_equal(Vector a, Vector b) INLINE_CONST_FUNC
Definition OOVector.h:232
uint8_t _normalMode
Definition OOMesh.h:84
OOScalar x
Definition OOVector.h:32
OOScalar y
Definition OOVector.h:33
OOScalar z
Definition OOVector.h:34

Referenced by OOMesh(Private)::loadData:scaleFactor:.

Here is the caller graph for this function:

◆ copyWithZone:

- (id) copyWithZone: (NSZone*) zone
implementation

Definition at line 345 of file OOMesh.m.

345 :(NSZone*)zone
346{
347 if (zone == [self zone])
348 return [self retain]; // OK because we're immutable seen from the outside
349 else
350 return [self mutableCopyWithZone:zone];
351}

References mutableCopyWithZone:.

Here is the call graph for this function:

◆ dealloc

- (void) dealloc
implementation

Definition at line 294 of file OOMesh.m.

295{
296 unsigned i;
297
301
302 [self deleteDisplayLists];
303
304 for (i = 0; i != kOOMeshMaxMaterials; ++i) {
305 DESTROY(materials[i]);
307 }
308
310
312
318
319#if OOMESH_PROFILE
320 DESTROY(_stopwatch);
321#endif
322
323 [super dealloc];
324}
#define DESTROY(x)
@ kOOMeshMaxMaterials
Definition OOMesh.h:50
void unregisterClient:(id< OOGraphicsResetClient > client)
OOGraphicsResetManager * sharedManager()
NSMutableDictionary * _retainedObjects
Definition OOMesh.h:115
NSDictionary * _shaderMacros
Definition OOMesh.h:120
OOMaterial * materials[kOOMeshMaxMaterials]
Definition OOMesh.m:565
id _shaderBindingTarget
Definition OOMesh.h:121
NSString * materialKeys[kOOMeshMaxMaterials]
Definition OOMesh.h:105
Octree * octree
Definition OOMesh.m:631
NSString * _cacheKey
Definition OOMesh.h:119
NSDictionary * _materialDict
Definition OOMesh.h:117
NSDictionary * _shadersDict
Definition OOMesh.h:118
NSString * baseFileOctreeCacheRef
Definition OOMesh.h:93
NSString * baseFile
Definition OOMesh.h:92

References _cacheKey, _materialDict, _retainedObjects, _shaderBindingTarget, _shaderMacros, _shadersDict, baseFile, baseFileOctreeCacheRef, dealloc, deleteDisplayLists, DESTROY, kOOMeshMaxMaterials, materialKeys, materials, octree, OOGraphicsResetManager::sharedManager, and OOGraphicsResetManager::unregisterClient:.

Referenced by dealloc.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ deleteDisplayLists

- (void) deleteDisplayLists
implementation

Provided by category OOMesh(Private).

Definition at line 913 of file OOMesh.m.

914{
915 if (listsReady) {
917
918 OOGL(glDeleteLists(displayList0, materialCount));
919 listsReady = NO;
920 }
921}
#define OO_ENTER_OPENGL()
#define OOGL(statement)
Definition OOOpenGL.h:262
GLuint displayList0
Definition OOMesh.h:107
uint8_t listsReady
Definition OOMesh.h:86
OOMeshMaterialCount materialCount
Definition OOMesh.h:88

Referenced by dealloc, and OOMesh(Private)::resetGraphicsState.

Here is the caller graph for this function:

◆ descriptionComponents

- (NSString *) descriptionComponents
implementation

Definition at line 340 of file OOMesh.m.

341{
342 return [NSString stringWithFormat:@"\"%@\", %zu vertices, %zu faces, radius: %g m normals: %@", [self modelName], [self vertexCount], [self faceCount], [self collisionRadius], NormalModeDescription(_normalMode)];
343}

References collisionRadius, descriptionComponents, faceCount, modelName, and vertexCount.

Referenced by descriptionComponents.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FaceArea

+ (float) FaceArea (GLuint *) vertIndices
(Vector *) vertices 
implementation

Provided by category OOMesh(Private).

Definition at line 1571 of file OOMesh.m.

1572{
1573 /* Calculate areas using Heron's formula. */
1574 float a2 = distance2(vertices[vertIndices[0]], vertices[vertIndices[1]]);
1575 float b2 = distance2(vertices[vertIndices[1]], vertices[vertIndices[2]]);
1576 float c2 = distance2(vertices[vertIndices[2]], vertices[vertIndices[0]]);
1577 return sqrt((2.0f * (a2 * b2 + b2 * c2 + c2 * a2) - (a2 * a2 + b2 * b2 + c2 * c2)) * 0.0625f);
1578}
OOINLINE OOScalar distance2(Vector v1, Vector v2) INLINE_CONST_FUNC
Definition OOVector.h:275

◆ FaceAreaCorrect

+ (float) FaceAreaCorrect (GLuint *) vertIndices
(Vector *) vertices 
implementation

Provided by category OOMesh(Private).

Definition at line 1619 of file OOMesh.m.

1620{
1621 /* Calculate area of triangle.
1622 The magnitude of the cross product of two vectors is the area of
1623 the parallelogram they span. The area of a triangle is half the
1624 area of a parallelogram sharing two of its sides.
1625 Since we only use the area of the triangle as a weight factor,
1626 constant terms are irrelevant, so we don't bother halving the
1627 value.
1628 */
1629 Vector AB = vector_subtract(vertices[vertIndices[1]], vertices[vertIndices[0]]);
1630 Vector AC = vector_subtract(vertices[vertIndices[2]], vertices[vertIndices[0]]);
1631 return magnitude(true_cross_product(AB, AC));
1632}
OOINLINE OOScalar magnitude(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:242
OOINLINE Vector true_cross_product(Vector first, Vector second) CONST_FUNC
Definition OOVector.h:285

◆ faceCount

- (size_t) faceCount

References faceCount.

◆ findBoundingBoxRelativeToPosition:ri:rj:rk:selfPosition:si:sj:sk:

- (BoundingBox) findBoundingBoxRelativeToPosition: (Vector) opv
ri: (Vector) ri
rj: (Vector) rj
rk: (Vector) rk
selfPosition: (Vector) position
si: (Vector) si
sj: (Vector) sj
sk: (Vector) sk 

Definition at line 664 of file OOMesh.m.

664 :(Vector)opv
665 ri:(Vector)ri
666 rj:(Vector)rj
667 rk:(Vector)rk
668 selfPosition:(Vector)position
669 si:(Vector)si
670 sj:(Vector)sj
671 sk:(Vector)sk
672{
673 BoundingBox result;
674 Vector pv, rv;
675
676 // FIXME: rewrite with matrices
677 Vector rpos = vector_subtract(position, opv); // model origin relative to opv
678
679 rv.x = dot_product(ri, rpos);
680 rv.y = dot_product(rj, rpos);
681 rv.z = dot_product(rk, rpos); // model origin rel to opv in ijk
682
683 if (EXPECT_NOT(vertexCount < 1)) {
684 bounding_box_reset_to_vector(&result, rv);
685 } else {
686 pv.x = rpos.x + si.x * _vertices[0].x + sj.x * _vertices[0].y + sk.x * _vertices[0].z;
687 pv.y = rpos.y + si.y * _vertices[0].x + sj.y * _vertices[0].y + sk.y * _vertices[0].z;
688 pv.z = rpos.z + si.z * _vertices[0].x + sj.z * _vertices[0].y + sk.z * _vertices[0].z; // _vertices[0] position rel to opv
689 rv.x = dot_product(ri, pv);
690 rv.y = dot_product(rj, pv);
691 rv.z = dot_product(rk, pv); // _vertices[0] position rel to opv in ijk
692 bounding_box_reset_to_vector(&result, rv);
693 }
694
696 for (i = 1; i < vertexCount; i++) {
697 pv.x = rpos.x + si.x * _vertices[i].x + sj.x * _vertices[i].y + sk.x * _vertices[i].z;
698 pv.y = rpos.y + si.y * _vertices[i].x + sj.y * _vertices[i].y + sk.y * _vertices[i].z;
699 pv.z = rpos.z + si.z * _vertices[i].x + sj.z * _vertices[i].y + sk.z * _vertices[i].z;
700 rv.x = dot_product(ri, pv);
701 rv.y = dot_product(rj, pv);
702 rv.z = dot_product(rk, pv);
703 bounding_box_add_vector(&result, rv);
704 }
705
706 return result;
707}
#define EXPECT_NOT(x)
float y

References _vertices, bounding_box_add_vector(), bounding_box_reset_to_vector(), dot_product(), EXPECT_NOT, vector_subtract(), vertexCount, Vector::x, Vector::y, and Vector::z.

Referenced by ShipEntity::findBoundingBoxRelativeToPosition:i:j:k:.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ findSubentityBoundingBoxWithPosition:rotMatrix:

- (BoundingBox) findSubentityBoundingBoxWithPosition: (Vector) position
rotMatrix: (OOMatrix) rotMatrix 

Definition at line 709 of file OOMesh.m.

709 :(Vector)position rotMatrix:(OOMatrix)rotMatrix
710{
711 // HACK! Should work out what the various bounding box things do and make it neat and consistent.
712 // FIXME: this is a bottleneck.
713 // Try to fix bottleneck by caching for common case where subentity
714 // pos+rot is constant from frame to frame. - CIM
715
716 if (vector_equal(position, _lastPosition) && OOMatrixEqual(rotMatrix, _lastRotMatrix)) {
717 return _lastBoundingBox;
718 }
719
720 BoundingBox result;
721 Vector v;
722
723 v = vector_add(position, OOVectorMultiplyMatrix(_vertices[0], rotMatrix));
725
727 for (i = 1; i < vertexCount; i++) {
728 v = vector_add(position, OOVectorMultiplyMatrix(_vertices[i], rotMatrix));
729 bounding_box_add_vector(&result, v);
730 }
731
732 _lastBoundingBox = result;
733 _lastPosition = position;
734 _lastRotMatrix = rotMatrix;
735
736 return result;
737}
Vector OOVectorMultiplyMatrix(Vector v, OOMatrix m) CONST_FUNC
Definition OOMatrix.m:121
bool OOMatrixEqual(OOMatrix a, OOMatrix b) CONST_FUNC
Definition OOMatrix.m:91
struct OOMatrix OOMatrix
Vector _lastPosition
Definition OOMesh.h:123
BoundingBox _lastBoundingBox
Definition OOMesh.h:125
OOMatrix _lastRotMatrix
Definition OOMesh.h:124

References _lastBoundingBox, _lastPosition, _lastRotMatrix, _vertices, bounding_box_add_vector(), bounding_box_reset_to_vector(), OOMatrixEqual(), OOVectorMultiplyMatrix(), vector_add(), vector_equal(), and vertexCount.

Referenced by ShipEntity::findSubentityBoundingBox.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ generateFaceTangents

- (void) generateFaceTangents
implementation

Provided by category OOMesh(Private).

Definition at line 1534 of file OOMesh.m.

1535{
1537
1539 for (i = 0; i < faceCount; i++) {
1540 OOMeshFace* face = _faces + i;
1541
1542 /* Generate tangents, i.e. vectors that run in the direction of the s
1543 texture coordinate. Based on code I found in a forum somewhere and
1544 then lost track of. Sorry to whomever I should be crediting.
1545 -- Ahruman 2008-11-23
1546 */
1547 Vector vAB = vector_subtract(_vertices[face->vertex[1]], _vertices[face->vertex[0]]);
1548 Vector vAC = vector_subtract(_vertices[face->vertex[2]], _vertices[face->vertex[0]]);
1549 Vector nA = face->normal;
1550
1551 // projAB = aB - (nA . vAB) * nA
1552 Vector vProjAB = vector_subtract(vAB, vector_multiply_scalar(nA, dot_product(nA, vAB)));
1553 Vector vProjAC = vector_subtract(vAC, vector_multiply_scalar(nA, dot_product(nA, vAC)));
1554
1555 // delta s/t
1556 GLfloat dsAB = face->s[1] - face->s[0];
1557 GLfloat dsAC = face->s[2] - face->s[0];
1558 GLfloat dtAB = face->t[1] - face->t[0];
1559 GLfloat dtAC = face->t[2] - face->t[0];
1560
1561 if (dsAC * dtAB > dsAB * dtAC) {
1563 } else {
1565 }
1566 }
1567
1569}
OOINLINE Vector vector_normal(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:270
Vector tangent
Definition OOMesh.h:66
GLuint vertex[3]
Definition OOMesh.h:63
Vector normal
Definition OOMesh.h:65
GLfloat t[3]
Definition OOMesh.h:68
GLfloat s[3]
Definition OOMesh.h:67

Referenced by OOMesh(Private)::loadData:scaleFactor:.

Here is the caller graph for this function:

◆ getNormal:andTangent:forVertex:inSmoothGroup:

- (void) getNormal: (Vector*) outNormal
andTangent: (Vector*) outTangent
forVertex: (OOMeshVertexCount) v_index
inSmoothGroup: (OOMeshSmoothGroup) smoothGroup 
implementation

Provided by category OOMesh(Private).

Definition at line 1681 of file OOMesh.m.

1681 :(Vector*)outNormal andTangent:(Vector*)outTangent forVertex:(OOMeshVertexCount)v_index inSmoothGroup:(OOMeshSmoothGroup)smoothGroup
1682{
1684
1685 assert(outNormal != NULL && outTangent != NULL);
1686
1687 NSUInteger j;
1688 Vector normal_sum = kZeroVector;
1689 Vector tangent_sum = kZeroVector;
1690 for (j = 0; j < faceCount; j++) {
1691 if (_faces[j].smoothGroup == smoothGroup) {
1692 if ((_faces[j].vertex[0] == v_index) || (_faces[j].vertex[1] == v_index) || (_faces[j].vertex[2] == v_index)) {
1693 float area = FaceArea(_faces[j].vertex, _vertices);
1694 normal_sum = vector_add(normal_sum, vector_multiply_scalar(_faces[j].normal, area));
1695 tangent_sum = vector_add(tangent_sum, vector_multiply_scalar(_faces[j].tangent, area));
1696 }
1697 }
1698 }
1699
1700 *outNormal = vector_normal_or_fallback(normal_sum, kBasisZVector);
1701 *outTangent = vector_normal_or_fallback(tangent_sum, kBasisXVector);
1702
1704}
uint16_t OOMeshSmoothGroup
Definition OOMesh.h:53

Referenced by OOMesh(Private)::setUpVertexArrays.

Here is the caller graph for this function:

◆ hasOpaqueParts

- (BOOL) hasOpaqueParts
implementation

Reimplemented from OODrawable.

Definition at line 575 of file OOMesh.m.

576{
577 return YES;
578}

References hasOpaqueParts.

Referenced by hasOpaqueParts.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ init

- (id) init
implementation

Definition at line 274 of file OOMesh.m.

275{
276 self = [super init];
277 if (self == nil)
278 return nil;
279
280 baseFile = @"No Model";
281 baseFileOctreeCacheRef = @"No Model-0.000";
282 _cacheWriteable = YES;
283#if OO_MULTITEXTURE
284 _textureUnitCount = NSNotFound;
285#endif
286
288 _lastRotMatrix = kZeroMatrix; // not identity
290
291 return self;
292}
const BoundingBox kZeroBoundingBox
Definition OOVector.m:36
const OOMatrix kZeroMatrix
Definition OOMatrix.m:33
return nil
BOOL _cacheWriteable
Definition OOMesh.h:94

References _cacheWriteable, _lastBoundingBox, _lastPosition, _lastRotMatrix, baseFile, baseFileOctreeCacheRef, init, kZeroBoundingBox, kZeroMatrix, kZeroVector, and nil.

Referenced by init.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ initWithName:cacheKey:materialDictionary:shadersDictionary:smooth:shaderMacros:shaderBindingTarget:scaleFactor:cacheWriteable:

- (id) initWithName: (NSString*) name
cacheKey: (NSString*) cacheKey
materialDictionary: (NSDictionary*) materialDict
shadersDictionary: (NSDictionary*) shadersDict
smooth: (BOOL) smooth
shaderMacros: (NSDictionary*) macros
shaderBindingTarget: (id<OOWeakReferenceSupport>) object
scaleFactor: (float) scale
cacheWriteable: (BOOL) cacheWriteable 
implementation

Provided by category OOMesh(Private).

Definition at line 817 of file OOMesh.m.

817 :(NSString*)name
818 cacheKey:(NSString*)cacheKey
819 materialDictionary:(NSDictionary*)materialDict
820 shadersDictionary:(NSDictionary*)shadersDict
821 smooth:(BOOL)smooth
822 shaderMacros:(NSDictionary*)macros
823 shaderBindingTarget:(id<OOWeakReferenceSupport>)target
824 scaleFactor:(float)scale
825 cacheWriteable:(BOOL)cacheWriteable
826{
828
829 self = [super init];
830 if (self == nil)
831 return nil;
832
833 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
835 _cacheWriteable = cacheWriteable;
836
837#if OOMESH_PROFILE
838 _stopwatch = [[OOProfilingStopwatch alloc] init];
839#endif
840
841 if ([self loadData:name scaleFactor:scale]) {
842 [self calculateBoundingVolumes];
843 PROFILE(@"finished calculateBoundingVolumes (again\?\?)");
844
845 baseFile = [name copy];
846 baseFileOctreeCacheRef = [[NSString stringWithFormat:@"%@-%.3f", baseFile, scale] copy];
847
848 /* New in r3033: save the material-defining parameters here so we
849 can rebind the materials at any time.
850 -- Ahruman 2010-02-17
851 */
852 _materialDict = [materialDict copy];
853 _shadersDict = [shadersDict copy];
854 _cacheKey = [cacheKey copy];
855 _shaderMacros = [macros copy];
856 _shaderBindingTarget = [target weakRetain];
857
858 [self rebindMaterials];
859 PROFILE(@"finished material setup");
860
862 } else {
863 [self release];
864 self = nil;
865 }
866#if OOMESH_PROFILE
867 DESTROY(_stopwatch);
868#endif
869#if OO_MULTITEXTURE
870 if (EXPECT(self != nil)) {
871 _textureUnitCount = NSNotFound;
872 }
873#endif
874
875 [pool release];
876 return self;
877
879}
#define EXPECT(x)
#define OOJS_PROFILE_EXIT
#define PROFILE(tag)
Definition OOMesh.m:94
@ kNormalModeSmooth
Definition OOMesh.m:75
@ kNormalModePerFace
Definition OOMesh.m:74
void registerClient:(id< OOGraphicsResetClient > client)

◆ loadData:scaleFactor:

- (BOOL) loadData: (NSString*) filename
scaleFactor: (float) scale 
implementation

Provided by category OOMesh(Private).

Definition at line 1080 of file OOMesh.m.

1080 :(NSString*)filename scaleFactor:(float)scale
1081{
1083
1084 NSScanner* scanner;
1085 NSDictionary* cacheData = nil;
1086 BOOL failFlag = NO;
1087 NSString* failString = @"***** ";
1088 unsigned i, j;
1089 NSMutableDictionary* texFileName2Idx = nil;
1090 NSString* cacheKey = nil;
1091 BOOL using_preloaded = NO;
1092
1093 cacheKey = [NSString stringWithFormat:@"%@:%u:%.3f", filename, _normalMode, scale];
1094 cacheData = [OOCacheManager meshDataForName:cacheKey];
1095 if (cacheData != nil) {
1096 if ([self setModelFromModelData:cacheData name:filename]) {
1097 using_preloaded = YES;
1098 PROFILE(@"loaded from cache");
1099 OOLog(@"mesh.load.cached", @"Retrieved mesh \"%@\" from cache.", filename);
1100 }
1101 }
1102
1103 if (!using_preloaded) {
1104 OOLog(@"mesh.load.uncached", @"Mesh \"%@\" is not in cache, loading.", cacheKey);
1105
1106 NSCharacterSet* whitespaceCharSet = [NSCharacterSet whitespaceCharacterSet];
1107 NSCharacterSet* whitespaceAndNewlineCharSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
1108#if OOLITE_MAC_OS_X
1109 NSCharacterSet* newlineCharSet = [NSCharacterSet newlineCharacterSet];
1110#else
1111 static NSCharacterSet* newlineCharSet = nil;
1112 if (newlineCharSet == nil) {
1113 NSMutableCharacterSet* temp = [[whitespaceAndNewlineCharSet mutableCopy] autorelease];
1114 [temp formIntersectionWithCharacterSet:[whitespaceCharSet invertedSet]];
1115 newlineCharSet = [temp copy];
1116 }
1117#endif
1118
1119 texFileName2Idx = [NSMutableDictionary dictionary];
1120
1121 {
1122 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
1123 NSString* data = [ResourceManager stringFromFilesNamed:filename inFolder:@"Models" cache:NO];
1124 if (data == nil) {
1125 // Model not found
1126 OOLog(kOOLogMeshDataNotFound, @"***** ERROR: could not find %@", filename);
1127 OOStandardsError(@"Model file not found");
1128 return NO;
1129 }
1130
1131 // strip out comments and commas between values
1132 NSMutableArray* lines = [NSMutableArray arrayWithArray:[data componentsSeparatedByString:@"\n"]];
1133 for (i = 0; i < [lines count]; i++) {
1134 NSString* line = [lines objectAtIndex:i];
1135 NSArray* parts;
1136 //
1137 // comments
1138 //
1139 parts = [line componentsSeparatedByString:@"#"];
1140 line = [parts objectAtIndex:0];
1141 parts = [line componentsSeparatedByString:@"//"];
1142 line = [parts objectAtIndex:0];
1143 //
1144 // commas
1145 //
1146 line = [[line componentsSeparatedByString:@","] componentsJoinedByString:@" "];
1147 //
1148 [lines replaceObjectAtIndex:i withObject:line];
1149 }
1150
1151 data = [lines componentsJoinedByString:@"\n"];
1152 scanner = [NSScanner scannerWithString:data];
1153
1154 [scanner retain];
1155 [pool release];
1156 [scanner autorelease];
1157 }
1158
1159 PROFILE(@"finished preprocessing");
1160
1161 // get number of vertices
1162 //
1163 [scanner setScanLocation:0]; // reset
1164 if ([scanner scanString:@"NVERTS" intoString:NULL]) {
1165 int n_v;
1166 if ([scanner scanInt:&n_v])
1167 vertexCount = n_v;
1168 else {
1169 failFlag = YES;
1170 failString = [NSString stringWithFormat:@"%@Failed to read value of NVERTS\n", failString];
1171 }
1172 } else {
1173 failFlag = YES;
1174 failString = [NSString stringWithFormat:@"%@Failed to read NVERTS\n", failString];
1175 }
1176
1177 if (![self allocateVertexBuffersWithCount:vertexCount]) {
1178 OOLog(kOOLogAllocationFailure, @"***** ERROR: failed to allocate memory for model %@ (%u vertices).", filename, vertexCount);
1179 return NO;
1180 }
1181
1182 // get number of faces
1183 if ([scanner scanString:@"NFACES" intoString:NULL]) {
1184 int n_f;
1185 if ([scanner scanInt:&n_f]) {
1186 faceCount = n_f;
1187 } else {
1188 failFlag = YES;
1189 failString = [NSString stringWithFormat:@"%@Failed to read value of NFACES\n", failString];
1190 }
1191 } else {
1192 failFlag = YES;
1193 failString = [NSString stringWithFormat:@"%@Failed to read NFACES\n", failString];
1194 }
1195
1196 // Allocate face->vertex table.
1197 size_t faceRefSize = sizeof(VertexFaceRef) * vertexCount;
1198 VertexFaceRef* faceRefs = calloc(1, faceRefSize);
1199 if (faceRefs != NULL) {
1200 // use an NSData to effectively autorelease it.
1201 NSData* faceRefHolder = [NSData dataWithBytesNoCopy:faceRefs length:faceRefSize freeWhenDone:YES];
1202 if (faceRefHolder == nil) {
1203 free(faceRefs);
1204 faceRefs = NULL;
1205 }
1206 }
1207
1208 if (faceRefs == NULL || ![self allocateFaceBuffersWithCount:faceCount]) {
1209 OOLog(kOOLogAllocationFailure, @"***** ERROR: failed to allocate memory for model %@ (%u vertices, %u faces).", filename, vertexCount, faceCount);
1210 return NO;
1211 }
1212
1213 // get vertex data
1214 if ([scanner scanString:@"VERTEX" intoString:NULL]) {
1215 for (j = 0; j < vertexCount; j++) {
1216 float x, y, z;
1217 if (!failFlag) {
1218 if (![scanner scanFloat:&x])
1219 failFlag = YES;
1220 if (![scanner scanFloat:&y])
1221 failFlag = YES;
1222 if (![scanner scanFloat:&z])
1223 failFlag = YES;
1224 if (!failFlag) {
1225 _vertices[j] = make_vector(x * scale, y * scale, z * scale);
1226 } else {
1227 failString = [NSString stringWithFormat:@"%@Failed to read a value for vertex[%d] in %@\n", failString, j, @"VERTEX"];
1228 }
1229 }
1230 }
1231 } else {
1232 failFlag = YES;
1233 failString = [NSString stringWithFormat:@"%@Failed to find VERTEX data\n", failString];
1234 }
1235
1236 // get face data
1237 if ([scanner scanString:@"FACES" intoString:NULL]) {
1238 for (j = 0; j < faceCount; j++) {
1239 int r, g, b;
1240 float nx, ny, nz;
1241 int n_v;
1242 if (!failFlag) {
1243 // colors
1244 if (![scanner scanInt:&r])
1245 failFlag = YES;
1246 if (![scanner scanInt:&g])
1247 failFlag = YES;
1248 if (![scanner scanInt:&b])
1249 failFlag = YES;
1250 if (!failFlag) {
1251 _faces[j].smoothGroup = r;
1252 } else {
1253 failString = [NSString stringWithFormat:@"%@Failed to read a color for face[%d] in FACES\n", failString, j];
1254 }
1255
1256 // normal
1257 if (![scanner scanFloat:&nx])
1258 failFlag = YES;
1259 if (![scanner scanFloat:&ny])
1260 failFlag = YES;
1261 if (![scanner scanFloat:&nz])
1262 failFlag = YES;
1263 if (!failFlag) {
1264 _faces[j].normal = vector_normal(make_vector(nx, ny, nz));
1265 } else {
1266 failString = [NSString stringWithFormat:@"%@Failed to read a normal for face[%d] in FACES\n", failString, j];
1267 }
1268
1269 // vertices
1270 if ([scanner scanInt:&n_v]) {
1271 if (n_v < 3) {
1272 failFlag = YES;
1273 failString = [NSString stringWithFormat:@"%@Face[%u] has fewer than three vertices.\n", failString, j];
1274 } else if (n_v > 3) {
1275 OOLogWARN(@"mesh.load.warning.nonTriangular", @"Face[%u] of %@ has %u vertices specified. Only the first three will be used.", j, baseFile, n_v);
1276 n_v = 3;
1277 }
1278 } else {
1279 failFlag = YES;
1280 failString = [NSString stringWithFormat:@"%@Failed to read number of vertices for face[%d] in FACES\n", failString, j];
1281 }
1282
1283 if (!failFlag) {
1284 int vi;
1285 for (i = 0; (int)i < n_v; i++) {
1286 if ([scanner scanInt:&vi]) {
1287 _faces[j].vertex[i] = vi;
1288 if (faceRefs != NULL)
1289 VFRAddFace(&faceRefs[vi], j);
1290 } else {
1291 failFlag = YES;
1292 failString = [NSString stringWithFormat:@"%@Failed to read vertex[%d] for face[%d] in FACES\n", failString, i, j];
1293 }
1294 }
1295 }
1296 }
1297 }
1298 } else {
1299 failFlag = YES;
1300 failString = [NSString stringWithFormat:@"%@Failed to find FACES data\n", failString];
1301 }
1302
1303 // Get textures data.
1304 if ([scanner scanString:@"TEXTURES" intoString:NULL]) {
1305 for (j = 0; j < faceCount; j++) {
1306 NSString* materialKey;
1307 float max_x, max_y;
1308 float s, t;
1309 if (!failFlag) {
1310 // materialKey
1311 //
1312 [scanner scanCharactersFromSet:whitespaceAndNewlineCharSet intoString:NULL];
1313 if (![scanner scanUpToCharactersFromSet:whitespaceCharSet intoString:&materialKey]) {
1314 failFlag = YES;
1315 failString = [NSString stringWithFormat:@"%@Failed to read texture filename for face[%d] in TEXTURES\n", failString, j];
1316 } else {
1317 NSNumber* index = [texFileName2Idx objectForKey:materialKey];
1318 if (index != nil) {
1319 _faces[j].materialIndex = [index unsignedIntValue];
1320 } else {
1322 OOLog(kOOLogMeshTooManyMaterials, @"***** ERROR: model %@ has too many materials (maximum is %d)", filename, kOOMeshMaxMaterials);
1323 return NO;
1324 }
1325 _faces[j].materialIndex = materialCount;
1326 materialKeys[materialCount] = [materialKey retain];
1327 index = [NSNumber numberWithUnsignedInt:materialCount];
1328 [texFileName2Idx setObject:index forKey:materialKey];
1329 ++materialCount;
1330 }
1331 }
1332
1333 // texture size
1334 //
1335 if (!failFlag) {
1336 if (![scanner scanFloat:&max_x])
1337 failFlag = YES;
1338 if (![scanner scanFloat:&max_y])
1339 failFlag = YES;
1340 if (failFlag)
1341 failString = [NSString stringWithFormat:@"%@Failed to read texture size for max_x and max_y in face[%d] in TEXTURES\n", failString, j];
1342 }
1343
1344 // vertices
1345 //
1346 if (!failFlag) {
1347 for (i = 0; i < 3; i++) {
1348 if (![scanner scanFloat:&s])
1349 failFlag = YES;
1350 if (![scanner scanFloat:&t])
1351 failFlag = YES;
1352 if (!failFlag) {
1353 _faces[j].s[i] = s / max_x;
1354 _faces[j].t[i] = t / max_y;
1355 } else
1356 failString = [NSString stringWithFormat:@"%@Failed to read s t coordinates for vertex[%d] in face[%d] in TEXTURES\n", failString, i, j];
1357 }
1358 }
1359 }
1360 }
1361 } else {
1362 failFlag = YES;
1363 failString = [failString stringByAppendingString:@"Failed to find TEXTURES data (will use placeholder material)\n"];
1364 materialKeys[0] = @"_oo_placeholder_material";
1365 materialCount = 1;
1366
1367 for (j = 0; j < faceCount; j++) {
1368 _faces[j].materialIndex = 0;
1369 }
1370 }
1371
1372 if ([scanner scanString:@"NAMES" intoString:NULL]) {
1373 unsigned int count;
1374 if (![scanner scanInt:(int*)&count]) {
1375 failFlag = YES;
1376 failString = [failString stringByAppendingString:@"Expected count after NAMES\n"];
1377 } else {
1378 for (j = 0; j < count; j++) {
1379 NSString* name = nil;
1380 [scanner scanCharactersFromSet:whitespaceAndNewlineCharSet intoString:NULL];
1381 if (![scanner scanUpToCharactersFromSet:newlineCharSet intoString:&name]) {
1382 failFlag = YES;
1383 failString = [failString stringByAppendingString:@"Expected file name\n"];
1384 } else {
1385 [self renameTexturesFrom:[NSString stringWithFormat:@"%u", j] to:name];
1386 }
1387 }
1388 }
1389 }
1390
1391 BOOL explicitTangents = NO;
1392
1393 // Get explicit normals.
1394 if ([scanner scanString:@"NORMALS" intoString:NULL]) {
1396 if (![self allocateNormalBuffersWithCount:vertexCount]) {
1397 OOLog(kOOLogAllocationFailure, @"***** ERROR: failed to allocate memory for model %@ (%u vertices).", filename, vertexCount);
1398 return NO;
1399 }
1400
1401 for (j = 0; j < vertexCount; j++) {
1402 float x, y, z;
1403 if (!failFlag) {
1404 if (![scanner scanFloat:&x])
1405 failFlag = YES;
1406 if (![scanner scanFloat:&y])
1407 failFlag = YES;
1408 if (![scanner scanFloat:&z])
1409 failFlag = YES;
1410 if (!failFlag) {
1412 } else {
1413 failString = [NSString stringWithFormat:@"%@Failed to read a value for vertex[%d] in %@\n", failString, j, @"NORMALS"];
1414 }
1415 }
1416 }
1417
1418 // Get explicit tangents (only together with vertices).
1419 if ([scanner scanString:@"TANGENTS" intoString:NULL]) {
1420 for (j = 0; j < vertexCount; j++) {
1421 float x, y, z;
1422 if (!failFlag) {
1423 if (![scanner scanFloat:&x])
1424 failFlag = YES;
1425 if (![scanner scanFloat:&y])
1426 failFlag = YES;
1427 if (![scanner scanFloat:&z])
1428 failFlag = YES;
1429 if (!failFlag) {
1431 } else {
1432 failString = [NSString stringWithFormat:@"%@Failed to read a value for vertex[%d] in %@\n", failString, j, @"TANGENTS"];
1433 }
1434 }
1435 }
1436 }
1437 }
1438
1439 PROFILE(@"finished parsing");
1440
1442 [self checkNormalsAndAdjustWinding];
1443 PROFILE(@"finished checkNormalsAndAdjustWinding");
1444 }
1445 if (!explicitTangents) {
1446 [self generateFaceTangents];
1447 PROFILE(@"finished generateFaceTangents");
1448 }
1449
1450 // check for smooth shading and recalculate normals
1452 if (![self allocateNormalBuffersWithCount:vertexCount]) {
1453 OOLog(kOOLogAllocationFailure, @"***** ERROR: failed to allocate memory for model %@ (%u vertices).", filename, vertexCount);
1454 return NO;
1455 }
1456 [self calculateVertexNormalsAndTangentsWithFaceRefs:faceRefs];
1457 PROFILE(@"finished calculateVertexNormalsAndTangents");
1458
1459 } else if (IsPerVertexNormalMode(_normalMode) && !explicitTangents) {
1460 [self calculateVertexTangentsWithFaceRefs:faceRefs];
1461 PROFILE(@"finished calculateVertexTangents");
1462 }
1463
1464 // save the resulting data for possible reuse
1465 if (EXPECT(_cacheWriteable)) {
1466 [OOCacheManager setMeshData:[self modelData] forName:cacheKey];
1467 PROFILE(@"saved to cache");
1468 }
1469
1470 if (failFlag) {
1471 OOLog(@"mesh.error", @"%@ ..... from %@ %@", failString, filename, (using_preloaded) ? @"(from preloaded data)" : @"(from file)");
1472 }
1473 }
1474
1475 [self calculateBoundingVolumes];
1476 PROFILE(@"finished calculateBoundingVolumes");
1477
1478 // set up vertex arrays for drawing
1479 if (![self setUpVertexArrays])
1480 return NO;
1481 PROFILE(@"finished setUpVertexArrays");
1482
1483 return YES;
1484
1486}
void OOStandardsError(NSString *message)
#define OOLogWARN(class, format,...)
Definition OOLogging.h:126
#define OOLog(class, format,...)
Definition OOLogging.h:84
NSString *const kOOLogAllocationFailure
Definition OOLogging.m:598
static void VFRAddFace(VertexFaceRef *vfr, NSUInteger index)
static BOOL IsLegacyNormalMode(OOMeshNormalMode mode)
Definition OOMesh.m:180
static NSString *const kOOLogMeshTooManyMaterials
Definition OOMesh.m:80
static NSString *const kOOLogMeshDataNotFound
Definition OOMesh.m:79
static BOOL IsPerVertexNormalMode(OOMeshNormalMode mode)
Definition OOMesh.m:201
OOINLINE Vector make_vector(OOScalar vx, OOScalar vy, OOScalar vz) INLINE_CONST_FUNC
Definition OOVector.h:149
void setMeshData:forName:(NSDictionary *inData,[forName] NSString *inShipName)
Definition OOMesh.m:2011
NSDictionary * meshDataForName:(NSString *inShipName)
Definition OOMesh.m:2006
BOOL setUpVertexArrays()
Definition OOMesh.m:1706
NSString * stringFromFilesNamed:inFolder:cache:(NSString *fileName,[inFolder] NSString *folderName,[cache] BOOL useCache)
const char * filename
Definition ioapi.h:125
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque

◆ materials

- (NSDictionary *) materials

References materials, and shaders.

Here is the call graph for this function:

◆ meshRescaledBy:

- (OOMesh *) meshRescaledBy: (GLfloat) scaleFactor

Definition at line 739 of file OOMesh.m.

739 :(GLfloat)scaleFactor
740{
741 OOMesh* result = [self mutableCopy];
742 [result rescaleByFactor:scaleFactor];
743 return [result autorelease];
744}
void rescaleByFactor:(GLfloat factor)
Definition OOMesh.m:1827

Referenced by OOVisualEffectEntity::rescaleBy:.

Here is the caller graph for this function:

◆ meshWithName:cacheKey:materialDictionary:shadersDictionary:smooth:shaderMacros:shaderBindingTarget:

+ (instancetype) meshWithName: (NSString*) name
cacheKey: (NSString*) cacheKey
materialDictionary: (NSDictionary*) materialDict
shadersDictionary: (NSDictionary*) shadersDict
smooth: (BOOL) smooth
shaderMacros: (NSDictionary*) macros
shaderBindingTarget: (id<OOWeakReferenceSupport>) object 

Definition at line 223 of file OOMesh.m.

223 :(NSString*)name
224 cacheKey:(NSString*)cacheKey
225 materialDictionary:(NSDictionary*)materialDict
226 shadersDictionary:(NSDictionary*)shadersDict
227 smooth:(BOOL)smooth
228 shaderMacros:(NSDictionary*)macros
229 shaderBindingTarget:(id<OOWeakReferenceSupport>)object
230{
231 return [[[self alloc] initWithName:name
232 cacheKey:cacheKey
233 materialDictionary:materialDict
234 shadersDictionary:shadersDict
235 smooth:smooth
236 shaderMacros:macros
237 shaderBindingTarget:object
238 scaleFactor:1.0f
239 cacheWriteable:YES] autorelease];
240}

Referenced by OOVisualEffectEntity::setUpVisualEffectFromDictionary:, ShipSetMaterialsInternal(), ShipSetMaterialsInternal(), VisualEffectSetMaterialsInternal(), and VisualEffectSetMaterialsInternal().

Here is the caller graph for this function:

◆ meshWithName:cacheKey:materialDictionary:shadersDictionary:smooth:shaderMacros:shaderBindingTarget:scaleFactor:cacheWriteable:

+ (instancetype) meshWithName: (NSString*) name
cacheKey: (NSString*) cacheKey
materialDictionary: (NSDictionary*) materialDict
shadersDictionary: (NSDictionary*) shadersDict
smooth: (BOOL) smooth
shaderMacros: (NSDictionary*) macros
shaderBindingTarget: (id<OOWeakReferenceSupport>) object
scaleFactor: (float) factor
cacheWriteable: (BOOL) cacheWriteable 

Definition at line 242 of file OOMesh.m.

242 :(NSString*)name
243 cacheKey:(NSString*)cacheKey
244 materialDictionary:(NSDictionary*)materialDict
245 shadersDictionary:(NSDictionary*)shadersDict
246 smooth:(BOOL)smooth
247 shaderMacros:(NSDictionary*)macros
248 shaderBindingTarget:(id<OOWeakReferenceSupport>)object
249 scaleFactor:(float)scale
250 cacheWriteable:(BOOL)cacheWriteable
251{
252 return [[[self alloc] initWithName:name
253 cacheKey:cacheKey
254 materialDictionary:materialDict
255 shadersDictionary:shadersDict
256 smooth:smooth
257 shaderMacros:macros
258 shaderBindingTarget:object
259 scaleFactor:scale
260 cacheWriteable:cacheWriteable] autorelease];
261}

Referenced by ShipEntity(Private)::rescaleBy:writeToCache:.

Here is the caller graph for this function:

◆ modelData

- (NSDictionary *) modelData
implementation

Provided by category OOMesh(Private).

Definition at line 930 of file OOMesh.m.

931{
933
934 NSNumber *vertCnt = nil,
935 *faceCnt = nil;
936 NSData *vertData = nil,
937 *normData = nil,
938 *tanData = nil,
939 *faceData = nil;
940 NSArray* mtlKeys = nil;
941 NSNumber* normMode = nil;
942
943 BOOL includeNormals = IsPerVertexNormalMode(_normalMode);
944
945 // Prepare cache data elements.
946 vertCnt = [NSNumber numberWithUnsignedInt:vertexCount];
947 faceCnt = [NSNumber numberWithUnsignedInt:faceCount];
948
949 vertData = [_retainedObjects objectForKey:@"vertices"];
950 faceData = [_retainedObjects objectForKey:@"faces"];
951 if (includeNormals) {
952 normData = [_retainedObjects objectForKey:@"normals"];
953 tanData = [_retainedObjects objectForKey:@"tangents"];
954 }
955
956 if (materialCount != 0) {
957 mtlKeys = [NSArray arrayWithObjects:materialKeys count:materialCount];
958 } else {
959 mtlKeys = [NSArray array];
960 }
961 normMode = [NSNumber numberWithUnsignedChar:_normalMode];
962
963 // Ensure we have all the required data elements.
964 if (vertCnt == nil || faceCnt == nil || vertData == nil || faceData == nil || mtlKeys == nil || normMode == nil) {
965 return nil;
966 }
967
968 if (includeNormals) {
969 if (normData == nil || tanData == nil)
970 return nil;
971 }
972
973 // All OK; stick 'em in a dictionary.
974 return [NSDictionary dictionaryWithObjectsAndKeys:
975 vertCnt, @"vertex count",
976 vertData, @"vertex data",
977 faceCnt, @"face count",
978 faceData, @"face data",
979 mtlKeys, @"material keys",
980 normMode, @"normal mode",
981 /* NOTE: order matters. Since normData and tanData
982 are last, if they're nil the dictionary will be
983 built without them, which is desired behaviour.
984 */
985 normData, @"normal data",
986 tanData, @"tangent data",
987 nil];
988
990}

Referenced by OOMesh(Private)::loadData:scaleFactor:.

Here is the caller graph for this function:

◆ modelName

- (NSString *) modelName

Definition at line 353 of file OOMesh.m.

354{
355 return baseFile;
356}

References baseFile, and modelName.

Referenced by descriptionComponents, modelName, and PlayerEntity::setUpTrumbles.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ mutableCopyWithZone:

- (id) mutableCopyWithZone: (NSZone*) zone
implementation

Provided by category OOMesh(Private).

Definition at line 881 of file OOMesh.m.

881 :(NSZone*)zone
882{
883 OOMesh* result = nil;
885
886 result = (OOMesh*)NSCopyObject(self, 0, zone);
887
888 if (result != nil) {
889 [result->baseFile retain];
890 [result->baseFileOctreeCacheRef retain];
891 [result->octree retain];
892 [result->_retainedObjects retain];
893 [result->_materialDict retain];
894 [result->_shadersDict retain];
895 [result->_cacheKey retain];
896 [result->_shaderMacros retain];
897 [result->_shaderBindingTarget retain];
898
899 for (i = 0; i != kOOMeshMaxMaterials; ++i) {
900 [result->materialKeys[i] retain];
901 [result->materials[i] retain];
902 }
903
904 // Reset unsharable GL state
905 result->listsReady = NO;
906
908 }
909
910 return result;
911}
uint8_t OOMeshMaterialCount
Definition OOMesh.h:54

Referenced by copyWithZone:.

Here is the caller graph for this function:

◆ NormalModeDescription

+ (NSString *) NormalModeDescription (OOMeshNormalMode) mode
implementation

Definition at line 326 of file OOMesh.m.

327{
328 switch (mode) {
330 return @"per-face";
332 return @"smooth";
334 return @"explicit";
335 }
336
337 return @"unknown";
338}
const char int mode
Definition ioapi.h:125

References kNormalModeExplicit, kNormalModePerFace, and kNormalModeSmooth.

◆ octree

- (Octree *) octree

References octree.

◆ octreeDepth

- (unsigned) octreeDepth
implementation

Definition at line 591 of file OOMesh.m.

592{
593 float threshold = kOctreeSizeThreshold;
594 unsigned result = kBaseOctreeDepth;
595 GLfloat xs, ys, zs, t, size;
596
598 // Shuffle dimensions around so zs is smallest
599 if (xs < zs) {
600 t = zs;
601 zs = xs;
602 xs = t;
603 }
604 if (ys < zs) {
605 t = zs;
606 zs = ys;
607 ys = t;
608 }
609 size = (xs + ys) / 2.0f; // Use average of two largest
610
612 result = kSmallOctreeDepth;
613 else
614 while (result < kMaxOctreeDepth) {
615 if (size < threshold)
616 break;
617 threshold *= 2.0f;
618 result++;
619 }
620
621 OOLog(@"mesh.load.octree.size", @"Selected octree depth %u for size %g for %@", result, size, baseFile);
622 return result;
623}
OOINLINE void bounding_box_get_dimensions(BoundingBox bb, GLfloat *xSize, GLfloat *ySize, GLfloat *zSize) ALWAYS_INLINE_FUNC
@ kBaseOctreeDepth
Definition OOMesh.m:66
@ kOctreeSmallSizeThreshold
Definition OOMesh.m:70
@ kSmallOctreeDepth
Definition OOMesh.m:68
@ kOctreeSizeThreshold
Definition OOMesh.m:69
@ kMaxOctreeDepth
Definition Octree.h:82

References baseFile, bounding_box_get_dimensions(), boundingBox, kBaseOctreeDepth, kMaxOctreeDepth, kOctreeSizeThreshold, kOctreeSmallSizeThreshold, kSmallOctreeDepth, octreeDepth, and OOLog.

Referenced by octreeDepth.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ placeholderMaterial

+ (OOMaterial *) placeholderMaterial

Definition at line 263 of file OOMesh.m.

264{
265 static OOBasicMaterial* placeholderMaterial = nil;
266
267 if (placeholderMaterial == nil) {
268 placeholderMaterial = [[OOBasicMaterial alloc] initWithName:@"/placeholder/" configuration:[[ResourceManager materialDefaults] oo_dictionaryForKey:@"no-textures-material"]];
269 }
270
271 return placeholderMaterial;
272}
OOMaterial * placeholderMaterial()
Definition OOMesh.m:263
NSDictionary * materialDefaults()

References ResourceManager::materialDefaults, nil, and placeholderMaterial.

Referenced by placeholderMaterial, and rebindMaterials.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ rebindMaterials

- (void) rebindMaterials

Definition at line 530 of file OOMesh.m.

531{
533 OOMaterial* material = nil;
534
535 if (materialCount != 0) {
536 for (i = 0; i != materialCount; ++i) {
537 OOMaterial* oldMaterial = materials[i];
538
539 if (![materialKeys[i] isEqualToString:@"_oo_placeholder_material"]) {
540 material = [OOMaterial materialWithName:materialKeys[i]
541 cacheKey:_cacheKey
542 materialDictionary:_materialDict
543 shadersDictionary:_shadersDict
544 macros:_shaderMacros
545 bindingTarget:[_shaderBindingTarget weakRefUnderlyingObject] // Windows DEP fix.
546 forSmoothedMesh:IsPerVertexNormalMode(_normalMode)];
547 } else {
548 material = nil;
549 }
550
551 if (material != nil) {
552 materials[i] = [material retain];
553 } else {
554 materials[i] = [[OOMesh placeholderMaterial] retain];
555 }
556
557 /* Release is deferred to here to ensure we don't end up releasing
558 a texture that's not in the recent-cache and then reloading it.
559 */
560 [oldMaterial release];
561 }
562 }
563}
OOMaterial * materialWithName:cacheKey:materialDictionary:shadersDictionary:macros:bindingTarget:forSmoothedMesh:(NSString *name,[cacheKey] NSString *cacheKey,[materialDictionary] NSDictionary *materialDict,[shadersDictionary] NSDictionary *shadersDict,[macros] NSDictionary *macros,[bindingTarget] id< OOWeakReferenceSupport > object,[forSmoothedMesh] BOOL smooth)

References materialCount, materialKeys, materials, OOMaterial::materialWithName:cacheKey:materialDictionary:shadersDictionary:macros:bindingTarget:forSmoothedMesh:, nil, placeholderMaterial, and rebindMaterials.

Referenced by OOMesh(Private)::initWithName:cacheKey:materialDictionary:shadersDictionary:smooth:shaderMacros:shaderBindingTarget:scaleFactor:cacheWriteable:, rebindMaterials, OOMesh(Private)::resetGraphicsState, and ShipEntity::setEntityPersonalityInt:.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ renameTexturesFrom:to:

- (void) renameTexturesFrom: (NSString*) from
to: (NSString*) to 
implementation

Provided by category OOMesh(Private).

Definition at line 1986 of file OOMesh.m.

1986 :(NSString*)from to:(NSString*)to
1987{
1988 /* IMPORTANT: this has to be called before setUpMaterials..., so it can
1989 only be used during loading.
1990 */
1992 for (i = 0; i != materialCount; i++) {
1993 if ([materialKeys[i] isEqualToString:from]) {
1994 [materialKeys[i] release];
1995 materialKeys[i] = [to copy];
1996 }
1997 }
1998}

Referenced by OOMesh(Private)::loadData:scaleFactor:.

Here is the caller graph for this function:

◆ renderOpaqueParts

- (void) renderOpaqueParts
implementation

Reimplemented from OODrawable.

Definition at line 368 of file OOMesh.m.

369{
371
372 BOOL meshBelongsToVisualEffect = [_shaderBindingTarget isVisualEffect];
373
375
376 OOGL(glVertexPointer(3, GL_FLOAT, 0, _displayLists.vertexArray));
377 OOGL(glNormalPointer(GL_FLOAT, 0, _displayLists.normalArray));
378
379 // for visual effects enable blending. This will allow use of alpha
380 // channel in shaders - note, this is a bit of cheating the system,
381 // which expects blending to be disabled at this point
382 if (meshBelongsToVisualEffect) {
383 OOGL(glEnable(GL_BLEND));
384 OOGL(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
385 }
386
387#if OO_SHADERS
388 if ([[OOOpenGLExtensionManager sharedManager] shadersSupported]) {
389 OOGL(glEnableVertexAttribArrayARB(kTangentAttributeIndex));
390 OOGL(glVertexAttribPointerARB(kTangentAttributeIndex, 3, GL_FLOAT, GL_FALSE, 0, _displayLists.tangentArray));
391 }
392#endif
393
394 BOOL usingNormalsAsTexCoords = NO;
396
397 /* FIXME: really, really horrible hack to set up texture coordinates for
398 each texture unit. Very messy and still fails to handle some possibly-
399 basic stuff, like switching usingNormalsAsTexCoords per texture unit.
400 The right way to do this is probably to move attribute setup into the
401 material model.
402 -- Ahruman 2010-04-12
403 */
404#if OO_MULTITEXTURE
405 if (_textureUnitCount == NSNotFound) {
406 _textureUnitCount = 0;
407 for (ti = 0; ti < materialCount; ti++) {
408 NSUInteger count = [materials[ti] countOfTextureUnitsWithBaseCoordinates];
409 if (_textureUnitCount < count)
410 _textureUnitCount = count;
411 }
412 }
413
414 NSUInteger unit;
415 if (_textureUnitCount <= 1) {
416 OOGL(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
417 } else {
418 /* It should not be possible to have multiple texture units if
419 texture combiners are not available.
420 */
421 NSAssert2([[OOOpenGLExtensionManager sharedManager] textureCombinersSupported], @"Mesh %@ uses %zu texture units, but multitexturing is not available.", [self shortDescription], _textureUnitCount);
422
423 for (unit = 0; unit < _textureUnitCount; unit++) {
424 OOGL(glClientActiveTextureARB(GL_TEXTURE0_ARB + unit));
425 OOGL(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
426 }
427 }
428#else
429 OOGL(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
430#endif
431
432 @try {
433 if (!listsReady) {
434 OOGL(displayList0 = glGenLists(materialCount));
435
436 // Ensure all textures are loaded
437 for (ti = 0; ti < materialCount; ti++) {
438 [materials[ti] ensureFinishedLoading];
439 }
440 }
441
442 for (ti = 0; ti < materialCount; ti++) {
443 BOOL wantsNormalsAsTextureCoordinates = [materials[ti] wantsNormalsAsTextureCoordinates];
444 if (ti == 0 || wantsNormalsAsTextureCoordinates != usingNormalsAsTexCoords) {
445 // FIXME: enabling/disabling texturing should be handled by the material.
446#if OO_MULTITEXTURE
447 for (unit = 0; unit < _textureUnitCount; unit++) {
448 if (_textureUnitCount > 1) {
449 OOGL(glClientActiveTextureARB(GL_TEXTURE0_ARB + unit));
450 OOGL(glActiveTextureARB(GL_TEXTURE0_ARB + unit));
451 }
452#endif
453 if (!wantsNormalsAsTextureCoordinates) {
454 OOGL(glDisable(GL_TEXTURE_CUBE_MAP));
455 OOGL(glTexCoordPointer(2, GL_FLOAT, 0, _displayLists.textureUVArray));
456 /* FIXME: Not including the line below breaks multitexturing in no-shaders mode.
457 However, the OpenGL state manager should probably be handling this;
458 TEXTURE_2D is part of OPENGL_STATE_OPAQUE, which has already been set.
459 - Nikos 20130103
460 */
461 OOGL(glEnable(GL_TEXTURE_2D));
462 } else {
463 OOGL(glDisable(GL_TEXTURE_2D));
464 OOGL(glTexCoordPointer(3, GL_FLOAT, 0, _displayLists.vertexArray));
465 OOGL(glEnable(GL_TEXTURE_CUBE_MAP));
466 }
467#if OO_MULTITEXTURE
468 }
469#endif
470 usingNormalsAsTexCoords = wantsNormalsAsTextureCoordinates;
471 }
472
473 [materials[ti] apply];
474 OOGL(glDrawArrays(GL_TRIANGLES, triangle_range[ti].location, triangle_range[ti].length));
475 }
476
477 listsReady = YES;
478 brokenInRender = NO;
479 }
480 @catch (NSException* exception) {
481 if (!brokenInRender) {
482 OOLog(kOOLogException, @"***** %s for %@ encountered exception: %@ : %@ *****", __PRETTY_FUNCTION__, self, [exception name], [exception reason]);
483 brokenInRender = YES;
484 }
485 if ([[exception name] hasPrefix:@"Oolite"])
486 [UNIVERSE handleOoliteException:exception]; // handle these ourself
487 else
488 @throw exception; // pass these on
489 }
490
491#if OO_SHADERS
492 if ([[OOOpenGLExtensionManager sharedManager] shadersSupported]) {
493 OOGL(glDisableVertexAttribArrayARB(kTangentAttributeIndex));
494 }
495#endif
496
498 OOCheckOpenGLErrors(@"OOMesh after drawing %@", self);
499
500#if OO_MULTITEXTURE
501 if (_textureUnitCount <= 1) {
502 OOGL(glDisableClientState(GL_TEXTURE_COORD_ARRAY));
503 } else {
504 for (unit = 0; unit < _textureUnitCount; unit++) {
505 OOGL(glClientActiveTextureARB(GL_TEXTURE0_ARB + unit));
506 OOGL(glDisableClientState(GL_TEXTURE_COORD_ARRAY));
507 }
508
509 OOGL(glClientActiveTextureARB(GL_TEXTURE0_ARB));
510 OOGL(glActiveTextureARB(GL_TEXTURE0_ARB));
511 }
512#else
513 OOGL(glDisableClientState(GL_TEXTURE_COORD_ARRAY));
514#endif
515
516#ifdef OO_DEBUG_MONITOR_ENABLED
518 [self debugDrawNormals];
520 [[self octree] drawOctree];
521#endif
522
523 // visual effect - disable previously enabled blending
524 if (meshBelongsToVisualEffect)
525 OOGL(glDisable(GL_BLEND));
526
528}
#define gDebugFlags
@ DEBUG_OCTREE_DRAW
@ DEBUG_DRAW_NORMALS
NSString *const kOOLogException
Definition OOLogging.m:600
uint8_t OOMeshMaterialIndex
Definition OOMesh.h:54
@ OPENGL_STATE_OPAQUE
Definition OOOpenGL.h:121
#define OOVerifyOpenGLState()
Definition OOOpenGL.h:133
BOOL OOCheckOpenGLErrors(NSString *format,...)
Definition OOOpenGL.m:38
#define OOSetOpenGLState(STATE)
Definition OOOpenGL.h:132
void applyNone()
Definition OOMaterial.m:72
uint8_t brokenInRender
Definition OOMesh.h:85
NSRange triangle_range[kOOMeshMaxMaterials]
Definition OOMesh.h:104

References _displayLists, OOMaterial::apply, OOMaterial::applyNone, brokenInRender, count, DEBUG_DRAW_NORMALS, DEBUG_OCTREE_DRAW, displayList0, OOMaterial::ensureFinishedLoading, gDebugFlags, kOOLogException, listsReady, materialCount, octree, OO_ENTER_OPENGL, OOCheckOpenGLErrors(), OOGL, OOLog, OOSetOpenGLState, OOVerifyOpenGLState, OPENGL_STATE_OPAQUE, renderOpaqueParts, triangle_range, and OOMaterial::wantsNormalsAsTextureCoordinates.

Referenced by renderOpaqueParts.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ rescaleByFactor:

- (void) rescaleByFactor: (GLfloat) factor
implementation

Provided by category OOMesh(Private).

Definition at line 1827 of file OOMesh.m.

1827 :(GLfloat)factor
1828{
1829 // Rescale base vertices used for geometry calculations.
1831 Vector* vertex = NULL;
1832
1833 for (i = 0; i < vertexCount; i++) {
1834 vertex = &_vertices[i];
1835 *vertex = vector_multiply_scalar(*vertex, factor);
1836 }
1837
1838 // Rescale actual display vertices.
1839 for (i = 0; i < _displayLists.count; i++) {
1840 vertex = &_displayLists.vertexArray[i];
1841 *vertex = vector_multiply_scalar(*vertex, factor);
1842 }
1843
1844 [self calculateBoundingVolumes];
1845 DESTROY(octree);
1846 DESTROY(baseFile); // Avoid octree cache.
1848}

◆ resetGraphicsState

- (void) resetGraphicsState
implementation

Provided by category OOMesh(Private).

Definition at line 923 of file OOMesh.m.

924{
925 [self deleteDisplayLists];
926 [self rebindMaterials];
927 _textureUnitCount = NSNotFound;
928}

◆ setBindingTarget:

- (void) setBindingTarget: (id<OOWeakReferenceSupport>) target
implementation

Reimplemented from OODrawable.

Definition at line 746 of file OOMesh.m.

746 :(id<OOWeakReferenceSupport>)target
747{
748 unsigned i;
749
750 for (i = 0; i != kOOMeshMaxMaterials; ++i) {
751 [materials[i] setBindingTarget:target];
752 }
753}

References kOOMeshMaxMaterials, and OOMaterial::setBindingTarget:.

Here is the call graph for this function:

◆ setModelFromModelData:name:

- (BOOL) setModelFromModelData: (NSDictionary*) dict
name: (NSString*) fileName 
implementation

Provided by category OOMesh(Private).

Definition at line 992 of file OOMesh.m.

992 :(NSDictionary*)dict name:(NSString*)fileName
993{
995
996 NSData *vertData = nil,
997 *normData = nil,
998 *tanData = nil,
999 *faceData = nil;
1000 NSArray* mtlKeys = nil;
1001 NSString* key = nil;
1002 unsigned i;
1003
1004 if (dict == nil || ![dict isKindOfClass:[NSDictionary class]])
1005 return NO;
1006
1007 vertexCount = [dict oo_unsignedIntForKey:@"vertex count"];
1008 faceCount = [dict oo_unsignedIntForKey:@"face count"];
1009
1010 if (vertexCount == 0 || faceCount == 0)
1011 return NO;
1012
1013 // Read data elements from dictionary.
1014 vertData = [dict oo_dataForKey:@"vertex data"];
1015 faceData = [dict oo_dataForKey:@"face data"];
1016
1017 mtlKeys = [dict oo_arrayForKey:@"material keys"];
1018 _normalMode = [dict oo_unsignedCharForKey:@"normal mode"];
1019 BOOL includeNormals = IsPerVertexNormalMode(_normalMode);
1020
1021 // Ensure we have all the required data elements.
1022 if (vertData == nil || faceData == nil || mtlKeys == nil) {
1023 OOLog(@"mesh.load.error.badCacheData", @"Ignoring bad cache data for mesh \"%@\".", fileName);
1024 return NO;
1025 }
1026
1027 if (includeNormals) {
1028 normData = [dict oo_dataForKey:@"normal data"];
1029 tanData = [dict oo_dataForKey:@"tangent data"];
1030 if (normData == nil || tanData == nil) {
1031 OOLog(@"mesh.load.error.badCacheData", @"Ignoring bad normal/tangent cache data for mesh \"%@\".", fileName);
1032 return NO;
1033 }
1034 }
1035
1036 // Ensure data objects are of correct size.
1037 if ([vertData length] != sizeof *_vertices * vertexCount)
1038 return NO;
1039 if ([faceData length] != sizeof *_faces * faceCount)
1040 return NO;
1041 if (includeNormals) {
1042 if ([normData length] != sizeof *_normals * vertexCount)
1043 return NO;
1044 if ([tanData length] != sizeof *_tangents * vertexCount)
1045 return NO;
1046 }
1047
1048 // Retain data.
1049 _vertices = (Vector*)[vertData bytes];
1050 [self setRetainedObject:vertData forKey:@"vertices"];
1051 _faces = (OOMeshFace*)[faceData bytes];
1052 [self setRetainedObject:faceData forKey:@"faces"];
1053 if (includeNormals) {
1054 _normals = (Vector*)[normData bytes];
1055 [self setRetainedObject:normData forKey:@"normals"];
1056 _tangents = (Vector*)[tanData bytes];
1057 [self setRetainedObject:tanData forKey:@"tangents"];
1058 } else {
1059 _normals = NULL;
1060 _tangents = NULL;
1061 }
1062
1063 // Copy material keys.
1064 materialCount = [mtlKeys count];
1065 for (i = 0; i != materialCount; ++i) {
1066 key = [mtlKeys oo_stringAtIndex:i];
1067 if (key != nil)
1068 materialKeys[i] = [key copy];
1069 else {
1070 OOLog(@"mesh.load.error.badCacheData", @"Ignoring bad cache data for mesh \"%@\".", fileName);
1071 return NO;
1072 }
1073 }
1074
1075 return YES;
1076
1078}

◆ setRetainedObject:forKey:

- (void) setRetainedObject: (id) object
forKey: (NSString*) key 
implementation

Provided by category OOMesh(Private).

Definition at line 1907 of file OOMesh.m.

1907 :(id)object forKey:(NSString*)key
1908{
1909 assert(key != nil);
1910
1911 if (object != nil) {
1912 if (_retainedObjects == nil)
1913 _retainedObjects = [[NSMutableDictionary alloc] init];
1914 [_retainedObjects setObject:object forKey:key];
1915 }
1916}

Referenced by OOMesh(Private)::allocateBytesWithSize:count:key:, and OOMesh(Private)::setModelFromModelData:name:.

Here is the caller graph for this function:

◆ setUpVertexArrays

- (BOOL) setUpVertexArrays
implementation

Provided by category OOMesh(Private).

Definition at line 1706 of file OOMesh.m.

1707{
1709
1710 NSUInteger fi, vi, mi;
1711
1712 if (![self allocateVertexArrayBuffersWithCount:faceCount])
1713 return NO;
1714
1715 // if smoothed, find any vertices that are between faces of different
1716 // smoothing groups and mark them as being on an edge and therefore NOT
1717 // smooth shaded
1718 BOOL is_edge_vertex[vertexCount];
1719 GLfloat smoothGroup[vertexCount];
1720 for (vi = 0; vi < vertexCount; vi++) {
1721 is_edge_vertex[vi] = NO;
1722 smoothGroup[vi] = -1;
1723 }
1725 for (fi = 0; fi < faceCount; fi++) {
1726 GLfloat rv = _faces[fi].smoothGroup;
1727 int i;
1728 for (i = 0; i < 3; i++) {
1729 vi = _faces[fi].vertex[i];
1730 if (smoothGroup[vi] < 0.0) // unassigned
1731 smoothGroup[vi] = rv;
1732 else if (smoothGroup[vi] != rv) // a different colour
1733 is_edge_vertex[vi] = YES;
1734 }
1735 }
1736 }
1737
1738 // base model, flat or smooth shaded, all triangles
1739 int tri_index = 0;
1740 int uv_index = 0;
1741 int vertex_index = 0;
1742
1743 // Iterate over material names
1744 for (mi = 0; mi != materialCount; ++mi) {
1745 triangle_range[mi].location = tri_index;
1746
1747 for (fi = 0; fi < faceCount; fi++) {
1748 Vector normal, tangent;
1749
1750 if (_faces[fi].materialIndex == mi) {
1751 for (vi = 0; vi < 3; vi++) {
1752 int v = _faces[fi].vertex[vi];
1754 if (is_edge_vertex[v]) {
1755 [self getNormal:&normal andTangent:&tangent forVertex:v inSmoothGroup:_faces[fi].smoothGroup];
1756 } else {
1757 NSAssert1(_normals != NULL && _tangents != NULL, @"Normal/tangent buffers not allocated in %s", __PRETTY_FUNCTION__);
1758
1759 normal = _normals[v];
1760 tangent = _tangents[v];
1761 }
1762 } else {
1763 normal = _faces[fi].normal;
1764 tangent = _faces[fi].tangent;
1765 }
1766
1767 // FIXME: avoid redundant vertices so index array is actually useful.
1768 _displayLists.indexArray[tri_index++] = vertex_index;
1769 _displayLists.normalArray[vertex_index] = normal;
1770 _displayLists.tangentArray[vertex_index] = tangent;
1771 _displayLists.vertexArray[vertex_index++] = _vertices[v];
1772 _displayLists.textureUVArray[uv_index++] = _faces[fi].s[vi];
1773 _displayLists.textureUVArray[uv_index++] = _faces[fi].t[vi];
1774 }
1775 }
1776 }
1777 triangle_range[mi].length = tri_index - triangle_range[mi].location;
1778 }
1779
1780 _displayLists.count = tri_index; // total number of triangle vertices
1781 return YES;
1782
1784}

◆ shaders

- (NSDictionary *) shaders

Definition at line 570 of file OOMesh.m.

571{
572 return _shadersDict;
573}

References _shadersDict, and shaders.

Referenced by materials, shaders, ShipSetMaterialsInternal(), ShipSetMaterialsInternal(), VisualEffectGetShaders(), VisualEffectGetShaders(), VisualEffectSetMaterialsInternal(), and VisualEffectSetMaterialsInternal().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ suppressClangStuff

- (BOOL) suppressClangStuff
implementation

Definition at line 808 of file OOMesh.m.

809{
810 return _normals && _tangents && _faces && boundingBox.min.x;
811}

References _faces, _normals, _tangents, boundingBox, and suppressClangStuff.

Referenced by suppressClangStuff.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ vertexCount

- (size_t) vertexCount

References vertexCount.

Member Data Documentation

◆ _cacheKey

- (NSString*) _cacheKey
private

Definition at line 119 of file OOMesh.h.

Referenced by dealloc.

◆ _cacheWriteable

- (BOOL) _cacheWriteable
private

Definition at line 94 of file OOMesh.h.

Referenced by init.

◆ _displayLists

- (OOMeshDisplayLists) _displayLists
private

Definition at line 102 of file OOMesh.h.

Referenced by renderOpaqueParts.

◆ _faces

- (OOMeshFace*) _faces
private

Definition at line 99 of file OOMesh.h.

Referenced by suppressClangStuff.

◆ _lastBoundingBox

- (BoundingBox) _lastBoundingBox
private

Definition at line 125 of file OOMesh.h.

Referenced by findSubentityBoundingBoxWithPosition:rotMatrix:, and init.

◆ _lastPosition

- (Vector) _lastPosition
private

Definition at line 123 of file OOMesh.h.

Referenced by findSubentityBoundingBoxWithPosition:rotMatrix:, and init.

◆ _lastRotMatrix

- (OOMatrix) _lastRotMatrix
private

Definition at line 124 of file OOMesh.h.

Referenced by findSubentityBoundingBoxWithPosition:rotMatrix:, and init.

◆ _materialDict

- (NSDictionary*) _materialDict
private

Definition at line 117 of file OOMesh.h.

Referenced by dealloc.

◆ _normalMode

- (uint8_t) _normalMode
private

Definition at line 84 of file OOMesh.h.

◆ _normals

- (Vector*) _normals
private

Definition at line 97 of file OOMesh.h.

Referenced by suppressClangStuff.

◆ _retainedObjects

- (NSMutableDictionary*) _retainedObjects
private

Definition at line 115 of file OOMesh.h.

Referenced by dealloc.

◆ _shaderBindingTarget

- (id) _shaderBindingTarget
private

Definition at line 121 of file OOMesh.h.

Referenced by dealloc.

◆ _shaderMacros

- (NSDictionary*) _shaderMacros
private

Definition at line 120 of file OOMesh.h.

Referenced by dealloc.

◆ _shadersDict

- (NSDictionary*) _shadersDict
private

Definition at line 118 of file OOMesh.h.

Referenced by dealloc, and shaders.

◆ _tangents

- (Vector*) _tangents
private

Definition at line 98 of file OOMesh.h.

Referenced by suppressClangStuff.

◆ _vertices

◆ baseFile

- (NSString*) baseFile
private

Definition at line 92 of file OOMesh.h.

Referenced by dealloc, init, modelName, and octreeDepth.

◆ baseFileOctreeCacheRef

- (NSString*) baseFileOctreeCacheRef
private

Definition at line 93 of file OOMesh.h.

Referenced by dealloc, and init.

◆ boundingBox

- (BoundingBox) boundingBox
private

◆ brokenInRender

- (uint8_t) brokenInRender
private

Definition at line 85 of file OOMesh.h.

Referenced by renderOpaqueParts.

◆ collisionRadius

- (GLfloat) collisionRadius
private

Definition at line 580 of file OOMesh.m.

581{
582 return collisionRadius;
583}

Referenced by descriptionComponents.

◆ displayList0

- (GLuint) displayList0
private

Definition at line 107 of file OOMesh.h.

Referenced by renderOpaqueParts.

◆ faceCount

- (size_t) faceCount
private

Definition at line 363 of file OOMesh.m.

364{
365 return faceCount;
366}

Referenced by descriptionComponents, and faceCount.

◆ listsReady

- (uint8_t) listsReady
private

Definition at line 86 of file OOMesh.h.

Referenced by OOMesh(Private)::mutableCopyWithZone:, and renderOpaqueParts.

◆ materialCount

- (OOMeshMaterialCount) materialCount
private

Definition at line 88 of file OOMesh.h.

Referenced by rebindMaterials, and renderOpaqueParts.

◆ materialKeys

- (NSString* materialKeys[kOOMeshMaxMaterials])
private

Definition at line 105 of file OOMesh.h.

Referenced by dealloc, and rebindMaterials.

◆ materials

◆ maxDrawDistance

- (GLfloat) maxDrawDistance
private

Definition at line 585 of file OOMesh.m.

586{
587 return maxDrawDistance;
588}

◆ octree

- (Octree *) octree
private

Definition at line 631 of file OOMesh.m.

632{
633 if (octree == nil) {
634 octree = [[OOCacheManager octreeForModel:baseFileOctreeCacheRef] retain];
635 if (octree == nil) {
636 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
637
638 OOMeshToOctreeConverter* converter = [OOMeshToOctreeConverter converterWithCapacity:faceCount];
640 for (i = 0; i < faceCount; i++) {
641 // Somewhat surprisingly, this method doesn't even show up in profiles. -- Ahruman 2012-09-22
642 Triangle tri;
643 tri.v[0] = _vertices[_faces[i].vertex[0]];
644 tri.v[1] = _vertices[_faces[i].vertex[1]];
645 tri.v[2] = _vertices[_faces[i].vertex[2]];
646 [converter addTriangle:tri];
647 }
648
649 octree = [converter findOctreeToDepth:[self octreeDepth]];
650 [octree retain];
651 if (EXPECT(_cacheWriteable)) {
652 [OOCacheManager setOctree:octree forModel:baseFileOctreeCacheRef];
653 }
654
655 [pool release];
656 } else {
657 OOLog(@"mesh.load.octreeCached", @"Retrieved octree \"%@\" from cache.", baseFileOctreeCacheRef);
658 }
659 }
660
661 return octree;
662}
return self
id init()
Definition OOMesh.m:274
unsigned octreeDepth()
Definition OOMesh.m:591
Vector v[3]
Definition OOTriangle.h:29

Referenced by dealloc, octree, renderOpaqueParts, and ShipEntity::setMesh:.

◆ triangle_range

- (NSRange triangle_range[kOOMeshMaxMaterials])
private

Definition at line 104 of file OOMesh.h.

Referenced by renderOpaqueParts.

◆ vertexCount

- (size_t) vertexCount
private

The documentation for this class was generated from the following files: