treasure_hunt_renderer.cc 43.9 KB
Newer Older
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
1
2
3
4
5
6
/*Uses code from Stackoverflow which uses the MIT license and the CC BY-SA 3.0*/
/*These licenses are compatible with Apache 2.0*/

/*
# Copyright 2016-2018 The NOMAD Developers Group
*/
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
/* Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <unistd.h>

#include "treasure_hunt_renderer.h"  // NOLINT

#include <android/log.h>
#include <assert.h>
#include <stdlib.h>
#include <cmath>
#include <random>

32
#include "NOMADVRLib/MyGL.h"
33
34
35
36
37
38
39

#include "NOMADVRLib/atoms.hpp"
#include "NOMADVRLib/ConfigFile.h"
#include "NOMADVRLib/atomsGL.h"
#include "NOMADVRLib/UnitCellShaders.h"
#include "NOMADVRLib/TessShaders.h"
#include "NOMADVRLib/polyhedron.h"
40
#include "NOMADVRLib/IsosurfacesGL.h"
41

lrz's avatar
lrz committed
42
43
#include "GoogleCardboard/aux.h"

44
#define LOG_TAG "NOMADgvrT"
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define CHECK(condition)                                                   \
  if (!(condition)) {                                                      \
    LOGE("*** CHECK FAILED at %s:%d: %s", __FILE__, __LINE__, #condition); \
    abort();                                                               \
  }

const char * configPath=0;

void eprintf( const char *fmt, ... )
{
	va_list args;
	char buffer[ 2048 ];

	va_start( args, fmt );
	vsprintf( buffer, fmt, args );
	va_end( args );

65
	LOGD("Message in NOMADgvrT");
66
67
68
69
70
71
72
	if (*fmt=='\0')
		LOGD("Empty format");
	LOGD("<%s>", buffer);
}


namespace {
73
74


Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
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
//static const float kZNear = 1.0f;
//static const float kZFar = 100.0f;
static const float kZNear = 0.01f;
static const float kZFar = 1000.0f;


static const int kCoordsPerVertex = 3;

static const uint64_t kPredictionTimeWithoutVsyncNanos = 50000000;

static std::array<float, 16> MatrixToGLArray(const gvr::Mat4f& matrix) {
  // Note that this performs a *tranpose* to a column-major matrix array, as
  // expected by GL.
  std::array<float, 16> result;
  for (int i = 0; i < 4; ++i) {
    for (int j = 0; j < 4; ++j) {
      result[j * 4 + i] = matrix.m[i][j];
    }
  }
  return result;
}

static std::array<float, 4> MatrixVectorMul(const gvr::Mat4f& matrix,
                                            const std::array<float, 4>& vec) {
  std::array<float, 4> result;
  for (int i = 0; i < 4; ++i) {
    result[i] = 0;
    for (int k = 0; k < 4; ++k) {
      result[i] += matrix.m[i][k] * vec[k];
    }
  }
  return result;
}

static gvr::Mat4f MatrixMul(const gvr::Mat4f& matrix1,
                            const gvr::Mat4f& matrix2) {
  gvr::Mat4f result;
  for (int i = 0; i < 4; ++i) {
    for (int j = 0; j < 4; ++j) {
      result.m[i][j] = 0.0f;
      for (int k = 0; k < 4; ++k) {
        result.m[i][j] += matrix1.m[i][k] * matrix2.m[k][j];
      }
    }
  }
  return result;
}

static gvr::Mat4f PerspectiveMatrixFromView(const gvr::Rectf& fov, float z_near,
                                            float z_far) {
  gvr::Mat4f result;
  const float x_left = -std::tan(fov.left * M_PI / 180.0f) * z_near;
  const float x_right = std::tan(fov.right * M_PI / 180.0f) * z_near;
  const float y_bottom = -std::tan(fov.bottom * M_PI / 180.0f) * z_near;
  const float y_top = std::tan(fov.top * M_PI / 180.0f) * z_near;
  const float zero = 0.0f;

  assert(x_left < x_right && y_bottom < y_top && z_near < z_far &&
         z_near > zero && z_far > zero);
  const float X = (2 * z_near) / (x_right - x_left);
  const float Y = (2 * z_near) / (y_top - y_bottom);
  const float A = (x_right + x_left) / (x_right - x_left);
  const float B = (y_top + y_bottom) / (y_top - y_bottom);
  const float C = (z_near + z_far) / (z_near - z_far);
  const float D = (2 * z_near * z_far) / (z_near - z_far);

  for (int i = 0; i < 4; ++i) {
    for (int j = 0; j < 4; ++j) {
      result.m[i][j] = 0.0f;
    }
  }
  result.m[0][0] = X;
  result.m[0][2] = A;
  result.m[1][1] = Y;
  result.m[1][2] = B;
  result.m[2][2] = C;
  result.m[2][3] = D;
  result.m[3][2] = -1;

  return result;
}

static gvr::Rectf ModulateRect(const gvr::Rectf& rect, float width,
                               float height) {
  gvr::Rectf result = {rect.left * width, rect.right * width,
                       rect.bottom * height, rect.top * height};
  return result;
}

static gvr::Recti CalculatePixelSpaceRect(const gvr::Sizei& texture_size,
                                          const gvr::Rectf& texture_rect) {
  const float width = static_cast<float>(texture_size.width);
  const float height = static_cast<float>(texture_size.height);
  const gvr::Rectf rect = ModulateRect(texture_rect, width, height);
  const gvr::Recti result = {
      static_cast<int>(rect.left), static_cast<int>(rect.right),
      static_cast<int>(rect.bottom), static_cast<int>(rect.top)};
  return result;
}

// Generate a random floating point number between 0 and 1.
static float RandomUniformFloat() {
  static std::random_device random_device;
  static std::mt19937 random_generator(random_device());
  static std::uniform_real_distribution<float> random_distribution(0, 1);
  return random_distribution(random_generator);
}

static void CheckGLError(const char* label) {
  int gl_error = glGetError();
  if (gl_error != GL_NO_ERROR) {
    LOGW("GL error @ %s: %d", label, gl_error);
    // Crash immediately to make OpenGL errors obvious.
    abort();
  }
}

static gvr::Sizei HalfPixelCount(const gvr::Sizei& in) {
  // Scale each dimension by sqrt(2)/2 ~= 7/10ths.
  gvr::Sizei out;
  out.width = (7 * in.width) / 10;
  out.height = (7 * in.height) / 10;
  return out;
}

static gvr::Mat4f ControllerQuatToMatrix(const gvr::ControllerQuat& quat) {
  gvr::Mat4f result;
  const float x = quat.qx;
  const float x2 = quat.qx * quat.qx;
  const float y = quat.qy;
  const float y2 = quat.qy * quat.qy;
  const float z = quat.qz;
  const float z2 = quat.qz * quat.qz;
  const float w = quat.qw;
  const float xy = quat.qx * quat.qy;
  const float xz = quat.qx * quat.qz;
  const float xw = quat.qx * quat.qw;
  const float yz = quat.qy * quat.qz;
  const float yw = quat.qy * quat.qw;
  const float zw = quat.qz * quat.qw;

  const float m11 = 1.0f - 2.0f * y2 - 2.0f * z2;
  const float m12 = 2.0f * (xy - zw);
  const float m13 = 2.0f * (xz + yw);
  const float m21 = 2.0f * (xy + zw);
  const float m22 = 1.0f - 2.0f * x2 - 2.0f * z2;
  const float m23 = 2.0f * (yz - xw);
  const float m31 = 2.0f * (xz - yw);
  const float m32 = 2.0f * (yz + xw);
  const float m33 = 1.0f - 2.0f * x2 - 2.0f * y2;

  return {{{m11, m12, m13, 0.0f},
           {m21, m22, m23, 0.0f},
           {m31, m32, m33, 0.0f},
           {0.0f, 0.0f, 0.0f, 1.0f}}};
}

static inline float VectorNorm(const std::array<float, 4>& vect) {
  return std::sqrt(vect[0] * vect[0] + vect[1] * vect[1] + vect[2] * vect[2]);
}

static float VectorInnerProduct(const std::array<float, 4>& vect1,
                                const std::array<float, 4>& vect2) {
  float product = 0;
  for (int i = 0; i < 3; i++) {
    product += vect1[i] * vect2[i];
  }
  return product;
}
}  // anonymous namespace

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
void TreasureHuntRenderer::keyPress (int k)
{ //X=99, Y=100, A=96, B=97
//UP=19, DOWN=20, LEFT=21, RIGHT=22, 
//https://developer.android.com/reference/android/view/KeyEvent.html
switch (k) {
	case 19:
		currentSet++;
		if (currentSet>TIMESTEPS-1)
	                currentSet=0;
		break;
	case 20:
		currentSet--;
		if (currentSet<0) 
			currentSet=TIMESTEPS-1;
		break;
	case 21:
		currentIso++;
		if (currentIso>ISOS)
			currentIso=0;
		break;
	case 22:
		currentIso--;
		if (currentIso<0)
			currentIso=ISOS;
		break;
	case 99: 
		animateTimesteps=!animateTimesteps;
		break;
	case 96:
		animateMovement=!animateMovement;
		
}
}

281
282
void TreasureHuntRenderer::loadConfigFile(void)
{
283
284
	if (configPath!=nullptr)
		eprintf ("configPath=<%s>", configPath);
285
286
	else
		eprintf ("configPath is null");
287

288
289
290
291
292
293
	if (TMPDIR!=nullptr)
		eprintf ("TMPDIR=<%s>", TMPDIR);
	else
		eprintf ("TMPDIR is null");
	
	std::string s(configPath);
294
295
296
	chdir(s.substr(0, s.find_last_of("\\/")).c_str());
	

297
	if ((error=::loadConfigFile(configPath))<0) {
298
299
		if (-100<error) {
			eprintf(loadConfigFileErrors[-error]);
300
			eprintf("Config file reading error");
301
302
		} else if (-200<error){
			eprintf(readAtomsXYZErrors[-error-100]);
303
			eprintf("XYZ file reading error");
304
305
		} else if (-300<error) {
			eprintf(readAtomsCubeErrors[-error-200]);
306
307
			eprintf("Cube file reading error");
		} else {
308
			eprintf(readAtomsJsonErrors[-error-300]);
309
310
311
312
313
314
315
			eprintf("Json reading error");
		}	
	}
	if (!solid) {
		LOGD("No atom glyph specified, using Icosahedron");
		solid=new Solid(Solid::Type::Icosahedron);
	}
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
316
317
318
319
320
321

	UserTranslation[0]=userpos[0]; //because of rotation in X to make Z vertical
	UserTranslation[1]=-userpos[2];
	UserTranslation[2]=userpos[1];
//	for (int i=0;i<3;i++)
// 		UserTranslation[i]=userpos[i];
322
323

//	LOGD("UT=%f, %f, %f\n", UserTranslation[0], UserTranslation[1], UserTranslation[2]);
324
325
326
327
328
329
330
331
332
333
334
}

TreasureHuntRenderer::TreasureHuntRenderer(
    gvr_context* gvr_context, std::unique_ptr<gvr::AudioApi> gvr_audio_api)
    : gvr_api_(gvr::GvrApi::WrapNonOwned(gvr_context)),
      scratch_viewport_(gvr_api_->CreateBufferViewport()),
      gvr_controller_api_(nullptr),
      gvr_viewer_type_(gvr_api_->GetViewerType()) {

	loadConfigFile();
	//eprintf("after config load, timesteps=%d", TIMESTEPS);
335
	
336
337


338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
  ResumeControllerApiAsNeeded();
  if (gvr_viewer_type_ == GVR_VIEWER_TYPE_CARDBOARD) {
    LOGD("Viewer type: CARDBOARD");
  } else if (gvr_viewer_type_ == GVR_VIEWER_TYPE_DAYDREAM) {
    LOGD("Viewer type: DAYDREAM");
  } else {
    LOGE("Unexpected viewer type.");
  }
}

TreasureHuntRenderer::~TreasureHuntRenderer() {
	glDeleteProgram(AtomsP);
	glDeleteProgram(UnitCellP);

	glDeleteTextures(2, textures);
}

355
356
357
358
359
360
const char * ErrorsGL[] = {
	"Failure compiling Unit Cell Shader", //-401
	"Failure compiling Atom Shader NoTess", //-402;

};

361
362
363
364
void TreasureHuntRenderer::InitializeGl() {
  gvr_api_->InitializeGl();

glGenTextures(2, textures);
365
glGenTextures(2+ZLAYERS, textDepthPeeling);
366
367
368
369
370
371
372
373
374
375
376
377
378
    //white
    unsigned char data2[4]={255,255,255,255}; //white texture for non-textured meshes
    glBindTexture(GL_TEXTURE_2D, textures[0]);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, data2);

    // Create the programs
	//Leave atoms until we check if android 7 has gles 3.2 or if we use the old icosahedron method with no tesselation
	if (!PrepareUnitCellShader (&UnitCellP, &UnitCellMatrixLoc, &UnitCellColourLoc)) {
		eprintf("OneTimeInit, failure compiling Unit Cell Shader");
379
		error=-401;
380
381
382
383
384
385
		return ;
	}
	
	//rgh: for now, we don't have any tess-ready phones
	//if (!PrepareAtomShader(&AtomsP, &AtomMatrixLoc)) {
		hasTess=false;
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
386
		if (!PrepareAtomShaderNoTess(&AtomsP, &AtomMatrixLoc, &totalatomsLocation)) {
387
			error=-402;
388
			eprintf ("PrepareAtomShaderNoTess failed");
389
		}
390
391
392
393
394
395
	//};

	//atom texture
	int e;
	
	e=atomTexture(textures[1]);
396
	if (e!=GL_NO_ERROR) {
397
		eprintf ("atomTexture error %d", e);
398
399
		error=-403;
	}
400

401
	e=SetupAtoms(&AtomTVAO, &AtomTBuffer, &BondIndices);
402
	if (e!=GL_NO_ERROR) {
403
		eprintf ("SetupAtoms error %d", e);
404
405
		error=-404;
	}
406
407
408
409

	if (!hasTess)
		e=SetupAtomsNoTess(&AtomVAO, &AtomBuffer, &AtomIndices);

410
	if (e!=GL_NO_ERROR) {
411
		eprintf ("SetupAtomsNoTess error %d, tess=%d", e, hasTess);
412
413
		error=-405;
	}
414
	e=SetupUnitCell(&UnitCellVAO, &UnitCellBuffer, &UnitCellIndexBuffer);
415
	if (e!=GL_NO_ERROR) {
416
		eprintf ("SetupUnitCell error %d", e);
417
418
		error=-406;
	}
419
420
421
422
423
	e=SetupMarkerNoTess(&MarkerVAO, &MarkerVertBuffer, &MarkerIndexBuffer);
	if (e!=GL_NO_ERROR) {
		eprintf ("SetupMarkerNoTess error %d", e);
		error=-411;
	}
424

425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
  // Because we are using 2X MSAA, we can render to half as many pixels and
  // achieve similar quality.
  render_size_ =
      HalfPixelCount(gvr_api_->GetMaximumEffectiveRenderTargetSize());
  std::vector<gvr::BufferSpec> specs;

  specs.push_back(gvr_api_->CreateBufferSpec());
  specs[0].SetColorFormat(GVR_COLOR_FORMAT_RGBA_8888);
  specs[0].SetDepthStencilFormat(GVR_DEPTH_STENCIL_FORMAT_DEPTH_16);
  specs[0].SetSize(render_size_);
  specs[0].SetSamples(2);

  swapchain_.reset(new gvr::SwapChain(gvr_api_->CreateSwapChain(specs)));

  viewport_list_.reset(
      new gvr::BufferViewportList(gvr_api_->CreateEmptyBufferViewportList()));

442
443
444
   if (ISOS || markers) {
	PrepareISOShader(&ISOP, &ISOMatrixLoc);
   }
445
446
//isosurfaces
	if (ISOS) {
447
		currentIso=ISOS;
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
		//rgh: FIXME Additive blending for android; do not need most of these textures
		//additive blending means white background makes everything white
		float m=BACKGROUND[0];
		m=std::max(m, BACKGROUND[1]);
		m=std::max(m, BACKGROUND[2]);
		if (m>0.2f) { //make background darker, preserving colour, so additive blending works
			for (int i=0;i<3;i++)
				BACKGROUND[i]*=0.2f / m;
		}

		e=SetupDepthPeeling(render_size_.width, render_size_.height, ZLAYERS, 
			textDepthPeeling, &peelingFramebuffer);
		if (!e) {
			eprintf("Error setting up DepthPeeling\n");
			error=-407;
		}


		if (GL_NO_ERROR!=(e=PrepareISOTransShader (&TransP, 
			&TransMatrixLoc, &BlendP)))
		{
			eprintf( "Error Preparing Transparency shader, %d\n", e );
			error=-408;
		}
		SetupBlending(&BlendVAO, &BlendBuffer, &BlendIndices);
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496

		std::vector<float> vertices;
#ifndef INDICESGL32
		std::vector<short> indices;
#else
		std::vector<GLuint> indices;
#endif
		numISOIndices=new int[TIMESTEPS*ISOS];
		ISOVAO=new GLuint[TIMESTEPS*ISOS];
		ISOBuffer=new GLuint[TIMESTEPS*ISOS];
		ISOIndices=new GLuint[TIMESTEPS*ISOS];

		glGenBuffers(TIMESTEPS*ISOS, ISOBuffer);
		glGenVertexArrays(TIMESTEPS*ISOS, ISOVAO);
		glGenBuffers(TIMESTEPS*ISOS, ISOIndices);

		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("opengl error %d, glGenBuffers\n", e);

		char tmpname[250];
		int timestep=1;
		for (int p = 0; p < TIMESTEPS*ISOS; p++) {
			sprintf(tmpname, "%s%d-%s.ply", PATH, timestep, 
				plyfiles[p % ISOS]);
497
498
			gvr::Mat4f trans;
			gvr::Mat4f matFinal, matcubetrans, mvs, sc, sctrans;
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
499

500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
		if (voxelSize[0]!=-1) {
			mvs=ScalingMatrix(scaling/(float)voxelSize[0], scaling/(float)voxelSize[1],
				scaling/(float)voxelSize[2]);
			matcubetrans=TranslationMatrix(cubetrans);
			gvr::Mat4f abcm {abc[0][0], abc[0][1], abc[0][2], 0,
					abc[1][0], abc[1][1], abc[1][2], 0,
					abc[2][0], abc[2][1], abc[2][2], 0,
					0, 0, 0, 1};
			sc=ScalingMatrix(supercell);
			sctrans=TranslationMatrix(-translations[p%ISOS][2], 
					-translations[p%ISOS][1], -translations[p%ISOS][0]);
			matFinal = MatrixMul(abcm,sctrans);
			matFinal=MatrixMul(matFinal,sc);
			matFinal=MatrixMul(matFinal,mvs);
		} else {
515
			for (int i=0;i<4;i++)
516
				for(int j=0;j<4;j++)
517
518
519
520
					matFinal.m[i][j]=(i==j);
			for (int i=0;i<3;i++)
				matFinal.m[i][3]=translations[p%ISOS][i];

521
522
523
			trans.m[0][0]=scaling;trans.m[0][1]=0;trans.m[0][2]=0; trans.m[0][3]=0;
			trans.m[1][0]=0;trans.m[1][1]=scaling;trans.m[1][2]=0;trans.m[1][3]=0; 
			trans.m[2][0]=0;trans.m[2][1]=0;trans.m[2][2]=scaling; trans.m[2][3]=0;
524
525
			trans.m[3][0]=0;trans.m[3][1]=0;trans.m[3][2]=0; trans.m[3][3]=1;
			matFinal=MatrixMul(trans, matFinal);
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
			float mat[16];
			for (int i=0;i<4;i++)
				for (int j=0;j<4;j++)
					mat[j*4+i]=matFinal.m[i][j];
			if (!AddModelToScene(mat, vertices, indices,
	                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              			tmpname, false, isocolours[p%ISOS][0]<0, p%ISOS))
			{
				eprintf("Error loading ply file %s\n", tmpname);
				//return; 
			}
#ifndef INDICESGL32
			if (vertices.size() > 65535 * numComponents)
			{
				eprintf("Mesh has more than 64k vertices (%d), unsupported\n", vertdataarray[currentlod][p].size() / numComponents);
				return;
			}
#endif
			numISOIndices[p] = indices.size();
			if (GL_NO_ERROR!=PrepareGLiso(ISOVAO[p], ISOBuffer[p], 
				vertices, ISOIndices[p], indices))
				eprintf ("PrepareGLiso, GL error");
			
			vertices.clear();
			indices.clear();

			if (p % ISOS == ISOS - 1) {
553
				//eprintf ("timestep %d", timestep);
554
555
556
557
558
				timestep++;
			}
		}
	}

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


}

void TreasureHuntRenderer::ResumeControllerApiAsNeeded() {
  switch (gvr_viewer_type_) {
    case GVR_VIEWER_TYPE_CARDBOARD:
      gvr_controller_api_.reset();
      break;
    case GVR_VIEWER_TYPE_DAYDREAM:
      if (!gvr_controller_api_) {
        // Initialized controller api.
        gvr_controller_api_.reset(new gvr::ControllerApi);
        CHECK(gvr_controller_api_);
        CHECK(gvr_controller_api_->Init(gvr::ControllerApi::DefaultOptions(),
                                        gvr_api_->cobj()));
      }
      gvr_controller_api_->Resume();
      break;
    default:
      LOGE("unexpected viewer type.");
      break;
  }
}

void TreasureHuntRenderer::ProcessControllerInput() {
  const int old_status = gvr_controller_state_.GetApiStatus();
  const int old_connection_state = gvr_controller_state_.GetConnectionState();

  // Read current controller state.
  gvr_controller_state_.Update(*gvr_controller_api_);

  // Print new API status and connection state, if they changed.
  if (gvr_controller_state_.GetApiStatus() != old_status ||
      gvr_controller_state_.GetConnectionState() != old_connection_state) {
    LOGD("TreasureHuntApp: controller API status: %s, connection state: %s",
         gvr_controller_api_status_to_string(
             gvr_controller_state_.GetApiStatus()),
         gvr_controller_connection_state_to_string(
             gvr_controller_state_.GetConnectionState()));
  }

  // Trigger click event if app/click button is clicked.
  if (gvr_controller_state_.GetButtonDown(GVR_CONTROLLER_BUTTON_APP) ||
      gvr_controller_state_.GetButtonDown(GVR_CONTROLLER_BUTTON_CLICK)) {
//    OnTriggerEvent();
  }
}

void TreasureHuntRenderer::DrawFrame() {
  if (gvr_viewer_type_ == GVR_VIEWER_TYPE_DAYDREAM) {
    ProcessControllerInput();
  }

613
if (animateTimesteps) {
614
615
616
617
618
619
620
621
622
623
	if (animationspeed>1)
		currentSet+=animationspeed;
	else {
		static float current=0;
		current+=animationspeed;
		if (current>1) {
			currentSet++;
			current=0;
		}
	}
624
625
            if (currentSet>TIMESTEPS-1)
                currentSet=0;
626
	}
627
628
629
630
631
632
633
634
635
636

  PrepareFramebuffer();
  gvr::Frame frame = swapchain_->AcquireFrame();

  // A client app does its rendering here.
  gvr::ClockTimePoint target_time = gvr::GvrApi::GetTimePointNow();
  target_time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos;

  head_view_ = gvr_api_->GetHeadSpaceFromStartSpaceRotation(target_time);

637
if (animateMovement) {
638
639
	const float speed=0.01;
	gvr::Mat4f inv=invert(head_view_);
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
640
641

	std::array<float, 4> dir({0,0,1,0}); // {0,0,1,0}
642
	std::array<float, 4> dir2=MatrixVectorMul(inv, dir);
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
643
	
644
	for (int i=0;i<3;i++)
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
645
646
		UserTranslation[i]+=dir2[i]*speed*movementspeed;

647
648
}

649

Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
650
	LOGD("UT=%f, %f, %f\n", UserTranslation[0], UserTranslation[1], UserTranslation[2]);
651
	//LOGD("MovementSpeed=%f\n", movementspeed);
652

653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
  gvr::Mat4f left_eye_matrix = gvr_api_->GetEyeFromHeadMatrix(GVR_LEFT_EYE);
  gvr::Mat4f right_eye_matrix = gvr_api_->GetEyeFromHeadMatrix(GVR_RIGHT_EYE);
  gvr::Mat4f left_eye_view = MatrixMul(left_eye_matrix, head_view_);
  gvr::Mat4f right_eye_view = MatrixMul(right_eye_matrix, head_view_);

  viewport_list_->SetToRecommendedBufferViewports();
  gvr::BufferViewport reticle_viewport = gvr_api_->CreateBufferViewport();

  glEnable(GL_DEPTH_TEST);
  glEnable(GL_CULL_FACE);
  glDisable(GL_SCISSOR_TEST);
  glDisable(GL_BLEND);

  // Draw the world.
  frame.BindBuffer(0);
668
  if (error<0) {
669
	//rgh: FIXME, add textures with messages here
670
		if (-100<error) { //error with ncfg file
671
			glClearColor(1.f, 0.f, 0.f, 1.f); 
672
		} else if (-200<error){//error loading xyz
673
			glClearColor(0.f, 1.f, 0.f, 1.f); 
674
		} else if (-300<error) {//error loading gaussian
675
			glClearColor(0.f, 0.f, 1.f, 1.f); 
676
677
678
679
		} else if (-400<error) {//error loading encyclopedia json
			glClearColor(0.f, 1.f, 1.f, 1.f); 
		} else if (-500<error) {//error loading analytics json
			glClearColor(1.f, 1.f, 0.f, 1.f); 
680
681
682
683
		} else {
			glClearColor(1.f, 0.f, 1.f, 1.f); 
		}
  } else {
684
	glClearColor(BACKGROUND[0], BACKGROUND[1], BACKGROUND[2], 1.f);
685
686
687
  }

    // Dark background so text shows up.
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
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  viewport_list_->GetBufferViewport(0, &scratch_viewport_);
  DrawWorld(left_eye_view, scratch_viewport_);
  viewport_list_->GetBufferViewport(1, &scratch_viewport_);
  DrawWorld(right_eye_view, scratch_viewport_);
  frame.Unbind();

  // Submit frame.
  frame.Submit(*viewport_list_, head_view_);

  CheckGLError("onDrawFrame");
}

void TreasureHuntRenderer::PrepareFramebuffer() {
  // Because we are using 2X MSAA, we can render to half as many pixels and
  // achieve similar quality.
  const gvr::Sizei recommended_size =
      HalfPixelCount(gvr_api_->GetMaximumEffectiveRenderTargetSize());
  if (render_size_.width != recommended_size.width ||
      render_size_.height != recommended_size.height) {
    // We need to resize the framebuffer.
    swapchain_->ResizeBuffer(0, recommended_size);
    render_size_ = recommended_size;
  }
}

void TreasureHuntRenderer::OnPause() {
  gvr_api_->PauseTracking();
  if (gvr_controller_api_) gvr_controller_api_->Pause();
}

void TreasureHuntRenderer::OnResume() {
  gvr_api_->ResumeTracking();
  gvr_viewer_type_ = gvr_api_->GetViewerType();
  ResumeControllerApiAsNeeded();
}

/**
 * Converts a raw text file, saved as a resource, into an OpenGL ES shader.
 *
 * @param type  The type of shader we will be creating.
 * @param resId The resource ID of the raw text file.
 * @return The shader object handler.
 */
