-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasst8.cpp.new
More file actions
executable file
·1450 lines (1222 loc) · 46.6 KB
/
asst8.cpp.new
File metadata and controls
executable file
·1450 lines (1222 loc) · 46.6 KB
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////////////////////////////////////////////////////////////////////////
//
// Harvard University
// CS175 : Computer Graphics
// Professor Steven Gortler
//
////////////////////////////////////////////////////////////////////////
#include <cstddef>
#include <vector>
#include <list>
#include <string>
#include <memory>
#include <map>
#include <fstream>
#include <stdexcept>
#if __GNUG__
# include <tr1/memory>
#endif
#include <GL/glew.h>
#ifdef __MAC__
# include <GLUT/glut.h>
#else
# include <GL/glut.h>
#endif
#include "ppm.h"
#include "cvec.h"
#include "matrix4.h"
#include "rigtform.h"
#include "glsupport.h"
#include "geometrymaker.h"
#include "geometry.h"
#include "arcball.h"
#include "scenegraph.h"
#include "sgutils.h"
#include "asstcommon.h"
#include "drawer.h"
#include "picker.h"
#include "mesh.h"
using namespace std;
using namespace tr1;
// G L O B A L S ///////////////////////////////////////////////////
// --------- IMPORTANT --------------------------------------------------------
// Before you start working on this assignment, set the following variable
// properly to indicate whether you want to use OpenGL 2.x with GLSL 1.0 or
// OpenGL 3.x+ with GLSL 1.3.
//
// Set g_Gl2Compatible = true to use GLSL 1.0 and g_Gl2Compatible = false to
// use GLSL 1.3. Make sure that your machine supports the version of GLSL you
// are using. In particular, on Mac OS X currently there is no way of using
// OpenGL 3.x with GLSL 1.3 when GLUT is used.
//
// If g_Gl2Compatible=true, shaders with -gl2 suffix will be loaded.
// If g_Gl2Compatible=false, shaders with -gl3 suffix will be loaded.
// To complete the assignment you only need to edit the shader files that get
// loaded
// ----------------------------------------------------------------------------
const bool g_Gl2Compatible = true;
static const float g_frustMinFov = 60.0; // A minimal of 60 degree field of view
static float g_frustFovY = g_frustMinFov; // FOV in y direction (updated by updateFrustFovY)
static const float g_frustNear = -0.1; // near plane
static const float g_frustFar = -50.0; // far plane
static const float g_groundY = -2.0; // y coordinate of the ground
static const float g_groundSize = 10.0; // half the ground length
enum SkyMode {WORLD_SKY=0, SKY_SKY=1};
static int g_windowWidth = 512;
static int g_windowHeight = 512;
static bool g_mouseClickDown = false; // is the mouse button pressed
static bool g_mouseLClickButton, g_mouseRClickButton, g_mouseMClickButton;
static int g_mouseClickX, g_mouseClickY; // coordinates for mouse click event
static int g_activeShader = 0;
static SkyMode g_activeCameraFrame = WORLD_SKY;
static bool g_displayArcball = true;
static double g_arcballScreenRadius = 100; // number of pixels
static double g_arcballScale = 1;
static bool g_pickingMode = false;
static bool g_playingAnimation = false;
// --------- Materials
static shared_ptr<Material> g_redDiffuseMat,
g_blueDiffuseMat,
g_bumpFloorMat,
g_arcballMat,
g_pickingMat,
g_lightMat,
g_shinyMat;
static shared_ptr<Material> g_bunnyMat; // for the bunny
static vector<shared_ptr<Material> > g_bunnyShellMats; // for bunny shells
shared_ptr<Material> g_overridingMaterial;
static bool g_smoothSubdRendering = false;
// --------- Geometry
typedef SgGeometryShapeNode MyShapeNode;
// Vertex buffer and index buffer associated with the ground and cube geometry
static shared_ptr<Geometry> g_ground, g_cube, g_sphere;
static shared_ptr<SimpleGeometryPN> g_meshGeometry;
static Mesh g_mesh;
static int g_subdLevels = 0;
static const int g_numShells = 24; // constants defining how many layers of shells
static double g_furHeight = 0.21;
static double g_hairyness = 0.7;
static shared_ptr<SimpleGeometryPN> g_bunnyGeometry;
static vector<shared_ptr<SimpleGeometryPNX> > g_bunnyShellGeometries;
static Mesh g_bunnyMesh;
// --------- Scene
static shared_ptr<SgRootNode> g_world;
static shared_ptr<SgRbtNode> g_skyNode, g_groundNode, g_robot1Node, g_robot2Node, g_light1, g_light2, g_meshNode;
static shared_ptr<SgRbtNode> g_currentCameraNode;
static shared_ptr<SgRbtNode> g_currentPickedRbtNode;
static shared_ptr<SgRbtNode> g_bunnyNode;
// ---------- Animation
class Animator {
public:
typedef vector<shared_ptr<SgRbtNode> > SgRbtNodes;
typedef vector<RigTForm> KeyFrame;
typedef list<KeyFrame> KeyFrames;
typedef KeyFrames::iterator KeyFrameIter;
private:
SgRbtNodes nodes_;
KeyFrames keyFrames_;
public:
void attachSceneGraph(shared_ptr<SgNode> root) {
nodes_.clear();
keyFrames_.clear();
dumpSgRbtNodes(root, nodes_);
}
void loadAnimation(const char *filename) {
ifstream f(filename, ios::binary);
if (!f)
throw runtime_error(string("Cannot load ") + filename);
int numFrames, numRbtsPerFrame;
f >> numFrames >> numRbtsPerFrame;
if (numRbtsPerFrame != nodes_.size()) {
cerr << "Number of Rbt per frame in " << filename
<<" does not match number of SgRbtNodes in the current scene graph.";
return;
}
Cvec3 t;
Quat r;
keyFrames_.clear();
for (int i = 0; i < numFrames; ++i) {
keyFrames_.push_back(KeyFrame());
keyFrames_.back().reserve(numRbtsPerFrame);
for (int j = 0; j < numRbtsPerFrame; ++j) {
f >> t[0] >> t[1] >> t[2] >> r[0] >> r[1] >> r[2] >> r[3];
keyFrames_.back().push_back(RigTForm(t, r));
}
}
}
void saveAnimation(const char *filename) {
ofstream f(filename, ios::binary);
int numRbtsPerFrame = nodes_.size();
f << getNumKeyFrames() << ' ' << numRbtsPerFrame << '\n';
for (KeyFrames::const_iterator frameIter = keyFrames_.begin(), e = keyFrames_.end(); frameIter != e; ++frameIter) {
for (int j = 0; j < numRbtsPerFrame; ++j) {
const RigTForm& rbt = (*frameIter)[j];
const Cvec3& t = rbt.getTranslation();
const Quat& r = rbt.getRotation();
f << t[0] << ' ' << t[1] << ' ' << t[2] << ' '
<< r[0] << ' ' << r[1] << ' ' << r[2] << ' ' << r[3] << '\n';
}
}
}
int getNumKeyFrames() const {
return keyFrames_.size();
}
int getNumRbtNodes() const {
return nodes_.size();
}
// t can be in the range [0, keyFrames_.size()-3]. Fractional amount like 1.5 is allowed.
void animate(double t) {
if (t < 0 || t > keyFrames_.size() - 3)
throw runtime_error("Invalid animation time parameter. Must be in the range [0, numKeyFrames - 3]");
t += 1; // interpret the key frames to be at t= -1, 0, 1, 2, ...
const int integralT = int(floor(t));
const double fraction = t - integralT;
KeyFrameIter f1 = getNthKeyFrame(integralT), f0 = f1, f2 = f1;
--f0;
++f2;
KeyFrameIter f3 = f2;
++f3;
if (f3 == keyFrames_.end()) // this might be true when t is exactly keyFrames_.size()-3.
f3 = f2; // in which case we step back
for (int i = 0, n = nodes_.size(); i < n; ++i) {
nodes_[i]->setRbt(interpolateCatmullRom((*f0)[i], (*f1)[i], (*f2)[i], (*f3)[i], fraction));
}
}
KeyFrameIter keyFramesBegin() {
return keyFrames_.begin();
}
KeyFrameIter keyFramesEnd() {
return keyFrames_.end();
}
KeyFrameIter getNthKeyFrame(int n) {
KeyFrameIter frameIter = keyFrames_.begin();
advance(frameIter, n);
return frameIter;
}
void deleteKeyFrame(KeyFrameIter keyFrameIter) {
keyFrames_.erase(keyFrameIter);
}
void pullKeyFrameFromSg(KeyFrameIter keyFrameIter) {
for (int i = 0, n = nodes_.size(); i < n; ++i) {
(*keyFrameIter)[i] = nodes_[i]->getRbt();
}
}
void pushKeyFrameToSg(KeyFrameIter keyFrameIter) {
for (int i = 0, n = nodes_.size(); i < n; ++i) {
nodes_[i]->setRbt((*keyFrameIter)[i]);
}
}
KeyFrameIter insertEmptyKeyFrameAfter(KeyFrameIter beforeFrame) {
if (beforeFrame != keyFrames_.end())
++beforeFrame;
KeyFrameIter frameIter = keyFrames_.insert(beforeFrame, KeyFrame());
frameIter->resize(nodes_.size());
return frameIter;
}
};
static int g_msBetweenKeyFrames = 2000; // 2 seconds between keyframes
static int g_animateFramesPerSecond = 60; // frames to render per second during animation playback
static Animator g_animator;
static Animator::KeyFrameIter g_curKeyFrame;
static int g_curKeyFrameNum;
// these control bubbling of subdivision surface
static bool g_bubbling = true;
static double g_bublingTime = 0;
static double g_bubblingSpeed = 0.01;
// Global variables for used physical simulation
static const Cvec3 g_gravity(0, -0.5, 0); // gavity vector
static double g_timeStep = 0.02;
static double g_numStepsPerFrame = 10;
static double g_damping = 0.96;
static double g_stiffness = 10;
static int g_simulationsPerSecond = 60;
static std::vector<Cvec3> g_tipPos, // should be hair tip pos in world-space coordinates
g_tipVelocity; // should be hair tip velocity in world-space coordinates
///////////////// END OF G L O B A L S //////////////////////////////////////////////////
static VertexPN getVertexPN(Mesh& m, const int face, const int vertex);
static VertexPNX getFurVertexPNX(Mesh& m, const int face, const int vertex, int shellNum);
// Specifying shell geometries based on g_tipPos, g_furHeight, and g_numShells.
// You need to call this function whenver the shell needs to be updated
static void updateShellGeometry() {
Mesh m(g_bunnyMesh);
// dynamic vertex buffer
vector<VertexPNX> verts;
verts.reserve(m.getNumFaces() * 6); // conservative estimate of num of vertices
Cvec2 texture;
RigTForm bunny = getPathAccumRbt(g_world, g_bunnyNode, 0);
for (int i = 0; i < g_numShells; i++)
{
verts.clear();
for (int j = 0, l = m.getNumFaces(); j < l; j++)
{
for (int k = 0; k < 3; k++)
{
if (k == 0)
texture = Cvec2(0, 0);
else if (k == 1)
texture = Cvec2(0, g_hairyness);
else
texture = Cvec2(g_hairyness, 0);
Cvec3 p = g_bunnyMesh.getFace(j).getVertex(k).getPosition();
Cvec3 normal = g_bunnyMesh.getFace(j).getVertex(k).getNormal();
Cvec3 t = g_tipPos[g_bunnyMesh.getFace(j).getVertex(k).getIndex()];
Cvec3 s = p + (normal * g_furHeight);
int m = g_numShells;
Cvec3 n = normal * (g_furHeight / m);
t = Cvec3(inv(bunny) * Cvec4(t, 1));
Cvec3 d = (t - p - (normal * g_furHeight)) / ((m - 1) * m / 2);
Cvec3 pos;
if (i == 0)
pos = p;
else
pos = p + n * (i) + d * ((i-1) * (i) / 2);
verts.push_back(VertexPNX(pos, n + d * i, texture));
}
}
g_bunnyShellGeometries[i]->reset(&verts[0], verts.size());
}
// TASK 1 and 3 TODO: finish this function as part of Task 1 and Task 3
}
// New glut timer call back that perform dynamics simulation
// every g_simulationsPerSecond times per second
static void hairsSimulationCallback(int dontCare) {
RigTForm bunny = getPathAccumRbt(g_world, g_bunnyNode, 0);
for (int i = 0; i < g_numStepsPerFrame; i++)
{
for (int j = 0, m = g_bunnyMesh.getNumVertices(); j < m; j++)
{
Cvec3 p = g_bunnyMesh.getVertex(j).getPosition();
Cvec3 t = g_tipPos[j];
Cvec3 n = g_bunnyMesh.getVertex(j).getNormal();
Cvec3 s = p + (n * g_furHeight);
Cvec3 v = g_tipVelocity[j];
s = Cvec3(bunny * Cvec4(s, 1));
p = Cvec3(bunny * Cvec4(p, 1));
Cvec3 springForce = (s - t) * g_stiffness;
Cvec3 force = g_gravity + springForce;
t = t + v * g_timeStep;
if (norm(t - p) != 0)
t = p + (t - p) / norm(t - p) * g_furHeight;
g_tipVelocity[j] = (v + force * g_timeStep) * g_damping;
g_tipPos[j] = t;
}
}
// schedule this to get called again
glutTimerFunc(1000/g_simulationsPerSecond, hairsSimulationCallback, 0);
glutPostRedisplay(); // signal redisplaying
}
static void initSimulation() {
g_tipPos.resize(g_bunnyMesh.getNumVertices(), Cvec3(0));
g_tipVelocity = g_tipPos;
Mesh m(g_bunnyMesh);
g_tipPos.clear();
// TASK 1 TODO: initialize g_tipPos to "at-rest" hair tips in world coordinates
for (int i = 0; i < m.getNumFaces(); ++i) {
for (int j = 0; j < 3; ++j) {
g_tipPos.push_back((m.getFace(i).getVertex(j).getPosition()) + (m.getFace(i).getVertex(j).getNormal() * g_furHeight));
}
if (m.getFace(i).getNumVertices() == 4) {
// need another triangle to finish the face
for (int j = 0; j < 3; ++j) {
g_tipPos.push_back((m.getFace(i).getVertex(j).getPosition()) + (m.getFace(i).getVertex(j).getNormal() * g_furHeight));
}
}
}
// Starts hair tip simulation
hairsSimulationCallback(0);
}
static void initGround() {
int ibLen, vbLen;
getPlaneVbIbLen(vbLen, ibLen);
// Temporary storage for cube Geometry
vector<VertexPNTBX> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makePlane(g_groundSize*2, vtx.begin(), idx.begin());
g_ground.reset(new SimpleIndexedGeometryPNTBX(&vtx[0], &idx[0], vbLen, ibLen));
}
static void initCubes() {
int ibLen, vbLen;
getCubeVbIbLen(vbLen, ibLen);
// Temporary storage for cube Geometry
vector<VertexPNTBX> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makeCube(1, vtx.begin(), idx.begin());
g_cube.reset(new SimpleIndexedGeometryPNTBX(&vtx[0], &idx[0], vbLen, ibLen));
}
static void initSphere() {
int ibLen, vbLen;
getSphereVbIbLen(20, 10, vbLen, ibLen);
// Temporary storage for sphere Geometry
vector<VertexPNTBX> vtx(vbLen);
vector<unsigned short> idx(ibLen);
makeSphere(1, 20, 10, vtx.begin(), idx.begin());
g_sphere.reset(new SimpleIndexedGeometryPNTBX(&vtx[0], &idx[0], vtx.size(), idx.size()));
}
static void initRobots() {
// Init whatever extra geometry needed for the robots
}
static void initNormals(Mesh& m) {
for (int i = 0; i < m.getNumVertices(); ++i) {
m.getVertex(i).setNormal(Cvec3(0));
}
for (int i = 0; i < m.getNumFaces(); ++i) {
const Mesh::Face f = m.getFace(i);
const Cvec3 n = f.getNormal();
for (int j = 0; j < f.getNumVertices(); ++j) {
f.getVertex(j).setNormal(f.getVertex(j).getNormal() + n);
}
}
for (int i = 0; i < m.getNumVertices(); ++i) {
Cvec3 n = m.getVertex(i).getNormal();
if (norm2(n) > CS175_EPS2)
m.getVertex(i).setNormal(normalize(n));
}
}
static void subdivide(Mesh& m) {
for (int i = 0; i < m.getNumFaces(); ++i) {
const Mesh::Face f = m.getFace(i);
m.setNewFaceVertex(f, Cvec3(0));
for (int j = f.getNumVertices()-1; j >= 0; --j) {
m.setNewFaceVertex(f, m.getNewFaceVertex(f) + f.getVertex(j).getPosition());
}
m.setNewFaceVertex(f, m.getNewFaceVertex(f) / f.getNumVertices());
}
for (int i = 0; i < m.getNumEdges(); ++i) {
const Mesh::Edge e = m.getEdge(i);
m.setNewEdgeVertex(e, (m.getNewFaceVertex(e.getFace(0)) + m.getNewFaceVertex(e.getFace(1)) + e.getVertex(0).getPosition() + e.getVertex(1).getPosition()) * 0.25);
}
for (int i = 0; i < m.getNumVertices(); ++i) {
const Mesh::Vertex v = m.getVertex(i);
Cvec3 rv = v.getPosition(), re(0), rf(0);
double n = 0;
Mesh::VertexIterator it(v.getIterator()), it0(it);
do {
re += it.getVertex().getPosition();
rf += m.getNewFaceVertex(it.getFace());
}
while (++n, ++it != it0);
m.setNewVertexVertex(v, rv * ((n-2)/n) + (re + rf) / (n*n));
}
m.subdivide();
}
static VertexPN getVertexPN(Mesh& m, const int face, const int vertex) {
const Mesh::Face f = m.getFace(face);
const Cvec3 n = g_smoothSubdRendering ? f.getVertex(vertex).getNormal() : f.getNormal();
const Cvec3& v = f.getVertex(vertex).getPosition();
return VertexPN(v[0], v[1], v[2], n[0], n[1], n[2]);
}
static VertexPNX getFurVertexPNX(Mesh& m, const int face, const int vertex, int shellNum) {
const Mesh::Face f = m.getFace(face);
const Cvec3 n = f.getVertex(vertex).getNormal();
const Cvec3 normalizedN = normalize(n);
Cvec3 scaleValue = ((normalizedN * (double) g_furHeight) / g_numShells) * shellNum;
const Cvec3& v = (f.getVertex(vertex).getPosition()) + scaleValue;
Cvec2 t;
if (vertex == 0) {
t = Cvec2(0,0);
} else if (vertex == 1) {
t = Cvec2(g_hairyness,0);
} else {
t = Cvec2(0,g_hairyness);
}
return VertexPNX(v[0], v[1], v[2], n[0], n[1], n[2], t[0], t[1]);
}
// Interpret t as milliseconds
static void updateSubdMesh(int levelSubd) {
Mesh m(g_mesh);
for (int i = 0; i < m.getNumVertices(); ++i) {
m.getVertex(i).setPosition(g_mesh.getVertex(i).getPosition() * (1 + 0.7*sin(double(3 + (i%5)) * g_bublingTime)));
}
for (int i = 0; i < levelSubd; ++i) {
subdivide(m);
}
initNormals(m);
// dynamic vertex buffer
vector<VertexPN> verts;
verts.reserve(m.getNumFaces() * 6); // conservative estimate of num of vertices
for (int i = 0; i < m.getNumFaces(); ++i) {
for (int j = 0; j < 3; ++j) {
verts.push_back(getVertexPN(m, i, j));
}
if (m.getFace(i).getNumVertices() == 4) {
// need another triangle to finish the face
for (int j = 0; j < 3; ++j) {
verts.push_back(getVertexPN(m, i, (2 + j) % 4));
}
}
}
g_meshGeometry->reset(&verts[0], verts.size());
}
static void initSubdMesh() {
g_mesh.load("cube.mesh");
// allocate enough vertices for 7 levels of subdivision
g_meshGeometry.reset(new SimpleGeometryPN());
updateSubdMesh(g_subdLevels);
}
// takes a projection matrix and send to the the shaders
static void sendProjectionMatrix(Uniforms& uniforms, const Matrix4& projMatrix) {
uniforms.put("uProjMatrix", projMatrix);
}
// update g_frustFovY from g_frustMinFov, g_windowWidth, and g_windowHeight
static void updateFrustFovY() {
if (g_windowWidth >= g_windowHeight)
g_frustFovY = g_frustMinFov;
else {
const double RAD_PER_DEG = 0.5 * CS175_PI/180;
g_frustFovY = atan2(sin(g_frustMinFov * RAD_PER_DEG) * g_windowHeight / g_windowWidth, cos(g_frustMinFov * RAD_PER_DEG)) / RAD_PER_DEG;
}
}
static Matrix4 makeProjectionMatrix() {
return Matrix4::makeProjection(
g_frustFovY, g_windowWidth / static_cast <double> (g_windowHeight),
g_frustNear, g_frustFar);
}
enum ManipMode {
ARCBALL_ON_PICKED,
ARCBALL_ON_SKY,
EGO_MOTION
};
static ManipMode getManipMode() {
// if nothing is picked or the picked transform is the transfrom we are viewing from
if (g_currentPickedRbtNode == NULL || g_currentPickedRbtNode == g_currentCameraNode) {
if (g_currentCameraNode == g_skyNode && g_activeCameraFrame == WORLD_SKY)
return ARCBALL_ON_SKY;
else
return EGO_MOTION;
}
else
return ARCBALL_ON_PICKED;
}
static bool shouldUseArcball() {
return getManipMode() != EGO_MOTION;
}
// The translation part of the aux frame either comes from the current
// active object, or is the identity matrix when
static RigTForm getArcballRbt() {
switch (getManipMode()) {
case ARCBALL_ON_PICKED:
return getPathAccumRbt(g_world, g_currentPickedRbtNode);
case ARCBALL_ON_SKY:
return RigTForm();
case EGO_MOTION:
return getPathAccumRbt(g_world, g_currentCameraNode);
default:
throw runtime_error("Invalid ManipMode");
}
}
static void updateArcballScale() {
RigTForm arcballEye = inv(getPathAccumRbt(g_world, g_currentCameraNode)) * getArcballRbt();
double depth = arcballEye.getTranslation()[2];
if (depth > -CS175_EPS)
g_arcballScale = 0.02;
else
g_arcballScale = getScreenToEyeScale(depth, g_frustFovY, g_windowHeight);
}
static void drawArcBall(Uniforms& uniforms) {
RigTForm arcballEye = inv(getPathAccumRbt(g_world, g_currentCameraNode)) * getArcballRbt();
Matrix4 MVM = rigTFormToMatrix(arcballEye) * Matrix4::makeScale(Cvec3(1, 1, 1) * g_arcballScale * g_arcballScreenRadius);
sendModelViewNormalMatrix(uniforms, MVM, normalMatrix(MVM));
g_arcballMat->draw(*g_sphere, uniforms);
}
static void drawStuff(bool picking) {
updateShellGeometry();
// if we are not translating, update arcball scale
if (!(g_mouseMClickButton || (g_mouseLClickButton && g_mouseRClickButton)))
updateArcballScale();
Uniforms uniforms;
// build & send proj. matrix to vshader
const Matrix4 projmat = makeProjectionMatrix();
sendProjectionMatrix(uniforms, projmat);
const RigTForm eyeRbt = getPathAccumRbt(g_world, g_currentCameraNode);
const RigTForm invEyeRbt = inv(eyeRbt);
Cvec3 l1 = getPathAccumRbt(g_world, g_light1).getTranslation();
Cvec3 l2 = getPathAccumRbt(g_world, g_light2).getTranslation();
uniforms.put("uLight", Cvec3(invEyeRbt * Cvec4(l1, 1)));
uniforms.put("uLight2", Cvec3(invEyeRbt * Cvec4(l2, 1)));
if (!picking) {
Drawer drawer(invEyeRbt, uniforms);
g_world->accept(drawer);
if (g_displayArcball && shouldUseArcball())
drawArcBall(uniforms);
}
else {
Picker picker(invEyeRbt, uniforms);
g_overridingMaterial = g_pickingMat;
g_world->accept(picker);
g_overridingMaterial.reset();
glFlush();
g_currentPickedRbtNode = picker.getRbtNodeAtXY(g_mouseClickX, g_mouseClickY);
if (g_currentPickedRbtNode == g_groundNode)
g_currentPickedRbtNode.reset(); // set to NULL
cout << (g_currentPickedRbtNode ? "Part picked" : "No part picked") << endl;
}
}
static void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
drawStuff(false);
glutSwapBuffers();
checkGlErrors();
}
static void pick() {
// We need to set the clear color to black, for pick rendering.
// so let's save the clear color
GLdouble clearColor[4];
glGetDoublev(GL_COLOR_CLEAR_VALUE, clearColor);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
drawStuff(true);
// Uncomment below and comment out the glutPostRedisplay in mouse(...) call back
// to see result of the pick rendering pass
// glutSwapBuffers();
//Now set back the clear color
glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
checkGlErrors();
}
bool interpolateAndDisplay(float t) {
if (t > g_animator.getNumKeyFrames() - 3)
return true;
g_animator.animate(t);
return false;
}
static void animateTimerCallback(int ms) {
double t = (double)ms / g_msBetweenKeyFrames;
bool endReached = interpolateAndDisplay(t);
if (g_playingAnimation && !endReached) {
glutTimerFunc(1000/g_animateFramesPerSecond, animateTimerCallback, ms + 1000/g_animateFramesPerSecond);
}
else {
cerr << "Finished playing animation" << endl;
g_curKeyFrame = g_animator.keyFramesEnd();
advance(g_curKeyFrame, -2);
g_animator.pushKeyFrameToSg(g_curKeyFrame);
g_playingAnimation = false;
g_curKeyFrameNum = g_animator.getNumKeyFrames() - 2;
cerr << "Now at frame [" << g_curKeyFrameNum << "]" << endl;
}
glutPostRedisplay();
}
static void bubblingTimerCallback(int dontCare) {
if (g_bubbling) {
updateSubdMesh(g_subdLevels);
g_bublingTime += g_bubblingSpeed;
glutTimerFunc(1000/g_animateFramesPerSecond, bubblingTimerCallback, 0);
}
else {
cerr << "Bubbling stopped" << endl;
}
glutPostRedisplay();
}
static void reshape(const int w, const int h) {
g_windowWidth = w;
g_windowHeight = h;
glViewport(0, 0, w, h);
cerr << "Size of window is now " << w << "x" << h << endl;
g_arcballScreenRadius = min(h, w) * 0.25;
updateFrustFovY();
glutPostRedisplay();
}
static Cvec3 getArcballDirection(const Cvec2& p, const double r) {
double n2 = norm2(p);
if (n2 >= r*r)
return normalize(Cvec3(p, 0));
else
return normalize(Cvec3(p, sqrt(r*r - n2)));
}
static RigTForm moveArcball(const Cvec2& p0, const Cvec2& p1) {
const Matrix4 projMatrix = makeProjectionMatrix();
const RigTForm eyeInverse = inv(getPathAccumRbt(g_world, g_currentCameraNode));
const Cvec3 arcballCenter = getArcballRbt().getTranslation();
const Cvec3 arcballCenter_ec = Cvec3(eyeInverse * Cvec4(arcballCenter, 1));
if (arcballCenter_ec[2] > -CS175_EPS)
return RigTForm();
Cvec2 ballScreenCenter = getScreenSpaceCoord(arcballCenter_ec,
projMatrix, g_frustNear, g_frustFovY, g_windowWidth, g_windowHeight);
const Cvec3 v0 = getArcballDirection(p0 - ballScreenCenter, g_arcballScreenRadius);
const Cvec3 v1 = getArcballDirection(p1 - ballScreenCenter, g_arcballScreenRadius);
return RigTForm(Quat(0.0, v1[0], v1[1], v1[2]) * Quat(0.0, -v0[0], -v0[1], -v0[2]));
}
static RigTForm doMtoOwrtA(const RigTForm& M, const RigTForm& O, const RigTForm& A) {
return A * M * inv(A) * O;
}
static RigTForm getMRbt(const double dx, const double dy) {
RigTForm M;
if (g_mouseLClickButton && !g_mouseRClickButton) {
if (shouldUseArcball())
M = moveArcball(Cvec2(g_mouseClickX, g_mouseClickY), Cvec2(g_mouseClickX + dx, g_mouseClickY + dy));
else
M = RigTForm(Quat::makeXRotation(-dy) * Quat::makeYRotation(dx));
}
else {
double movementScale = getManipMode() == EGO_MOTION ? 0.02 : g_arcballScale;
if (g_mouseRClickButton && !g_mouseLClickButton) {
M = RigTForm(Cvec3(dx, dy, 0) * movementScale);
}
else if (g_mouseMClickButton || (g_mouseLClickButton && g_mouseRClickButton)) {
M = RigTForm(Cvec3(0, 0, -dy) * movementScale);
}
}
switch (getManipMode()) {
case ARCBALL_ON_PICKED:
break;
case ARCBALL_ON_SKY:
M = inv(M);
break;
case EGO_MOTION:
if (g_mouseLClickButton && !g_mouseRClickButton) // only invert rotation
M = inv(M);
break;
}
return M;
}
static RigTForm makeMixedFrame(const RigTForm& objRbt, const RigTForm& eyeRbt) {
return transFact(objRbt) * linFact(eyeRbt);
}
// l = w X Y Z
// o = l O
// a = w A = l (Z Y X)^1 A = l A'
// o = a (A')^-1 O
// => a M (A')^-1 O = l A' M (A')^-1 O
static void motion(const int x, const int y) {
if (!g_mouseClickDown)
return;
const double dx = x - g_mouseClickX;
const double dy = g_windowHeight - y - 1 - g_mouseClickY;
const RigTForm M = getMRbt(dx, dy); // the "action" matrix
// the matrix for the auxiliary frame (the w.r.t.)
RigTForm A = makeMixedFrame(getArcballRbt(), getPathAccumRbt(g_world, g_currentCameraNode));
shared_ptr<SgRbtNode> target;
switch (getManipMode()) {
case ARCBALL_ON_PICKED:
target = g_currentPickedRbtNode;
break;
case ARCBALL_ON_SKY:
target = g_skyNode;
break;
case EGO_MOTION:
target = g_currentCameraNode;
break;
}
A = inv(getPathAccumRbt(g_world, target, 1)) * A;
target->setRbt(doMtoOwrtA(M, target->getRbt(), A));
g_mouseClickX += dx;
g_mouseClickY += dy;
glutPostRedisplay(); // we always redraw if we changed the scene
}
static void mouse(const int button, const int state, const int x, const int y) {
g_mouseClickX = x;
g_mouseClickY = g_windowHeight - y - 1; // conversion from GLUT window-coordinate-system to OpenGL window-coordinate-system
g_mouseLClickButton |= (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN);
g_mouseRClickButton |= (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN);
g_mouseMClickButton |= (button == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN);
g_mouseLClickButton &= !(button == GLUT_LEFT_BUTTON && state == GLUT_UP);
g_mouseRClickButton &= !(button == GLUT_RIGHT_BUTTON && state == GLUT_UP);
g_mouseMClickButton &= !(button == GLUT_MIDDLE_BUTTON && state == GLUT_UP);
g_mouseClickDown = g_mouseLClickButton || g_mouseRClickButton || g_mouseMClickButton;
if (g_pickingMode && button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
pick();
g_pickingMode = false;
cerr << "Picking mode is off" << endl;
glutPostRedisplay(); // request redisplay since the arcball will have moved
}
glutPostRedisplay();
}
static void keyboard(const unsigned char key, const int x, const int y) {
switch (key) {
case 27:
exit(0); // ESC
case 'h':
cout << " ============== H E L P ==============\n\n"
<< "h\t\thelp menu\n"
<< "s\t\tsave screenshot\n"
<< "p\t\tUse mouse to pick a part to edit\n"
<< "v\t\tCycle view\n"
<< "drag left mouse to rotate\n"
<< "a\t\tToggle display arcball\n"
<< "w\t\tWrite animation to animation.txt\n"
<< "i\t\tRead animation from animation.txt\n"
<< "<space>\t\tCopy frame to scene\n"
<< "u\t\tCopy sceneto frame\n"
<< "n\t\tCreate new frame after current frame and copy scene to it\n"
<< "d\t\tDelete frame\n"
<< ">\t\tGo to next frame\n"
<< "<\t\tGo to prev. frame\n"
<< "y\t\tPlay/Stop animation\n"
<< "9\t\tDecrease subdivision levels\n"
<< "0\t\tIncrease subdivision levels\n"
<< "b\t\tToggle subdivison surface bubbling\n"
<< "f\t\tToggle faceted shading of subdivision surface\n"
<< "7\t\tDecrease subdivision surface bubbling speed\n"
<< "8\t\tIncrease subdivision surface bubbling speed\n"
<< endl;
break;
case 's':
glFlush();
writePpmScreenshot(g_windowWidth, g_windowHeight, "out.ppm");
break;
case 'v':
{
shared_ptr<SgRbtNode> viewers[] = {g_skyNode, g_robot1Node, g_robot2Node};
for (int i = 0; i < 3; ++i) {
if (g_currentCameraNode == viewers[i]) {
g_currentCameraNode = viewers[(i+1)%3];
break;
}
}
}
break;
case 'p':
g_pickingMode = !g_pickingMode;
cerr << "Picking mode is " << (g_pickingMode ? "on" : "off") << endl;
break;
case 'm':
g_activeCameraFrame = SkyMode((g_activeCameraFrame+1) % 2);
cerr << "Editing sky eye w.r.t. " << (g_activeCameraFrame == WORLD_SKY ? "world-sky frame\n" : "sky-sky frame\n") << endl;
break;
case 'a':
g_displayArcball = !g_displayArcball;
break;
case 'u':
if (g_playingAnimation) {
cerr << "Cannot operate when playing animation" << endl;
break;
}
if (g_curKeyFrame == g_animator.keyFramesEnd()) { // only possible when frame list is empty
cerr << "Create new frame [0]." << endl;
g_curKeyFrame = g_animator.insertEmptyKeyFrameAfter(g_animator.keyFramesBegin());
g_curKeyFrameNum = 0;
}
cerr << "Copying scene graph to current frame [" << g_curKeyFrameNum << "]" << endl;
g_animator.pullKeyFrameFromSg(g_curKeyFrame);
break;
case 'n':
if (g_playingAnimation) {
cerr << "Cannot operate when playing animation" << endl;
break;
}
if (g_animator.getNumKeyFrames() != 0)
++ g_curKeyFrameNum;
g_curKeyFrame = g_animator.insertEmptyKeyFrameAfter(g_curKeyFrame);
g_animator.pullKeyFrameFromSg(g_curKeyFrame);
cerr << "Create new frame [" << g_curKeyFrameNum << "]" << endl;
break;
case ' ':
if (g_playingAnimation) {
cerr << "Cannot operate when playing animation" << endl;
break;
}
if (g_curKeyFrame != g_animator.keyFramesEnd()) {
cerr << "Loading current key frame [" << g_curKeyFrameNum << "] to scene graph" << endl;
g_animator.pushKeyFrameToSg(g_curKeyFrame);
}
else {
cerr << "No key frame defined" << endl;
}
break;
case 'd':
if (g_playingAnimation) {
cerr << "Cannot operate when playing animation" << endl;
break;
}
if (g_curKeyFrame != g_animator.keyFramesEnd()) {
Animator::KeyFrameIter newCurKeyFrame = g_curKeyFrame;
cerr << "Deleting current frame [" << g_curKeyFrameNum << "]" << endl;;
if (g_curKeyFrame == g_animator.keyFramesBegin()) {
++newCurKeyFrame;
}
else {
--newCurKeyFrame;
--g_curKeyFrameNum;