add tinygltfloader

This commit is contained in:
Hartmut Seichter 2019-01-10 22:07:45 +01:00
parent 5160ec4b0b
commit 4b695ecaf6
25 changed files with 10805 additions and 0 deletions

View file

@ -0,0 +1,4 @@
#ifndef BUFFER_HPP
#define BUFFER_HPP
#endif // BUFFER_HPP

View file

@ -0,0 +1,7 @@
---
BasedOnStyle: LLVM
IndentWidth: 2
TabWidth: 2
UseTab: Never
BreakBeforeBraces: Attach
Standard: Cpp03

View file

@ -0,0 +1,10 @@
language: cpp
compiler: gcc
before_install:
- sudo apt-get update -qq -y
script:
- make
- ./loader_test box.gltf

View file

@ -0,0 +1,2 @@
all:
g++ -Wall -Werror -g -O2 -o loader_test test.cc

View file

@ -0,0 +1,93 @@
# Tiny glTF loader, header only C++ glTF parsing library.
`TinyGLTFLoader` is a header only C++ glTF https://github.com/KhronosGroup/glTF parsing library
![](images/glview_duck.png)
[![Build Status](https://travis-ci.org/syoyo/tinygltfloader.svg?branch=master)](https://travis-ci.org/syoyo/tinygltfloader)
[![Build status](https://ci.appveyor.com/api/projects/status/i5ku97hf0r0quti3?svg=true)](https://ci.appveyor.com/project/syoyo/tinygltfloader)
## Features
* Portable C++. C++-98 with STL dependency only.
* Moderate parsing time and memory consumption.
* glTF specification v1.0.0
* Buffers
* [x] Parse BASE64 encoded embedded buffer fata(DataURI).
* [x] Load `.bin` file.
* Image(Using stb_image)
* [x] Parse BASE64 encoded embedded image fata(DataURI).
* [x] Load external image file.
* [x] PNG(8bit only)
* [x] JPEG(8bit only)
* [x] BMP
* [x] GIF
## Limitation
Currently, TinyGLTFLoader only loads nodes and geometry(mesh/buffer) data.
## Examples
* [glview](examples/glview) : Simple glTF geometry viewer.
## TODOs
* [ ] Support multiple scenes in `.gltf`
* [ ] Parse `animation`, `program`, `sampler`, `shader`, `technique`, `texture`
* [ ] Compression/decompression(Open3DGC, etc)
* [ ] Support `extensions` and `extras` property
* [ ] HDR image
* [ ] Binary glTF.
## License
TinyGLTFLoader is licensed under 2-clause BSD.
TinyGLTFLoader uses the following third party libraries.
* picojson.h : Copyright 2009-2010 Cybozu Labs, Inc. Copyright 2011-2014 Kazuho Oku
* base64 : Copyright (C) 2004-2008 René Nyffenegger
* stb_image.h : v2.08 - public domain image loader - http://nothings.org/stb_image.h
## Build and example
Copy `stb_image.h`, `picojson.h` and `tiny_gltf_loader.h` to your project.
```
// Define these only in *one* .cc file.
#define TINYGLTF_LOADER_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#include "tiny_gltf_loader.h"
using namespace tinygltf;
Scene scene;
TinyGLTFLoader loader;
std::string err;
bool ret = loader.LoadFromFile(scene, err, argv[1]);
if (!err.empty()) {
printf("Err: %s\n", err.c_str());
}
if (!ret) {
printf("Failed to parse glTF\n");
return -1;
}
```
## Running tests.
### Setup
Python 2.6 or 2.7 required.
Git clone https://github.com/KhronosGroup/glTF to your local dir.
### Run test
After building `loader_test`, edit `test_runner.py`, then,
$ python test_runner.py

View file

@ -0,0 +1,12 @@
version: 0.9.{build}
# scripts that runs after repo cloning.
install:
- vcsetup.bat
platform: x64
configuration: Release
build:
parallel: true
project: TinyGLTFLoaderSolution.sln

View file

@ -0,0 +1,267 @@
{
"accessors": {
"accessor_21": {
"bufferView": "bufferView_29",
"byteOffset": 0,
"byteStride": 0,
"componentType": 5123,
"count": 36,
"type": "SCALAR"
},
"accessor_23": {
"bufferView": "bufferView_30",
"byteOffset": 0,
"byteStride": 12,
"componentType": 5126,
"count": 24,
"max": [
0.5,
0.5,
0.5
],
"min": [
-0.5,
-0.5,
-0.5
],
"type": "VEC3"
},
"accessor_25": {
"bufferView": "bufferView_30",
"byteOffset": 288,
"byteStride": 12,
"componentType": 5126,
"count": 24,
"max": [
1,
1,
1
],
"min": [
-1,
-1,
-1
],
"type": "VEC3"
},
"accessor_27": {
"bufferView": "bufferView_30",
"byteOffset": 576,
"byteStride": 8,
"componentType": 5126,
"count": 24,
"max": [
1,
1
],
"min": [
0,
0
],
"type": "VEC2"
}
},
"animations": {},
"asset": {
"generator": "collada2gltf@ceec062e3d5793f2f249f53cbd843aee382ad40b",
"premultipliedAlpha": true,
"profile": {
"api": "WebGL",
"version": "1.0.2"
},
"version": 1
},
"bufferViews": {
"bufferView_29": {
"buffer": "box",
"byteLength": 72,
"byteOffset": 0,
"target": 34963
},
"bufferView_30": {
"buffer": "box",
"byteLength": 768,
"byteOffset": 72,
"target": 34962
}
},
"buffers": {
"box": {
"byteLength": 840,
"type": "arraybuffer",
"uri": "data:application/octet-stream;base64,AAABAAIAAwACAAEABAAFAAYABwAGAAUACAAJAAoACwAKAAkADAANAA4ADwAOAA0AEAARABIAEwASABEAFAAVABYAFwAWABUAAAAAvwAAAL8AAAA/AAAAPwAAAL8AAAA/AAAAvwAAAD8AAAA/AAAAPwAAAD8AAAA/AAAAPwAAAL8AAAA/AAAAvwAAAL8AAAA/AAAAPwAAAL8AAAC/AAAAvwAAAL8AAAC/AAAAPwAAAD8AAAA/AAAAPwAAAL8AAAA/AAAAPwAAAD8AAAC/AAAAPwAAAL8AAAC/AAAAvwAAAD8AAAA/AAAAPwAAAD8AAAA/AAAAvwAAAD8AAAC/AAAAPwAAAD8AAAC/AAAAvwAAAL8AAAA/AAAAvwAAAD8AAAA/AAAAvwAAAL8AAAC/AAAAvwAAAD8AAAC/AAAAvwAAAL8AAAC/AAAAvwAAAD8AAAC/AAAAPwAAAL8AAAC/AAAAPwAAAD8AAAC/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AACAPgAAAAAAAIA+oKqqPgAAAD8AAAAAAAAAP6Cqqj4AAIA+oKqqPgAAAACgqqo+AACAPrCqKj8AAAAAsKoqPwAAAD+gqqo+AACAPqCqqj4AAAA/sKoqPwAAgD6wqio/AABAP6Cqqj4AAAA/oKqqPgAAQD+wqio/AAAAP7CqKj8AAIA/oKqqPgAAQD+gqqo+AACAP7CqKj8AAEA/sKoqPwAAgD4AAIA/AAAAPwAAgD8AAIA+sKoqPwAAAD+wqio/"
}
},
"materials": {
"Effect-Red": {
"name": "Red",
"technique": "technique0",
"values": {
"diffuse": [
0.8,
0,
0,
1
],
"shininess": 256,
"specular": [
0.2,
0.2,
0.2,
1
]
}
}
},
"meshes": {
"Geometry-mesh002": {
"name": "Mesh",
"primitives": [
{
"attributes": {
"NORMAL": "accessor_25",
"POSITION": "accessor_23",
"TEXCOORD_0": "accessor_27"
},
"indices": "accessor_21",
"material": "Effect-Red",
"mode": 4
}
]
}
},
"nodes": {
"Geometry-mesh002Node": {
"children": [],
"matrix": [
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
],
"meshes": [
"Geometry-mesh002"
],
"name": "Mesh"
},
"node_1": {
"children": [
"Geometry-mesh002Node"
],
"matrix": [
1,
0,
0,
0,
0,
0,
-1,
0,
0,
1,
0,
0,
0,
0,
0,
1
],
"name": "Y_UP_Transform"
}
},
"programs": {
"program_0": {
"attributes": [
"a_normal",
"a_position"
],
"fragmentShader": "box0FS",
"vertexShader": "box0VS"
}
},
"scene": "defaultScene",
"scenes": {
"defaultScene": {
"nodes": [
"node_1"
]
}
},
"shaders": {
"box0FS": {
"type": 35632,
"uri": "data:text/plain;base64,cHJlY2lzaW9uIGhpZ2hwIGZsb2F0Owp2YXJ5aW5nIHZlYzMgdl9ub3JtYWw7CnVuaWZvcm0gdmVjNCB1X2RpZmZ1c2U7CnVuaWZvcm0gdmVjNCB1X3NwZWN1bGFyOwp1bmlmb3JtIGZsb2F0IHVfc2hpbmluZXNzOwp2b2lkIG1haW4odm9pZCkgewp2ZWMzIG5vcm1hbCA9IG5vcm1hbGl6ZSh2X25vcm1hbCk7CnZlYzQgY29sb3IgPSB2ZWM0KDAuLCAwLiwgMC4sIDAuKTsKdmVjNCBkaWZmdXNlID0gdmVjNCgwLiwgMC4sIDAuLCAxLik7CnZlYzQgc3BlY3VsYXI7CmRpZmZ1c2UgPSB1X2RpZmZ1c2U7CnNwZWN1bGFyID0gdV9zcGVjdWxhcjsKZGlmZnVzZS54eXogKj0gbWF4KGRvdChub3JtYWwsdmVjMygwLiwwLiwxLikpLCAwLik7CmNvbG9yLnh5eiArPSBkaWZmdXNlLnh5ejsKY29sb3IgPSB2ZWM0KGNvbG9yLnJnYiAqIGRpZmZ1c2UuYSwgZGlmZnVzZS5hKTsKZ2xfRnJhZ0NvbG9yID0gY29sb3I7Cn0K"
},
"box0VS": {
"type": 35633,
"uri": "data:text/plain;base64,cHJlY2lzaW9uIGhpZ2hwIGZsb2F0OwphdHRyaWJ1dGUgdmVjMyBhX3Bvc2l0aW9uOwphdHRyaWJ1dGUgdmVjMyBhX25vcm1hbDsKdmFyeWluZyB2ZWMzIHZfbm9ybWFsOwp1bmlmb3JtIG1hdDMgdV9ub3JtYWxNYXRyaXg7CnVuaWZvcm0gbWF0NCB1X21vZGVsVmlld01hdHJpeDsKdW5pZm9ybSBtYXQ0IHVfcHJvamVjdGlvbk1hdHJpeDsKdm9pZCBtYWluKHZvaWQpIHsKdmVjNCBwb3MgPSB1X21vZGVsVmlld01hdHJpeCAqIHZlYzQoYV9wb3NpdGlvbiwxLjApOwp2X25vcm1hbCA9IHVfbm9ybWFsTWF0cml4ICogYV9ub3JtYWw7CmdsX1Bvc2l0aW9uID0gdV9wcm9qZWN0aW9uTWF0cml4ICogcG9zOwp9Cg=="
}
},
"skins": {},
"techniques": {
"technique0": {
"attributes": {
"a_normal": "normal",
"a_position": "position"
},
"parameters": {
"diffuse": {
"type": 35666
},
"modelViewMatrix": {
"semantic": "MODELVIEW",
"type": 35676
},
"normal": {
"semantic": "NORMAL",
"type": 35665
},
"normalMatrix": {
"semantic": "MODELVIEWINVERSETRANSPOSE",
"type": 35675
},
"position": {
"semantic": "POSITION",
"type": 35665
},
"projectionMatrix": {
"semantic": "PROJECTION",
"type": 35676
},
"shininess": {
"type": 5126
},
"specular": {
"type": 35666
}
},
"program": "program_0",
"states": {
"enable": [
2929,
2884
]
},
"uniforms": {
"u_diffuse": "diffuse",
"u_modelViewMatrix": "modelViewMatrix",
"u_normalMatrix": "normalMatrix",
"u_projectionMatrix": "projectionMatrix",
"u_shininess": "shininess",
"u_specular": "specular"
}
}
}
}

View file

@ -0,0 +1,24 @@
Simple OpenGL viewer for glTF geometry.
## Requirements
* premake4 : Requires recent `premake4` for macosx and linux, `premake5` for windows.
* GLEW
* glfw3
### MacOSX and Linux
> premake4 gmake
$ make
### Windows(not tested)
> premake5.exe vs2013
Open .sln in Visual Studio 2013
## TODO
* [x] Texture
* [ ] Various texture format.
* [ ] Shader
* [ ] Animation

View file

@ -0,0 +1,546 @@
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <cassert>
#include <cmath>
#include <GL/glew.h>
#define GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
#include "trackball.h"
#define TINYGLTF_LOADER_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#include "tiny_gltf_loader.h"
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
#define CheckGLErrors(desc) \
{ \
GLenum e = glGetError(); \
if (e != GL_NO_ERROR) { \
printf("OpenGL error in \"%s\": %d (%d) %s:%d\n", desc, e, e, __FILE__, \
__LINE__); \
exit(20); \
} \
}
#define CAM_Z (3.0f)
int width = 768;
int height = 768;
double prevMouseX, prevMouseY;
bool mouseLeftPressed;
bool mouseMiddlePressed;
bool mouseRightPressed;
float curr_quat[4];
float prev_quat[4];
float eye[3], lookat[3], up[3];
GLFWwindow *window;
typedef struct { GLuint vb; } GLBufferState;
typedef struct {
std::vector<GLuint> diffuseTex; // for each primitive in mesh
} GLMeshState;
typedef struct {
std::map<std::string, GLint> attribs;
std::map<std::string, GLint> uniforms;
} GLProgramState;
std::map<std::string, GLBufferState> gBufferState;
std::map<std::string, GLMeshState> gMeshState;
GLProgramState gGLProgramState;
void CheckErrors(std::string desc) {
GLenum e = glGetError();
if (e != GL_NO_ERROR) {
fprintf(stderr, "OpenGL error in \"%s\": %d (%d)\n", desc.c_str(), e, e);
exit(20);
}
}
bool LoadShader(GLenum shaderType, // GL_VERTEX_SHADER or GL_FRAGMENT_SHADER(or
// maybe GL_COMPUTE_SHADER)
GLuint &shader, const char *shaderSourceFilename) {
GLint val = 0;
// free old shader/program
if (shader != 0) {
glDeleteShader(shader);
}
std::vector<GLchar> srcbuf;
FILE *fp = fopen(shaderSourceFilename, "rb");
if (!fp) {
fprintf(stderr, "failed to load shader: %s\n", shaderSourceFilename);
return false;
}
fseek(fp, 0, SEEK_END);
size_t len = ftell(fp);
rewind(fp);
srcbuf.resize(len + 1);
len = fread(&srcbuf.at(0), 1, len, fp);
srcbuf[len] = 0;
fclose(fp);
const GLchar *srcs[1];
srcs[0] = &srcbuf.at(0);
shader = glCreateShader(shaderType);
glShaderSource(shader, 1, srcs, NULL);
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &val);
if (val != GL_TRUE) {
char log[4096];
GLsizei msglen;
glGetShaderInfoLog(shader, 4096, &msglen, log);
printf("%s\n", log);
// assert(val == GL_TRUE && "failed to compile shader");
printf("ERR: Failed to load or compile shader [ %s ]\n",
shaderSourceFilename);
return false;
}
printf("Load shader [ %s ] OK\n", shaderSourceFilename);
return true;
}
bool LinkShader(GLuint &prog, GLuint &vertShader, GLuint &fragShader) {
GLint val = 0;
if (prog != 0) {
glDeleteProgram(prog);
}
prog = glCreateProgram();
glAttachShader(prog, vertShader);
glAttachShader(prog, fragShader);
glLinkProgram(prog);
glGetProgramiv(prog, GL_LINK_STATUS, &val);
assert(val == GL_TRUE && "failed to link shader");
printf("Link shader OK\n");
return true;
}
void reshapeFunc(GLFWwindow *window, int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (float)w / (float)h, 0.1f, 1000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
width = w;
height = h;
}
void keyboardFunc(GLFWwindow *window, int key, int scancode, int action,
int mods) {
if (action == GLFW_PRESS || action == GLFW_REPEAT) {
// Close window
if (key == GLFW_KEY_Q || key == GLFW_KEY_ESCAPE)
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
void clickFunc(GLFWwindow *window, int button, int action, int mods) {
double x, y;
glfwGetCursorPos(window, &x, &y);
if (button == GLFW_MOUSE_BUTTON_LEFT) {
mouseLeftPressed = true;
if (action == GLFW_PRESS) {
int id = -1;
// int id = ui.Proc(x, y);
if (id < 0) { // outside of UI
trackball(prev_quat, 0.0, 0.0, 0.0, 0.0);
}
} else if (action == GLFW_RELEASE) {
mouseLeftPressed = false;
}
}
if (button == GLFW_MOUSE_BUTTON_RIGHT) {
if (action == GLFW_PRESS) {
mouseRightPressed = true;
} else if (action == GLFW_RELEASE) {
mouseRightPressed = false;
}
}
if (button == GLFW_MOUSE_BUTTON_MIDDLE) {
if (action == GLFW_PRESS) {
mouseMiddlePressed = true;
} else if (action == GLFW_RELEASE) {
mouseMiddlePressed = false;
}
}
}
void motionFunc(GLFWwindow *window, double mouse_x, double mouse_y) {
float rotScale = 1.0f;
float transScale = 2.0f;
if (mouseLeftPressed) {
trackball(prev_quat, rotScale * (2.0f * prevMouseX - width) / (float)width,
rotScale * (height - 2.0f * prevMouseY) / (float)height,
rotScale * (2.0f * mouse_x - width) / (float)width,
rotScale * (height - 2.0f * mouse_y) / (float)height);
add_quats(prev_quat, curr_quat, curr_quat);
} else if (mouseMiddlePressed) {
eye[0] += -transScale * (mouse_x - prevMouseX) / (float)width;
lookat[0] += -transScale * (mouse_x - prevMouseX) / (float)width;
eye[1] += transScale * (mouse_y - prevMouseY) / (float)height;
lookat[1] += transScale * (mouse_y - prevMouseY) / (float)height;
} else if (mouseRightPressed) {
eye[2] += transScale * (mouse_y - prevMouseY) / (float)height;
lookat[2] += transScale * (mouse_y - prevMouseY) / (float)height;
}
// Update mouse point
prevMouseX = mouse_x;
prevMouseY = mouse_y;
}
static void SetupGLState(Scene &scene, GLuint progId) {
// Buffer
{
std::map<std::string, BufferView>::const_iterator it(
scene.bufferViews.begin());
std::map<std::string, BufferView>::const_iterator itEnd(
scene.bufferViews.end());
for (; it != itEnd; it++) {
const BufferView &bufferView = it->second;
if (bufferView.target == 0) {
continue; // Unsupported bufferView.
}
const Buffer &buffer = scene.buffers[bufferView.buffer];
GLBufferState state;
glGenBuffers(1, &state.vb);
glBindBuffer(bufferView.target, state.vb);
glBufferData(bufferView.target, bufferView.byteLength,
&buffer.data.at(0) + bufferView.byteOffset, GL_STATIC_DRAW);
glBindBuffer(bufferView.target, 0);
gBufferState[it->first] = state;
}
}
// Texture
{
std::map<std::string, Mesh>::const_iterator it(scene.meshes.begin());
std::map<std::string, Mesh>::const_iterator itEnd(scene.meshes.end());
for (; it != itEnd; it++) {
const Mesh &mesh = it->second;
gMeshState[mesh.name].diffuseTex.resize(mesh.primitives.size());
for (size_t primId = 0; primId < mesh.primitives.size(); primId++) {
const Primitive &primitive = mesh.primitives[primId];
gMeshState[mesh.name].diffuseTex[primId] = 0;
if (primitive.material.empty()) {
continue;
}
Material &mat = scene.materials[primitive.material];
printf("material.name = %s\n", mat.name.c_str());
if (mat.values.find("diffuse") != mat.values.end()) {
std::string diffuseTexName = mat.values["diffuse"].stringValue;
if (scene.textures.find(diffuseTexName) != scene.textures.end()) {
Texture &tex = scene.textures[diffuseTexName];
if (scene.images.find(tex.source) != scene.images.end()) {
Image &image = scene.images[tex.source];
GLuint texId;
glGenTextures(1, &texId);
glBindTexture(tex.target, texId);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameterf(tex.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(tex.target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Ignore Texture.fomat.
GLenum format = GL_RGBA;
if (image.component == 3) {
format = GL_RGB;
}
glTexImage2D(tex.target, 0, tex.internalFormat, image.width,
image.height, 0, format, tex.type,
&image.image.at(0));
CheckErrors("texImage2D");
glBindTexture(tex.target, 0);
printf("TexId = %d\n", texId);
gMeshState[mesh.name].diffuseTex[primId] = texId;
}
}
}
}
}
}
glUseProgram(progId);
GLint vtloc = glGetAttribLocation(progId, "in_vertex");
GLint nrmloc = glGetAttribLocation(progId, "in_normal");
GLint uvloc = glGetAttribLocation(progId, "in_texcoord");
GLint diffuseTexLoc = glGetUniformLocation(progId, "diffuseTex");
gGLProgramState.attribs["POSITION"] = vtloc;
gGLProgramState.attribs["NORMAL"] = nrmloc;
gGLProgramState.attribs["TEXCOORD_0"] = uvloc;
gGLProgramState.uniforms["diffuseTex"] = diffuseTexLoc;
};
void DrawMesh(Scene &scene, const Mesh &mesh) {
if (gGLProgramState.uniforms["diffuseTex"] >= 0) {
glUniform1i(gGLProgramState.uniforms["diffuseTex"], 0); // TEXTURE0
}
for (size_t i = 0; i < mesh.primitives.size(); i++) {
const Primitive &primitive = mesh.primitives[i];
if (primitive.indices.empty())
return;
std::map<std::string, std::string>::const_iterator it(
primitive.attributes.begin());
std::map<std::string, std::string>::const_iterator itEnd(
primitive.attributes.end());
// Assume TEXTURE_2D target for the texture object.
glBindTexture(GL_TEXTURE_2D, gMeshState[mesh.name].diffuseTex[i]);
for (; it != itEnd; it++) {
const Accessor &accessor = scene.accessors[it->second];
glBindBuffer(GL_ARRAY_BUFFER, gBufferState[accessor.bufferView].vb);
CheckErrors("bind buffer");
int count = 1;
if (accessor.type == TINYGLTF_TYPE_SCALAR) {
count = 1;
} else if (accessor.type == TINYGLTF_TYPE_VEC2) {
count = 2;
} else if (accessor.type == TINYGLTF_TYPE_VEC3) {
count = 3;
} else if (accessor.type == TINYGLTF_TYPE_VEC4) {
count = 4;
}
// it->first would be "POSITION", "NORMAL", "TEXCOORD_0", ...
if ((it->first.compare("POSITION") == 0) ||
(it->first.compare("NORMAL") == 0) ||
(it->first.compare("TEXCOORD_0") == 0)) {
glVertexAttribPointer(
gGLProgramState.attribs[it->first], count, accessor.componentType,
GL_FALSE, accessor.byteStride, BUFFER_OFFSET(accessor.byteOffset));
CheckErrors("vertex attrib pointer");
glEnableVertexAttribArray(gGLProgramState.attribs[it->first]);
CheckErrors("enable vertex attrib array");
}
}
const Accessor &indexAccessor = scene.accessors[primitive.indices];
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,
gBufferState[indexAccessor.bufferView].vb);
CheckErrors("bind buffer");
int mode = -1;
if (primitive.mode == TINYGLTF_MODE_TRIANGLES) {
mode = GL_TRIANGLES;
} else if (primitive.mode == TINYGLTF_MODE_TRIANGLE_STRIP) {
mode = GL_TRIANGLE_STRIP;
} else if (primitive.mode == TINYGLTF_MODE_TRIANGLE_FAN) {
mode = GL_TRIANGLE_FAN;
} else if (primitive.mode == TINYGLTF_MODE_POINTS) {
mode = GL_POINTS;
} else if (primitive.mode == TINYGLTF_MODE_LINE) {
mode = GL_LINES;
} else if (primitive.mode == TINYGLTF_MODE_LINE_LOOP) {
mode = GL_LINE_LOOP;
};
glDrawElements(mode, indexAccessor.count, indexAccessor.componentType,
BUFFER_OFFSET(indexAccessor.byteOffset));
CheckErrors("draw elements");
{
std::map<std::string, std::string>::const_iterator it(
primitive.attributes.begin());
std::map<std::string, std::string>::const_iterator itEnd(
primitive.attributes.end());
for (; it != itEnd; it++) {
if ((it->first.compare("POSITION") == 0) ||
(it->first.compare("NORMAL") == 0) ||
(it->first.compare("TEXCOORD_0") == 0)) {
glDisableVertexAttribArray(gGLProgramState.attribs[it->first]);
}
}
}
}
}
void DrawScene(Scene &scene) {
std::map<std::string, Mesh>::const_iterator it(scene.meshes.begin());
std::map<std::string, Mesh>::const_iterator itEnd(scene.meshes.end());
for (; it != itEnd; it++) {
DrawMesh(scene, it->second);
}
}
static void Init() {
trackball(curr_quat, 0, 0, 0, 0);
eye[0] = 0.0f;
eye[1] = 0.0f;
eye[2] = CAM_Z;
lookat[0] = 0.0f;
lookat[1] = 0.0f;
lookat[2] = 0.0f;
up[0] = 0.0f;
up[1] = 1.0f;
up[2] = 0.0f;
}
int main(int argc, char **argv) {
if (argc < 2) {
std::cout << "glview input.gltf <scale>\n" << std::endl;
return 0;
}
float scale = 1.0f;
if (argc > 2) {
scale = atof(argv[2]);
}
Scene scene;
TinyGLTFLoader loader;
std::string err;
bool ret = loader.LoadFromFile(scene, err, argv[1]);
if (!err.empty()) {
printf("ERR: %s\n", err.c_str());
}
if (!ret) {
printf("Failed to load .glTF : %s\n", argv[1]);
exit(-1);
}
Init();
if (!glfwInit()) {
std::cerr << "Failed to initialize GLFW." << std::endl;
return -1;
}
window = glfwCreateWindow(width, height, "Simple glTF geometry viewer", NULL,
NULL);
if (window == NULL) {
std::cerr << "Failed to open GLFW window. " << std::endl;
glfwTerminate();
return 1;
}
glfwGetWindowSize(window, &width, &height);
glfwMakeContextCurrent(window);
// Callback
glfwSetWindowSizeCallback(window, reshapeFunc);
glfwSetKeyCallback(window, keyboardFunc);
glfwSetMouseButtonCallback(window, clickFunc);
glfwSetCursorPosCallback(window, motionFunc);
glewExperimental = true;
if (glewInit() != GLEW_OK) {
std::cerr << "Failed to initialize GLEW." << std::endl;
return -1;
}
reshapeFunc(window, width, height);
GLuint vertId = 0, fragId = 0, progId = 0;
if (false == LoadShader(GL_VERTEX_SHADER, vertId, "shader.vert")) {
return -1;
}
CheckErrors("load vert shader");
if (false == LoadShader(GL_FRAGMENT_SHADER, fragId, "shader.frag")) {
return -1;
}
CheckErrors("load frag shader");
if (false == LinkShader(progId, vertId, fragId)) {
return -1;
}
CheckErrors("link");
{
GLint vtxLoc = glGetAttribLocation(progId, "in_vertex");
if (vtxLoc < 0) {
printf("vertex loc not found.\n");
exit(-1);
}
GLint tnLoc = glGetAttribLocation(progId, "in_normal");
if (tnLoc < 0) {
printf("normal loc not found.\n");
exit(-1);
}
}
glUseProgram(progId);
CheckErrors("useProgram");
SetupGLState(scene, progId);
CheckErrors("SetupGLState");
while (glfwWindowShouldClose(window) == GL_FALSE) {
glfwPollEvents();
glClearColor(0.1f, 0.2f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
GLfloat mat[4][4];
build_rotmatrix(mat, curr_quat);
// camera(define it in projection matrix)
glMatrixMode(GL_PROJECTION);
glPushMatrix();
gluLookAt(eye[0], eye[1], eye[2], lookat[0], lookat[1], lookat[2], up[0],
up[1], up[2]);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMultMatrixf(&mat[0][0]);
glScalef(scale, scale, scale);
DrawScene(scene);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glFlush();
glfwSwapBuffers(window);
}
glfwTerminate();
}

View file

@ -0,0 +1,36 @@
solution "glview"
-- location ( "build" )
configurations { "Debug", "Release" }
platforms {"native", "x64", "x32"}
project "glview"
kind "ConsoleApp"
language "C++"
files { "glview.cc", "trackball.cc" }
includedirs { "./" }
includedirs { "../../" }
configuration { "linux" }
linkoptions { "`pkg-config --libs glfw3`" }
links { "GL", "GLU", "m", "GLEW" }
configuration { "windows" }
links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" }
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration { "macosx" }
includedirs { "/usr/local/include" }
buildoptions { "-Wno-deprecated-declarations" }
libdirs { "/usr/local/lib" }
links { "glfw3", "GLEW" }
linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo" }
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols", "ExtraWarnings"}
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize", "ExtraWarnings"}

View file

@ -0,0 +1,11 @@
uniform sampler2D diffuseTex;
varying vec3 normal;
varying vec2 texcoord;
void main(void)
{
//gl_FragColor = vec4(0.5 * normalize(normal) + 0.5, 1.0);
//gl_FragColor = vec4(texcoord, 0.0, 1.0);
gl_FragColor = texture2D(diffuseTex, texcoord);
}

View file

@ -0,0 +1,16 @@
attribute vec3 in_vertex;
attribute vec3 in_normal;
attribute vec2 in_texcoord;
varying vec3 normal;
varying vec2 texcoord;
void main(void)
{
vec4 p = gl_ModelViewProjectionMatrix * vec4(in_vertex, 1);
gl_Position = p;
vec4 nn = gl_ModelViewMatrixInverseTranspose * vec4(normalize(in_normal), 0);
normal = nn.xyz;
texcoord = in_texcoord;
}

View file

@ -0,0 +1,292 @@
/*
* (c) Copyright 1993, 1994, Silicon Graphics, Inc.
* ALL RIGHTS RESERVED
* Permission to use, copy, modify, and distribute this software for
* any purpose and without fee is hereby granted, provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation, and that
* the name of Silicon Graphics, Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific,
* written prior permission.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
* THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*
* US Government Users Restricted Rights
* Use, duplication, or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
* (c)(1)(ii) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227-7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement.
* Unpublished-- rights reserved under the copyright laws of the
* United States. Contractor/manufacturer is Silicon Graphics,
* Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
*
* OpenGL(TM) is a trademark of Silicon Graphics, Inc.
*/
/*
* Trackball code:
*
* Implementation of a virtual trackball.
* Implemented by Gavin Bell, lots of ideas from Thant Tessman and
* the August '88 issue of Siggraph's "Computer Graphics," pp. 121-129.
*
* Vector manip code:
*
* Original code from:
* David M. Ciemiewicz, Mark Grossman, Henry Moreton, and Paul Haeberli
*
* Much mucking with by:
* Gavin Bell
*/
#include <math.h>
#include "trackball.h"
/*
* This size should really be based on the distance from the center of
* rotation to the point on the object underneath the mouse. That
* point would then track the mouse as closely as possible. This is a
* simple example, though, so that is left as an Exercise for the
* Programmer.
*/
#define TRACKBALLSIZE (0.8)
/*
* Local function prototypes (not defined in trackball.h)
*/
static float tb_project_to_sphere(float, float, float);
static void normalize_quat(float[4]);
static void vzero(float *v) {
v[0] = 0.0;
v[1] = 0.0;
v[2] = 0.0;
}
static void vset(float *v, float x, float y, float z) {
v[0] = x;
v[1] = y;
v[2] = z;
}
static void vsub(const float *src1, const float *src2, float *dst) {
dst[0] = src1[0] - src2[0];
dst[1] = src1[1] - src2[1];
dst[2] = src1[2] - src2[2];
}
static void vcopy(const float *v1, float *v2) {
register int i;
for (i = 0; i < 3; i++)
v2[i] = v1[i];
}
static void vcross(const float *v1, const float *v2, float *cross) {
float temp[3];
temp[0] = (v1[1] * v2[2]) - (v1[2] * v2[1]);
temp[1] = (v1[2] * v2[0]) - (v1[0] * v2[2]);
temp[2] = (v1[0] * v2[1]) - (v1[1] * v2[0]);
vcopy(temp, cross);
}
static float vlength(const float *v) {
return sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
}
static void vscale(float *v, float div) {
v[0] *= div;
v[1] *= div;
v[2] *= div;
}
static void vnormal(float *v) { vscale(v, 1.0 / vlength(v)); }
static float vdot(const float *v1, const float *v2) {
return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];
}
static void vadd(const float *src1, const float *src2, float *dst) {
dst[0] = src1[0] + src2[0];
dst[1] = src1[1] + src2[1];
dst[2] = src1[2] + src2[2];
}
/*
* Ok, simulate a track-ball. Project the points onto the virtual
* trackball, then figure out the axis of rotation, which is the cross
* product of P1 P2 and O P1 (O is the center of the ball, 0,0,0)
* Note: This is a deformed trackball-- is a trackball in the center,
* but is deformed into a hyperbolic sheet of rotation away from the
* center. This particular function was chosen after trying out
* several variations.
*
* It is assumed that the arguments to this routine are in the range
* (-1.0 ... 1.0)
*/
void trackball(float q[4], float p1x, float p1y, float p2x, float p2y) {
float a[3]; /* Axis of rotation */
float phi; /* how much to rotate about axis */
float p1[3], p2[3], d[3];
float t;
if (p1x == p2x && p1y == p2y) {
/* Zero rotation */
vzero(q);
q[3] = 1.0;
return;
}
/*
* First, figure out z-coordinates for projection of P1 and P2 to
* deformed sphere
*/
vset(p1, p1x, p1y, tb_project_to_sphere(TRACKBALLSIZE, p1x, p1y));
vset(p2, p2x, p2y, tb_project_to_sphere(TRACKBALLSIZE, p2x, p2y));
/*
* Now, we want the cross product of P1 and P2
*/
vcross(p2, p1, a);
/*
* Figure out how much to rotate around that axis.
*/
vsub(p1, p2, d);
t = vlength(d) / (2.0 * TRACKBALLSIZE);
/*
* Avoid problems with out-of-control values...
*/
if (t > 1.0)
t = 1.0;
if (t < -1.0)
t = -1.0;
phi = 2.0 * asin(t);
axis_to_quat(a, phi, q);
}
/*
* Given an axis and angle, compute quaternion.
*/
void axis_to_quat(float a[3], float phi, float q[4]) {
vnormal(a);
vcopy(a, q);
vscale(q, sin(phi / 2.0));
q[3] = cos(phi / 2.0);
}
/*
* Project an x,y pair onto a sphere of radius r OR a hyperbolic sheet
* if we are away from the center of the sphere.
*/
static float tb_project_to_sphere(float r, float x, float y) {
float d, t, z;
d = sqrt(x * x + y * y);
if (d < r * 0.70710678118654752440) { /* Inside sphere */
z = sqrt(r * r - d * d);
} else { /* On hyperbola */
t = r / 1.41421356237309504880;
z = t * t / d;
}
return z;
}
/*
* Given two rotations, e1 and e2, expressed as quaternion rotations,
* figure out the equivalent single rotation and stuff it into dest.
*
* This routine also normalizes the result every RENORMCOUNT times it is
* called, to keep error from creeping in.
*
* NOTE: This routine is written so that q1 or q2 may be the same
* as dest (or each other).
*/
#define RENORMCOUNT 97
void add_quats(float q1[4], float q2[4], float dest[4]) {
static int count = 0;
float t1[4], t2[4], t3[4];
float tf[4];
vcopy(q1, t1);
vscale(t1, q2[3]);
vcopy(q2, t2);
vscale(t2, q1[3]);
vcross(q2, q1, t3);
vadd(t1, t2, tf);
vadd(t3, tf, tf);
tf[3] = q1[3] * q2[3] - vdot(q1, q2);
dest[0] = tf[0];
dest[1] = tf[1];
dest[2] = tf[2];
dest[3] = tf[3];
if (++count > RENORMCOUNT) {
count = 0;
normalize_quat(dest);
}
}
/*
* Quaternions always obey: a^2 + b^2 + c^2 + d^2 = 1.0
* If they don't add up to 1.0, dividing by their magnitued will
* renormalize them.
*
* Note: See the following for more information on quaternions:
*
* - Shoemake, K., Animating rotation with quaternion curves, Computer
* Graphics 19, No 3 (Proc. SIGGRAPH'85), 245-254, 1985.
* - Pletinckx, D., Quaternion calculus as a basic tool in computer
* graphics, The Visual Computer 5, 2-13, 1989.
*/
static void normalize_quat(float q[4]) {
int i;
float mag;
mag = (q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]);
for (i = 0; i < 4; i++)
q[i] /= mag;
}
/*
* Build a rotation matrix, given a quaternion rotation.
*
*/
void build_rotmatrix(float m[4][4], const float q[4]) {
m[0][0] = 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2]);
m[0][1] = 2.0 * (q[0] * q[1] - q[2] * q[3]);
m[0][2] = 2.0 * (q[2] * q[0] + q[1] * q[3]);
m[0][3] = 0.0;
m[1][0] = 2.0 * (q[0] * q[1] + q[2] * q[3]);
m[1][1] = 1.0 - 2.0 * (q[2] * q[2] + q[0] * q[0]);
m[1][2] = 2.0 * (q[1] * q[2] - q[0] * q[3]);
m[1][3] = 0.0;
m[2][0] = 2.0 * (q[2] * q[0] - q[1] * q[3]);
m[2][1] = 2.0 * (q[1] * q[2] + q[0] * q[3]);
m[2][2] = 1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0]);
m[2][3] = 0.0;
m[3][0] = 0.0;
m[3][1] = 0.0;
m[3][2] = 0.0;
m[3][3] = 1.0;
}

View file

@ -0,0 +1,75 @@
/*
* (c) Copyright 1993, 1994, Silicon Graphics, Inc.
* ALL RIGHTS RESERVED
* Permission to use, copy, modify, and distribute this software for
* any purpose and without fee is hereby granted, provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation, and that
* the name of Silicon Graphics, Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific,
* written prior permission.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
* THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*
* US Government Users Restricted Rights
* Use, duplication, or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
* (c)(1)(ii) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227-7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement.
* Unpublished-- rights reserved under the copyright laws of the
* United States. Contractor/manufacturer is Silicon Graphics,
* Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
*
* OpenGL(TM) is a trademark of Silicon Graphics, Inc.
*/
/*
* trackball.h
* A virtual trackball implementation
* Written by Gavin Bell for Silicon Graphics, November 1988.
*/
/*
* Pass the x and y coordinates of the last and current positions of
* the mouse, scaled so they are from (-1.0 ... 1.0).
*
* The resulting rotation is returned as a quaternion rotation in the
* first paramater.
*/
void trackball(float q[4], float p1x, float p1y, float p2x, float p2y);
void negate_quat(float *q, float *qn);
/*
* Given two quaternions, add them together to get a third quaternion.
* Adding quaternions to get a compound rotation is analagous to adding
* translations to get a compound translation. When incrementally
* adding rotations, the first argument here should be the new
* rotation, the second and third the total rotation (which will be
* over-written with the resulting new total rotation).
*/
void add_quats(float *q1, float *q2, float *dest);
/*
* A useful function, builds a rotation matrix in Matrix based on
* given quaternion.
*/
void build_rotmatrix(float m[4][4], const float q[4]);
/*
* This function computes a quaternion based on an axis (defined by
* the given vector) and an angle about which to rotate. The angle is
* expressed in radians. The result is put into the third argument.
*/
void axis_to_quat(float a[3], float phi, float q[4]);

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,29 @@
sources = {
"test.cc",
}
-- premake4.lua
solution "TinyGLTFLoaderSolution"
configurations { "Release", "Debug" }
if (os.is("windows")) then
platforms { "x32", "x64" }
else
platforms { "native", "x32", "x64" }
end
-- A project defines one build target
project "tinygltfloader"
kind "ConsoleApp"
language "C++"
files { sources }
configuration "Debug"
defines { "DEBUG" } -- -DDEBUG
flags { "Symbols" }
targetname "test_tinygltfloader_debug"
configuration "Release"
-- defines { "NDEBUG" } -- -NDEBUG
flags { "Symbols", "Optimize" }
targetname "test_tinygltfloader"

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,377 @@
#define TINYGLTF_LOADER_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#include "tiny_gltf_loader.h"
#include <fstream>
#include <cstdio>
#include <iostream>
std::string PrintMode(int mode) {
if (mode == TINYGLTF_MODE_POINTS) {
return "POINTS";
} else if (mode == TINYGLTF_MODE_LINE) {
return "LINE";
} else if (mode == TINYGLTF_MODE_LINE_LOOP) {
return "LINE_LOOP";
} else if (mode == TINYGLTF_MODE_TRIANGLES) {
return "TRIANGLES";
} else if (mode == TINYGLTF_MODE_TRIANGLE_FAN) {
return "TRIANGLE_FAN";
} else if (mode == TINYGLTF_MODE_TRIANGLE_STRIP) {
return "TRIANGLE_STRIP";
}
return "**UNKNOWN**";
}
std::string PrintType(int ty) {
if (ty == TINYGLTF_TYPE_SCALAR) {
return "SCALAR";
} else if (ty == TINYGLTF_TYPE_VECTOR) {
return "VECTOR";
} else if (ty == TINYGLTF_TYPE_VEC2) {
return "VEC2";
} else if (ty == TINYGLTF_TYPE_VEC3) {
return "VEC3";
} else if (ty == TINYGLTF_TYPE_VEC4) {
return "VEC4";
} else if (ty == TINYGLTF_TYPE_MATRIX) {
return "MATRIX";
} else if (ty == TINYGLTF_TYPE_MAT2) {
return "MAT2";
} else if (ty == TINYGLTF_TYPE_MAT3) {
return "MAT3";
} else if (ty == TINYGLTF_TYPE_MAT4) {
return "MAT4";
}
return "**UNKNOWN**";
}
std::string PrintComponentType(int ty) {
if (ty == TINYGLTF_COMPONENT_TYPE_BYTE) {
return "BYTE";
} else if (ty == TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE) {
return "UNSIGNED_BYTE";
} else if (ty == TINYGLTF_COMPONENT_TYPE_SHORT) {
return "SHORT";
} else if (ty == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT) {
return "UNSIGNED_SHORT";
} else if (ty == TINYGLTF_COMPONENT_TYPE_INT) {
return "INT";
} else if (ty == TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT) {
return "UNSIGNED_INT";
} else if (ty == TINYGLTF_COMPONENT_TYPE_FLOAT) {
return "FLOAT";
} else if (ty == TINYGLTF_COMPONENT_TYPE_DOUBLE) {
return "DOUBLE";
}
return "**UNKNOWN**";
}
std::string PrintFloatArray(const std::vector<double> &arr) {
if (arr.size() == 0) {
return "";
}
std::stringstream ss;
ss << "[ ";
for (size_t i = 0; i < arr.size(); i++) {
ss << arr[i] << ((i != arr.size() - 1) ? ", " : "");
}
ss << " ]";
return ss.str();
}
std::string PrintStringArray(const std::vector<std::string> &arr) {
if (arr.size() == 0) {
return "";
}
std::stringstream ss;
ss << "[ ";
for (size_t i = 0; i < arr.size(); i++) {
ss << arr[i] << ((i != arr.size() - 1) ? ", " : "");
}
ss << " ]";
return ss.str();
}
std::string Indent(int indent) {
std::string s;
for (int i = 0; i < indent; i++) {
s += " ";
}
return s;
}
void DumpNode(const Node &node, int indent) {
std::cout << Indent(indent) << "name : " << node.name << std::endl;
std::cout << Indent(indent) << "camera : " << node.camera << std::endl;
if (!node.rotation.empty()) {
std::cout << Indent(indent)
<< "rotation : " << PrintFloatArray(node.rotation)
<< std::endl;
}
if (!node.scale.empty()) {
std::cout << Indent(indent)
<< "scale : " << PrintFloatArray(node.scale) << std::endl;
}
if (!node.translation.empty()) {
std::cout << Indent(indent)
<< "translation : " << PrintFloatArray(node.translation)
<< std::endl;
}
if (!node.matrix.empty()) {
std::cout << Indent(indent)
<< "matrix : " << PrintFloatArray(node.matrix) << std::endl;
}
std::cout << Indent(indent)
<< "meshes : " << PrintStringArray(node.meshes) << std::endl;
std::cout << Indent(indent)
<< "children : " << PrintStringArray(node.children) << std::endl;
}
void DumpPrimitive(const Primitive &primitive, int indent) {
std::cout << Indent(indent) << "material : " << primitive.material
<< std::endl;
std::cout << Indent(indent) << "mode : " << PrintMode(primitive.mode)
<< "(" << primitive.mode << ")" << std::endl;
std::cout << Indent(indent)
<< "attributes(items=" << primitive.attributes.size() << ")"
<< std::endl;
std::map<std::string, std::string>::const_iterator it(
primitive.attributes.begin());
std::map<std::string, std::string>::const_iterator itEnd(
primitive.attributes.end());
for (; it != itEnd; it++) {
std::cout << Indent(indent + 1) << it->first << ": " << it->second
<< std::endl;
}
}
void Dump(const Scene &scene) {
std::cout << "=== Dump glTF ===" << std::endl;
std::cout << "asset.generator : " << scene.asset.generator
<< std::endl;
std::cout << "asset.premultipliedAlpha : " << scene.asset.premultipliedAlpha
<< std::endl;
std::cout << "asset.version : " << scene.asset.version
<< std::endl;
std::cout << "asset.profile.api : " << scene.asset.profile_api
<< std::endl;
std::cout << "asset.profile.version : " << scene.asset.profile_version
<< std::endl;
std::cout << std::endl;
std::cout << "=== Dump scene ===" << std::endl;
std::cout << "defaultScene: " << scene.defaultScene << std::endl;
{
std::map<std::string, std::vector<std::string> >::const_iterator it(
scene.scenes.begin());
std::map<std::string, std::vector<std::string> >::const_iterator itEnd(
scene.scenes.end());
std::cout << "scenes(items=" << scene.scenes.size() << ")" << std::endl;
for (; it != itEnd; it++) {
std::cout << Indent(1) << "name : " << it->first << std::endl;
std::cout << Indent(2) << "nodes : [ ";
for (size_t i = 0; i < it->second.size(); i++) {
std::cout << it->second[i]
<< ((i != (it->second.size() - 1)) ? ", " : "");
}
std::cout << " ] " << std::endl;
}
}
{
std::map<std::string, Mesh>::const_iterator it(scene.meshes.begin());
std::map<std::string, Mesh>::const_iterator itEnd(scene.meshes.end());
std::cout << "meshes(item=" << scene.meshes.size() << ")" << std::endl;
for (; it != itEnd; it++) {
std::cout << Indent(1) << "name : " << it->second.name << std::endl;
std::cout << Indent(1)
<< "primitives(items=" << it->second.primitives.size()
<< "): " << std::endl;
for (size_t i = 0; i < it->second.primitives.size(); i++) {
DumpPrimitive(it->second.primitives[i], 2);
}
}
}
{
std::map<std::string, Accessor>::const_iterator it(scene.accessors.begin());
std::map<std::string, Accessor>::const_iterator itEnd(
scene.accessors.end());
std::cout << "accessos(items=" << scene.accessors.size() << ")"
<< std::endl;
for (; it != itEnd; it++) {
std::cout << Indent(1) << "name : " << it->first << std::endl;
std::cout << Indent(2) << "bufferView : " << it->second.bufferView
<< std::endl;
std::cout << Indent(2) << "byteOffset : " << it->second.byteOffset
<< std::endl;
std::cout << Indent(2) << "byteStride : " << it->second.byteStride
<< std::endl;
std::cout << Indent(2) << "componentType: "
<< PrintComponentType(it->second.componentType) << "("
<< it->second.componentType << ")" << std::endl;
std::cout << Indent(2) << "count : " << it->second.count
<< std::endl;
std::cout << Indent(2) << "type : " << PrintType(it->second.type)
<< std::endl;
if (!it->second.minValues.empty()) {
std::cout << Indent(2) << "min : [";
for (size_t i = 0; i < it->second.minValues.size(); i++) {
std::cout << it->second.minValues[i]
<< ((i != it->second.minValues.size() - 1) ? ", " : "");
}
std::cout << "]" << std::endl;
}
if (!it->second.maxValues.empty()) {
std::cout << Indent(2) << "max : [";
for (size_t i = 0; i < it->second.maxValues.size(); i++) {
std::cout << it->second.maxValues[i]
<< ((i != it->second.maxValues.size() - 1) ? ", " : "");
}
std::cout << "]" << std::endl;
}
}
}
{
std::map<std::string, BufferView>::const_iterator it(
scene.bufferViews.begin());
std::map<std::string, BufferView>::const_iterator itEnd(
scene.bufferViews.end());
std::cout << "bufferViews(items=" << scene.bufferViews.size() << ")"
<< std::endl;
for (; it != itEnd; it++) {
std::cout << Indent(1) << "name : " << it->first << std::endl;
std::cout << Indent(2) << "buffer : " << it->second.buffer
<< std::endl;
std::cout << Indent(2) << "byteLength : " << it->second.byteLength
<< std::endl;
std::cout << Indent(2) << "byteOffset : " << it->second.byteOffset
<< std::endl;
}
}
{
std::map<std::string, Buffer>::const_iterator it(scene.buffers.begin());
std::map<std::string, Buffer>::const_iterator itEnd(scene.buffers.end());
std::cout << "buffers(items=" << scene.buffers.size() << ")" << std::endl;
for (; it != itEnd; it++) {
std::cout << Indent(1) << "name : " << it->first << std::endl;
std::cout << Indent(2) << "byteLength : " << it->second.data.size()
<< std::endl;
}
}
{
std::map<std::string, Material>::const_iterator it(scene.materials.begin());
std::map<std::string, Material>::const_iterator itEnd(
scene.materials.end());
std::cout << "materials(items=" << scene.materials.size() << ")"
<< std::endl;
for (; it != itEnd; it++) {
std::cout << Indent(1) << "name : " << it->first << std::endl;
std::cout << Indent(1) << "technique : " << it->second.technique
<< std::endl;
std::cout << Indent(1) << "values(items=" << it->second.values.size()
<< std::endl;
ParameterMap::const_iterator p(it->second.values.begin());
ParameterMap::const_iterator pEnd(it->second.values.end());
for (; p != pEnd; p++) {
if (!p->second.numberArray.empty()) {
std::cout << Indent(3) << p->first
<< PrintFloatArray(p->second.numberArray) << std::endl;
}
if (!p->second.stringValue.empty()) {
std::cout << Indent(3) << p->first << " : " << p->second.stringValue
<< std::endl;
}
}
}
}
{
std::map<std::string, Node>::const_iterator it(scene.nodes.begin());
std::map<std::string, Node>::const_iterator itEnd(scene.nodes.end());
std::cout << "nodes(items=" << scene.nodes.size() << ")" << std::endl;
for (; it != itEnd; it++) {
std::cout << Indent(1) << "name : " << it->first << std::endl;
DumpNode(it->second, 2);
}
}
{
std::map<std::string, Image>::const_iterator it(scene.images.begin());
std::map<std::string, Image>::const_iterator itEnd(scene.images.end());
std::cout << "images(items=" << scene.images.size() << ")" << std::endl;
for (; it != itEnd; it++) {
std::cout << Indent(1) << "name : " << it->first << std::endl;
std::cout << Indent(2) << "width : " << it->second.width << std::endl;
std::cout << Indent(2) << "height : " << it->second.height
<< std::endl;
std::cout << Indent(2) << "component : " << it->second.component
<< std::endl;
std::cout << Indent(2) << "name : " << it->second.name << std::endl;
}
}
{
std::map<std::string, Texture>::const_iterator it(scene.textures.begin());
std::map<std::string, Texture>::const_iterator itEnd(scene.textures.end());
std::cout << "textures(items=" << scene.textures.size() << ")" << std::endl;
for (; it != itEnd; it++) {
std::cout << Indent(1) << "name : " << it->first << std::endl;
std::cout << Indent(1) << "format : " << it->second.format
<< std::endl;
std::cout << Indent(1) << "internalFormat : " << it->second.internalFormat
<< std::endl;
std::cout << Indent(1) << "sampler : " << it->second.sampler
<< std::endl;
std::cout << Indent(1) << "source : " << it->second.source
<< std::endl;
std::cout << Indent(1) << "target : " << it->second.target
<< std::endl;
std::cout << Indent(1) << "type : " << it->second.type
<< std::endl;
}
}
}
int main(int argc, char **argv) {
if (argc < 2) {
printf("Needs input.gltf\n");
exit(1);
}
Scene scene;
TinyGLTFLoader loader;
std::string err;
bool ret = loader.LoadFromFile(scene, err, argv[1]);
if (!err.empty()) {
printf("Err: %s\n", err.c_str());
}
if (!ret) {
printf("Failed to parse glTF\n");
return -1;
}
Dump(scene);
return 0;
}

View file

@ -0,0 +1,64 @@
#!/usr/bin/env python
# Assume python 2.6 or 2.7
import glob
import os
import subprocess
## Simple test runner.
# -- config -----------------------
# Absolute path pointing to your cloned git repo of https://github.com/KhronosGroup/glTF/sampleModels
base_model_dir = "/Users/syoyo/work/glTF/sampleModels"
kinds = [ "glTF", "glTF-Binary", "glTF-Embedded", "glTF-MaterialsCommon"]
# ---------------------------------
failed = []
success = []
def run(filename):
print("Testing: " + filename)
cmd = ["./loader_test", filename]
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
except:
print "Failed to execute: ", cmd
raise
if p.returncode != 0:
failed.append(filename)
print(stdout)
print(stderr)
else:
success.append(filename)
def test():
for d in os.listdir(base_model_dir):
p = os.path.join(base_model_dir, d)
if os.path.isdir(p):
for k in kinds:
targetDir = os.path.join(p, k)
g = glob.glob(targetDir + "/*.gltf")
for gltf in g:
run(gltf)
def main():
test()
print("Success : {0}".format(len(success)))
print("Failed : {0}".format(len(failed)))
for fail in failed:
print("FAIL: " + fail)
if __name__ == '__main__':
main()

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1 @@
.\\tools\\windows\\premake5.exe vs2013