int TreasureHuntRenderer::LoadGLShader(int type, const char** shadercode) {
  int shader = glCreateShader(type);
  glShaderSource(shader, 1, shadercode, nullptr);
  glCompileShader(shader);

  // Get the compilation status.
  int compileStatus;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus);

  // If the compilation failed, delete the shader.
  if (compileStatus == 0) {
    glDeleteShader(shader);
    shader = 0;
  }

  return shader;
}

/**
 * Draws a frame for an eye.
 *
 * @param eye The eye to render. Includes all required transformations.
 */
void TreasureHuntRenderer::DrawWorld(const gvr::Mat4f& view_matrix,
                                     const gvr::BufferViewport& viewport) {
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
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
  const gvr::Recti pixel_rect =
      CalculatePixelSpaceRect(render_size_, viewport.GetSourceUv());

  glViewport(pixel_rect.left, pixel_rect.bottom,
             pixel_rect.right - pixel_rect.left,
             pixel_rect.top - pixel_rect.bottom);

  CheckGLError("World drawing setup");


  const gvr::Mat4f perspective =
      PerspectiveMatrixFromView(viewport.GetSourceFov(), kZNear, kZFar);
  modelview_ = MatrixMul(view_matrix, model_cube_);
  modelview_projection_cube_ = MatrixMul(perspective, modelview_);

  if (gvr_viewer_type_ == GVR_VIEWER_TYPE_DAYDREAM) {
    gvr::Mat4f controller_matrix =
        ControllerQuatToMatrix(gvr_controller_state_.GetOrientation());
//    DrawCursor();
  }

//glClearColor(0,0.5,0.2,1);
//glClear(GL_COLOR_BUFFER_BIT);

	//NOMAD rendering
glDisable(GL_CULL_FACE);
modelview_=view_matrix;
modelview_projection_cube_ = MatrixMul(perspective, modelview_);
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
786
787
788
789
790
791
792
793
794

//make sure we have the same coordinate system in HTC Vive and android

const gvr::Mat4f rot={.m={1,0,0,0, 	0,0,1,0,	0,-1,0,0,	0,0,0,1}};

gvr::Mat4f trans=MatrixMul (TranslationMatrix (UserTranslation), rot);
gvr::Mat4f finalMatrix=MatrixMul(modelview_projection_cube_, trans);


795
796
797
798
799
800
801
if(error)
	return;
if (has_abc) {
	RenderUnitCell(modelview_projection_cube_);
} else {
	RenderAtomTrajectories(modelview_projection_cube_);
}
802

803
if (ISOS)
804
	RenderIsos(modelview_projection_cube_, currentIso);
805
806
807
808
809
}

