Subversion Repositories gelsvn

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
78 jab 1
// bdl, jab, feb 2005
2
// Inspired by Nate Robins Obj loader
3
 
4
#include <CGLA/Vec3f.h>
5
#include <stdio.h>
6
#include <iostream>
7
 
178 bj 8
#include "TriMesh.h"
9
 
78 jab 10
using namespace std;
11
using namespace CGLA;
12
 
79 jab 13
namespace Geometry 
78 jab 14
{
15
	int TriMesh::find_material(const string& name) const
16
	{
136 jab 17
		for(size_t i=0;i<materials.size(); ++i)
78 jab 18
			{
19
				if(materials[i].name == name)
20
					return i;
21
			}
22
		return 0;
23
	}
178 bj 24
 
78 jab 25
	void TriMesh::compute_normals()
26
	{		
27
		// By default the normal faces are the same as the geometry faces
28
		// and there are just as many normals as vertices, so we simply
29
		// copy.
30
		normals = geometry;
31
 
32
		const int NV = normals.no_vertices();
33
		// The normals are initialized to zero.
34
		int i;
35
		for(i=0;i<NV; ++i)
36
			normals.vertex_rw(i) = Vec3f(0);
37
 
38
		// For each face
39
		int NF = geometry.no_faces();
40
		for(i=0;i<NF; ++i)
41
      {
42
				// Compute the normal
43
				const Vec3i& f  = geometry.face(i);
44
				const Vec3f p0 = geometry.vertex(f[0]);
45
				const Vec3f a  = geometry.vertex(f[1]) - p0;
46
				const Vec3f b  = geometry.vertex(f[2]) - p0;
47
				Vec3f face_normal = cross(a,b);
48
				float l = sqr_length(face_normal);
49
				if(l > 0.0f)
50
					face_normal /= sqrt(l);
51
 
52
				// Add the angle weighted normal to each vertex
53
				for(int j=0;j<3; ++j)
54
					{
55
						const Vec3f p0 = geometry.vertex(f[j]);
56
						const Vec3f a = normalize(geometry.vertex(f[(j+1)%3]) - p0);
57
						const Vec3f b = normalize(geometry.vertex(f[(j+2)%3]) - p0);
58
						float d = max(-1.0f, min(1.0f, dot(a,b)));
59
						normals.vertex_rw(f[j]) += face_normal * acos(d);
60
					}
61
      }
62
 
63
		// Normalize all normals
64
    for(i=0;i<NV; ++i)
65
			{
66
				normals.vertex_rw(i).normalize();
67
			}
68
	}
69
 
70
 
71
  void TriMesh::get_bbox(CGLA::Vec3f& p0, CGLA::Vec3f& p7) const
72
  {
73
    int i;
74
    p0 = geometry.vertex(0);
75
    p7 = geometry.vertex(0);
76
    for(i=1;i<geometry.no_vertices();i++) 
77
      {
78
				p0 = v_min(geometry.vertex(i), p0);
79
				p7 = v_max(geometry.vertex(i), p7);
80
      }
81
  }
82
 
83
  void TriMesh::get_bsphere(CGLA::Vec3f& c, float& r) const
84
  {
85
    Vec3f p0,p7;
86
    get_bbox(p0, p7);
87
    Vec3f rad = (p7 - p0)/2.0;
88
    c = p0 + rad;
89
    r = rad.length();
90
  }
91
 
92
 
93
}