void TreasureHuntRenderer::RenderIsos(const gvr::Mat4f eyeViewProjection, int curDataPos)
{
GLenum e;
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
810
811
812
813
814

gvr::Mat4f trans=TranslationMatrix (UserTranslation[0], UserTranslation[1], UserTranslation[2]);
const gvr::Mat4f rot={.m={1,0,0,0, 	0,0,1,0,	0,-1,0,0,	0,0,0,1}};					
gvr::Mat4f transform = MatrixMul(eyeViewProjection, MatrixMul(trans,rot));

815
816
817
818
819
820
float t[16];
for (int i=0;i<4;i++)
	for (int j=0;j<4;j++)
		t[j*4+i]=transform.m[i][j];

glUseProgram(ISOP);
821
if ((e = glGetError()) != GL_NO_ERROR)
822
823
		eprintf("1 Gl error RenderIsos timestep =%d: %d\n", currentSet, e);
glUniformMatrix4fv(ISOMatrixLoc, 1, GL_FALSE, t);
824
if ((e = glGetError()) != GL_NO_ERROR)
825
826
827
828
829
830
		eprintf("2 Gl error RenderIsos timestep =%d: %d\n", currentSet, e);

if (curDataPos!=ISOS) {
	glBindVertexArray(ISOVAO[currentSet*ISOS+curDataPos]);
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf("3 Gl error RenderIsos timestep =%d: %d\n", currentSet, e);
831
	//eprintf ("Drawing %d vertices, isos", numISOIndices[currentSet*ISOS+curDataPos]);
832
833
834
835
	glDrawElements(GL_TRIANGLES,numISOIndices[currentSet*ISOS+curDataPos] , GL_UNSIGNED_INT, 0);
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf("4 Gl error RenderIsos timestep =%d: %d\n", currentSet, e);
} else {
836
/*transparency*/
837
838
839
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE);
	glDepthMask(GL_FALSE);
840
841
	for (int i=0;i<ISOS;i++) {
		glBindVertexArray(ISOVAO[currentSet*ISOS+i]);
842
843
844
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("5 Gl error RenderIsos timestep =%d: %d\n", currentSet, e);
		//eprintf ("Drawing %d vertices, isos", numISOIndices[currentSet*ISOS+i]);
845
		glDrawElements(GL_TRIANGLES,numISOIndices[currentSet*ISOS+i] , GL_UNSIGNED_INT, 0); 
846
847
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("6 Gl error RenderIsos timestep =%d: %d\n", currentSet, e);
848
	}
849
	glDisable(GL_BLEND);
850
	glDepthMask(GL_TRUE);
851
852
853
} //if (curDataPos!=ISOS) 
//eprintf ("end of RenderIsos");
glBindVertexArray(0);
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
void TreasureHuntRenderer::RenderMarker(const float *m) //m[16]
{
int e;
if (!markers)
	return;

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindVertexArray(MarkerVAO);
if ((e = glGetError()) != GL_NO_ERROR)
	eprintf("b %d", e);
glUseProgram(ISOP);
if ((e = glGetError()) != GL_NO_ERROR)
	eprintf("c %d", e);
glUniformMatrix4fv(ISOMatrixLoc, 1, GL_FALSE, m);
if ((e = glGetError()) != GL_NO_ERROR)
	eprintf("d %d, matrixloc=%d, program=%d", e, ISOMatrixLoc, ISOP); 
glDrawElements(GL_TRIANGLES, 3*3*MARKERSOLID::nFaces, 
#ifndef INDICESGL32				
				GL_UNSIGNED_SHORT, (void*)(currentSet*sizeof(unsigned short)*3*3*MARKERSOLID::nFaces
)
#else
				GL_UNSIGNED_INT, (void*)(currentSet*sizeof(unsigned int)*3*3*MARKERSOLID::nFaces
)
#endif
	);
if ((e = glGetError()) != GL_NO_ERROR)
	eprintf("e %d", e);
glBindVertexArray(0);
if ((e = glGetError()) != GL_NO_ERROR)
	eprintf("f %d", e);

glDisable(GL_BLEND);
}


892
893
void TreasureHuntRenderer::RenderAtoms(const float *m) //m[16]
{
894
895
	//eprintf ("RenderAtoms start numatoms %d, timestep %d", numAtoms[currentSet], currentSet);
	//eprintf ("solid nfaces %d", solid->nFaces);
896
897
898
899
900
901
902
903
904
905
	int e;
	if (numAtoms==0)
		return;
	
	if (hasTess) {
	//FIXME, unimplemented
		LOGW("FIXME, No Tess code for atoms yet!");
		return;
	} else { //no tess
		glBindVertexArray(AtomVAO[0]);
906
907
908
909
910
911
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, AtomIndices[0]);
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("1 Gl error RenderAtom timestep =%d: %d\n", currentSet, e);
		glBindBuffer(GL_ARRAY_BUFFER, AtomBuffer[0]);
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("2 Gl error RenderAtom timestep =%d: %d\n", currentSet, e);
912

913
914
915
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7*sizeof(float), (const void *)0);
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("3 Gl error RenderAtom timestep =%d: %d\n", currentSet, e);
916

917
918
919
		glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (const void *)(3*sizeof(float)));
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("4 Gl error RenderAtom timestep =%d: %d\n", currentSet, e);
920

921
922
923
		glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (const void *)(6 * sizeof(float)));
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("5 Gl error RenderAtom timestep =%d: %d\n", currentSet, e);
924
925

		glBindTexture(GL_TEXTURE_2D, textures[1]);
926
927
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("6 Gl error RenderAtom timestep =%d: %d\n", currentSet, e);
928
929

		glUseProgram(AtomsP);
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
930
		glUniform1f(totalatomsLocation, (float)getTotalAtomsInTexture());
931
932
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("7 Gl error RenderAtom timestep =%d: %d\n", currentSet, e);
933
934

		glUniformMatrix4fv(AtomMatrixLoc, 1, GL_FALSE, m);
935
936
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("8 Gl error RenderAtom timestep =%d: %d\n", currentSet, e);
937
938
939
940
941
942
943
944
945

		if (currentSet==0) {
			glDrawElements(GL_TRIANGLES, numAtoms[currentSet]* 3 * solid->nFaces, 
#ifndef INDICESGL32				
				GL_UNSIGNED_SHORT,
#else
				GL_UNSIGNED_INT,
#endif	
				0);
946
947
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("9 Gl error RenderAtom timestep =%d: %d\n", currentSet, e);
948
949
950
951
952
953
954
955
956

		} else {
			glDrawElements(GL_TRIANGLES, (numAtoms[currentSet]-numAtoms[currentSet-1]) * 3 * solid->nFaces,
#ifndef INDICESGL32				
				GL_UNSIGNED_SHORT, (void*)(numAtoms[currentSet-1]*sizeof(unsigned short)*3*solid->nFaces)
#else
				GL_UNSIGNED_INT, (void*)(numAtoms[currentSet-1]*sizeof(unsigned int)*3*solid->nFaces)
#endif
				);
957
958
			if ((e = glGetError()) != GL_NO_ERROR)
				eprintf("10 Gl error RenderAtom timestep =%d: %d\n", currentSet, e);
959
960
961
962
963
964
965
966
967

		}
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("Gl error after Render  Atom timestep =%d: %d\n", currentSet, e);
		//now cloned atoms
		if (numClonedAtoms!=0 && currentSet==0) {
			glBindVertexArray(AtomVAO[1]);
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, AtomIndices[1]);
			glBindBuffer(GL_ARRAY_BUFFER, AtomBuffer[1]);
968
969
970
			glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7*sizeof(float), (const void *)0);
			glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (const void *)(3*sizeof(float)));
			glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (const void *)(6 * sizeof(float)));
971

972
973
			if ((e = glGetError()) != GL_NO_ERROR)
				eprintf("5 Gl error RenderAtom timestep =%d: %d\n", currentSet, e);
974
975
976
977
978
979
980
981
982
983
984
985
			glDrawElements(GL_TRIANGLES, numClonedAtoms* 3 * solid->nFaces, 
#ifndef INDICESGL32				
				GL_UNSIGNED_SHORT,
#else
				GL_UNSIGNED_INT,
#endif	
				0);			
			
			
			if ((e = glGetError()) != GL_NO_ERROR)
				eprintf("Gl error after Render cloned Atom timestep =%d: %d\n", currentSet, e);
		} // painting cloned atoms
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
		//now bonds
		if (numBonds && displaybonds /*&& showAtoms*/) {
			glLineWidth(bondThickness);
			glBindVertexArray(AtomTVAO[2]);
			glUseProgram(UnitCellP);
			glUniformMatrix4fv(UnitCellMatrixLoc, 1, GL_FALSE, m);
			glUniform4fv(UnitCellColourLoc, 1, bondscolours);
			if ((e = glGetError()) != GL_NO_ERROR)
				eprintf("Gl error after Render Atom bonds uniform timestep =%d: %d\n", currentSet, e);
			if (currentSet==0||fixedAtoms)
				glDrawElements(GL_LINES, numBonds[0],  GL_UNSIGNED_INT, (void*)0);
			else
				glDrawElements(GL_LINES, numBonds[currentSet]-numBonds[currentSet-1], GL_UNSIGNED_INT, 
					(void*)(sizeof(int)*numBonds[currentSet-1]) );
			glLineWidth(1.0f);
			if ((e = glGetError()) != GL_NO_ERROR)
				eprintf("Gl error after Render Atom bonds timestep =%d: %d\n", currentSet, e);
			glBindVertexArray(0);
		}
1005
1006
1007
	} // no tess
}

1008
1009


1010
1011
1012
1013
1014
void TreasureHuntRenderer::RenderAtomTrajectories(const gvr::Mat4f eyeViewProjection)
{
int e;
if (!numAtoms)
	return;
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
1015
1016
gvr::Mat4f sc=ScalingMatrix(scaling);
gvr::Mat4f trans=TranslationMatrix (UserTranslation[0]/scaling, UserTranslation[1]/scaling, UserTranslation[2]/scaling);
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
1017
const gvr::Mat4f rot={.m={1,0,0,0, 	0,0,1,0,	0,-1,0,0,	0,0,0,1}};					
1018
//trans.translate(iPos).rotateX(-90).translate(UserPosition);
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
1019
gvr::Mat4f transform = MatrixMul(eyeViewProjection, MatrixMul(sc, MatrixMul(trans,rot)));
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
//gvr::Mat4f transform=eyeViewProjection;					
float t[16];
for (int i=0;i<4;i++)
	for (int j=0;j<4;j++)
		t[j*4+i]=transform.m[i][j];
glUseProgram(UnitCellP);
glUniformMatrix4fv(UnitCellMatrixLoc, 1, GL_FALSE, t);
if ((e = glGetError()) != GL_NO_ERROR)
	eprintf("Gl error after glUniform4fv 1 RenderAtomTrajectories: %d\n", e);
RenderAtomTrajectoriesUnitCell();
RenderAtoms(t);
1031
RenderMarker(t);
1032
1033
}

1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
void TreasureHuntRenderer::RenderAtomTrajectoriesUnitCell()
{
	//now trajectories
if (!showTrajectories)
	return;

int e;
if (!AtomTVAO) {
	LOGW("RenderAtomTrajectoriesUnitCell, no atoms");
	return;
}
glBindVertexArray(AtomTVAO[0]);
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf("1 Gl error RenderAtomTrajectoriesUnitCell: %d\n", e);
//glUseProgram(UnitCellP);
//glUniformMatrix4fv(m_nUnitCellMatrixLocation, 1, GL_FALSE, matrix);
1050
glUniform4fv(UnitCellColourLoc, 1, atomtrajectorycolour);
1051
if ((e = glGetError()) != GL_NO_ERROR)
1052
	eprintf("Gl error after glUniform4fv 2 RenderAtomTrajectoriesUnitCell: %d\n", e);
1053
1054
1055
1056
//glEnableVertexAttribArray(0);
//glDisableVertexAttribArray(1);

//LOG("atomtrajectories.size()=%d", atomtrajectories.size());
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
1057
1058
//rgh FIXME, old code which does not work with large atom sets!

1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
glBindBuffer(GL_ARRAY_BUFFER, AtomTBuffer[0]);
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf("3 Gl error RenderAtomTrajectoriesUnitCell: %d\n", e);

for (unsigned int i=0;i<atomtrajectories.size();i++) {
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 4 * sizeof(float)*numAtoms[0], 
		(const void *)(0+4*sizeof(float)*atomtrajectories[i]));
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf("4 Gl error RenderAtomTrajectoriesUnitCell: %d\n", e);

		//LOG("atomtrajectoryrestarts[%d].size()=%d", i, atomtrajectoryrestarts[i].size());
	for (unsigned int j=1;j<atomtrajectoryrestarts[i].size();j++) {
		int orig=atomtrajectoryrestarts[i][j-1];
		int count=atomtrajectoryrestarts[i][j]-atomtrajectoryrestarts[i][j-1];
		glDrawArrays(GL_LINE_STRIP, orig, count);
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf("5 Gl error RenderAtomTrajectoriesUnitCell: %d, orig=%d, count=%d\n", e, orig, count);

	} //j
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf("Gl error after Render Atom trajectories: %d\n", e);
} //i

} //OvrApp::RenderAtomTrajectoriesUnitCell()


void TreasureHuntRenderer::RenderUnitCell(const gvr::Mat4f eyeViewProjection)
{
1087
1088
1089
1090
	//eprintf ("eyeViewProjection");
	//for (int i=0;i<4;i++)
	//	for (int j=0;j<4;j++)
	//		eprintf ("%d %d = %f", i, j, eyeViewProjection.m[i][j]);
1091
	//eprintf ("RenderUnitCell, has_abc=%d", has_abc);
1092
1093
1094
1095
1096
1097
1098
	if (!has_abc)
		return;
	if (UnitCellVAO==0)
		eprintf ("Error, Unit Cell VAO not loaded");
	int e;
	
	int p[3];
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
1099
	gvr::Mat4f sc=ScalingMatrix(scaling);
1100
1101
1102
1103
1104
1105
	for (p[0]=0;p[0]<repetitions[0];(p[0])++)
		for (p[1]=0;p[1]<repetitions[1];(p[1])++)
			for (p[2]=0;p[2]<repetitions[2];(p[2])++)
				{
					float delta[3];
					GetDisplacement(p, delta);
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
1106
					/*gvr::Mat4f trans={1,0,0,delta[0]+UserTranslation[0],
1107
1108
						0,1,0,delta[1]+UserTranslation[1],
						0,0,1,delta[2]+UserTranslation[2],
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
1109
						0,0,0,1};*/
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
1110
1111
gvr::Mat4f trans=TranslationMatrix (delta[0]+UserTranslation[0]/scaling, delta[2]+UserTranslation[1]/scaling, 
	-delta[1]+UserTranslation[2]/scaling);
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
1112
1113
const gvr::Mat4f rot={.m={1,0,0,0, 	0,0,1,0,	0,-1,0,0,	0,0,0,1}};					
//trans.translate(iPos).rotateX(-90).translate(UserPosition);
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
1114
gvr::Mat4f transform = MatrixMul(eyeViewProjection, MatrixMul(sc, MatrixMul(trans,rot)));					
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
1115
1116
1117
1118



					//gvr::Mat4f transform = MatrixMul(eyeViewProjection,trans);
1119
1120
1121
1122
1123
1124
1125
1126
					//gvr::Mat4f transform=eyeViewProjection;					
					float t[16];
					for (int i=0;i<4;i++)
						for (int j=0;j<4;j++)
							t[j*4+i]=transform.m[i][j];
					glUseProgram(UnitCellP);
					glUniformMatrix4fv(UnitCellMatrixLoc, 1, GL_FALSE, t);
					if ((e = glGetError()) != GL_NO_ERROR)
Ruben Jesus Garcia Hernandez's avatar
Ruben Jesus Garcia Hernandez committed
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
						eprintf("Gl error after glUniform4fv 1 RenderUnitCell: %d\n", e);
					if (displayunitcell) {
						glUniform4fv(UnitCellColourLoc, 1, unitcellcolour);
						if ((e = glGetError()) != GL_NO_ERROR)
							eprintf("Gl error after glUniform4fv 2 RenderUnitCell: %d\n", e);
						glBindVertexArray(UnitCellVAO);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, UnitCellIndexBuffer);
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("1 Gl error RenderAtom timestep =%d: %d\n", currentSet, e);
		glBindBuffer(GL_ARRAY_BUFFER, UnitCellBuffer);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (const void *)(0));
		glEnableVertexAttribArray(0);
		glDisableVertexAttribArray(1);
		glDisableVertexAttribArray(2);
		glDisableVertexAttribArray(3);
						if ((e = glGetError()) != GL_NO_ERROR)
							eprintf("Gl error after glBindVertexArray RenderUnitCell: %d\n", e);
						glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, 0);
						//glDrawElements(GL_TRIANGLES, 24, GL_UNSIGNED_INT, 0);
						if ((e = glGetError()) != GL_NO_ERROR)
							eprintf("Gl error after RenderUnitCell: %d\n", e);
					}
1149
1150
1151
					//atom trajectories
					RenderAtomTrajectoriesUnitCell();
					RenderAtoms(t);
1152
					RenderMarker(t);
1153
1154
1155
1156
				}
}

void TreasureHuntRenderer::OnTriggerEvent() {
1157
	animateMovement=!animateMovement;
1158
1159
}