* Adjustment: Update Bullet version to 3.24.

This commit is contained in:
Robert MacGregor 2022-06-27 10:01:08 -04:00
parent 35de012ee7
commit 4a3f31df2a
6148 changed files with 2112532 additions and 56873 deletions

View file

@ -0,0 +1,80 @@
INCLUDE_DIRECTORIES(
..
../ThirdPartyLibs
../../src
../ThirdPartyLibs/glad
)
FILE(GLOB OpenGLWindow_HDRS "*.h" )
FILE(GLOB OpenGLWindowMac_CPP "Mac*.cpp")
FILE(GLOB OpenGLWindowMacObjC_CPP "Mac*.m")
FILE(GLOB OpenGLWindowWin32_CPP "Win32*.cpp")
FILE(GLOB OpenGLWindowLinux_CPP "X11*.cpp")
FILE(GLOB OpenGLWindowCommon_CPP "*.cpp" )
LIST(REMOVE_ITEM OpenGLWindowCommon_CPP ${OpenGLWindowMac_CPP} )
LIST(REMOVE_ITEM OpenGLWindowCommon_CPP ${OpenGLWindowWin32_CPP} )
LIST(REMOVE_ITEM OpenGLWindowCommon_CPP ${OpenGLWindowLinux_CPP} )
LIST(REMOVE_ITEM OpenGLWindowCommon_CPP X11OpenGLWindow.cpp )
LIST(REMOVE_ITEM OpenGLWindowCommon_CPP MacOpenGLWindow.cpp )
#MESSAGE (${OpenGLWindowCommon_CPP})
IF (WIN32)
SET(OpenGLWindow_SRCS ${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/glad/gl.c ${OpenGLWindowWin32_CPP} ${OpenGLWindowCommon_CPP})
INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/glad
)
ADD_DEFINITIONS(-DGLEW_STATIC)
ENDIF(WIN32)
IF (APPLE)
SET(OpenGLWindow_SRCS ${OpenGLWindowMac_CPP} ${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/glad/gl.c ${OpenGLWindowMacObjC_CPP} ${OpenGLWindowCommon_CPP} )
ENDIF(APPLE)
#no Linux detection?
IF(NOT WIN32 AND NOT APPLE)
INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/glad
${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/optionalX11
)
ADD_DEFINITIONS(-DGLEW_STATIC)
ADD_DEFINITIONS("-DGLEW_INIT_OPENGL11_FUNCTIONS=1")
ADD_DEFINITIONS("-DGLEW_DYNAMIC_LOAD_ALL_GLX_FUNCTIONS=1")
ADD_DEFINITIONS("-DDYNAMIC_LOAD_X11_FUNCTIONS=1")
SET(OpenGLWindow_SRCS ${OpenGLWindowLinux_CPP} ${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/glad/glx.c ${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/glad/gl.c ${OpenGLWindowCommon_CPP} )
ENDIF()
IF(BUILD_EGL)
SET(OpenGLWindow_SRCS ${OpenGLWindow_SRCS} ${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/glad/egl.c)
ENDIF(BUILD_EGL)
SET(OpenGLWindow_SRCS ${OpenGLWindow_SRCS} ${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/stb_image/stb_image_write.cpp)
ADD_LIBRARY(OpenGLWindow ${OpenGLWindow_SRCS} ${OpenGLWindow_HDRS})
if (UNIX AND NOT APPLE)
target_link_libraries(OpenGLWindow ${DL})
elseif (APPLE)
target_link_libraries(OpenGLWindow ${COCOA_LIBRARY})
endif ()
if (BUILD_SHARED_LIBS)
target_link_libraries(OpenGLWindow Bullet3Common)
if (WIN32 OR APPLE)
target_link_libraries(OpenGLWindow ${OPENGL_gl_LIBRARY})
else()
set (CMAKE_THREAD_PREFER_PTHREAD TRUE)
FIND_PACKAGE(Threads)
target_link_libraries(OpenGLWindow ${CMAKE_THREAD_LIBS_INIT})
endif()
endif()
#target_link_libraries(OpenGLWindow ${OPENGL_gl_LIBRARY})
INSTALL(TARGETS OpenGLWindow
RUNTIME DESTINATION bin
LIBRARY DESTINATION lib${LIB_SUFFIX}
ARCHIVE DESTINATION lib${LIB_SUFFIX})

View file

@ -0,0 +1,387 @@
// portions of this file are copied from GLFW egl_context.c/egl_context.h
//========================================================================
// GLFW 3.3 EGL - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2016 Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#ifdef BT_USE_EGL
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdlib>
#include "OpenGLInclude.h"
#include "glad/egl.h"
#include "glad/gl.h"
#include "EGLOpenGLWindow.h"
struct EGLInternalData2
{
bool m_isInitialized;
int m_windowWidth;
int m_windowHeight;
int m_renderDevice;
b3KeyboardCallback m_keyboardCallback;
b3WheelCallback m_wheelCallback;
b3ResizeCallback m_resizeCallback;
b3MouseButtonCallback m_mouseButtonCallback;
b3MouseMoveCallback m_mouseMoveCallback;
EGLBoolean success;
EGLint num_configs;
EGLConfig egl_config;
EGLSurface egl_surface;
EGLContext egl_context;
EGLDisplay egl_display;
EGLInternalData2()
: m_isInitialized(false),
m_windowWidth(0),
m_windowHeight(0),
m_keyboardCallback(0),
m_wheelCallback(0),
m_resizeCallback(0),
m_mouseButtonCallback(0),
m_mouseMoveCallback(0) {}
};
EGLOpenGLWindow::EGLOpenGLWindow() { m_data = new EGLInternalData2(); }
EGLOpenGLWindow::~EGLOpenGLWindow() { delete m_data; }
void EGLOpenGLWindow::createWindow(const b3gWindowConstructionInfo& ci)
{
m_data->m_windowWidth = ci.m_width;
m_data->m_windowHeight = ci.m_height;
m_data->m_renderDevice = ci.m_renderDevice;
EGLint egl_config_attribs[] = {EGL_RED_SIZE,
8,
EGL_GREEN_SIZE,
8,
EGL_BLUE_SIZE,
8,
EGL_DEPTH_SIZE,
8,
EGL_SURFACE_TYPE,
EGL_PBUFFER_BIT,
EGL_RENDERABLE_TYPE,
EGL_OPENGL_BIT,
EGL_NONE};
EGLint egl_pbuffer_attribs[] = {
EGL_WIDTH,
m_data->m_windowWidth,
EGL_HEIGHT,
m_data->m_windowHeight,
EGL_NONE,
};
// Load EGL functions
int egl_version = gladLoaderLoadEGL(NULL);
if (!egl_version)
{
fprintf(stderr, "failed to EGL with glad.\n");
exit(EXIT_FAILURE);
};
// Query EGL Devices
const int max_devices = 32;
EGLDeviceEXT egl_devices[max_devices];
EGLint num_devices = 0;
EGLint egl_error = eglGetError();
if (!eglQueryDevicesEXT(max_devices, egl_devices, &num_devices) ||
egl_error != EGL_SUCCESS)
{
printf("eglQueryDevicesEXT Failed.\n");
m_data->egl_display = EGL_NO_DISPLAY;
} else
{
// default case, should always happen (for future compatibility)
if (m_data->m_renderDevice == -1)
{
// check env variable
const char* env_p = std::getenv("EGL_VISIBLE_DEVICES");
// variable is set
if(env_p != NULL)
{
m_data->m_renderDevice = std::atoi(env_p);
fprintf(stderr, "EGL device choice: %d of %d (from EGL_VISIBLE_DEVICES)\n", m_data->m_renderDevice, num_devices);
} else {
fprintf(stderr, "EGL device choice: %d of %d.\n", m_data->m_renderDevice, num_devices);
} // else leave with -1
} else
{
fprintf(stderr, "EGL device choice: %d of %d.\n", m_data->m_renderDevice, num_devices);
}
}
// Query EGL Screens
if (m_data->m_renderDevice == -1)
{
// Chose default screen, by trying all
for (EGLint i = 0; i < num_devices; ++i)
{
// Set display
EGLDisplay display = eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT,
egl_devices[i], NULL);
if (eglGetError() == EGL_SUCCESS && display != EGL_NO_DISPLAY)
{
int major, minor;
EGLBoolean initialized = eglInitialize(display, &major, &minor);
if (eglGetError() == EGL_SUCCESS && initialized == EGL_TRUE)
{
m_data->egl_display = display;
break;
}
}
else
{
fprintf(stderr, "GetDisplay %d failed with error: %x\n", i, eglGetError());
}
}
}
else
{
// Chose specific screen, by using m_renderDevice
if (m_data->m_renderDevice < 0 || m_data->m_renderDevice >= num_devices)
{
fprintf(stderr, "Invalid render_device choice: %d < %d.\n", m_data->m_renderDevice, num_devices);
exit(EXIT_FAILURE);
}
// Set display
EGLDisplay display = eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT,
egl_devices[m_data->m_renderDevice], NULL);
if (eglGetError() == EGL_SUCCESS && display != EGL_NO_DISPLAY)
{
int major, minor;
EGLBoolean initialized = eglInitialize(display, &major, &minor);
if (eglGetError() == EGL_SUCCESS && initialized == EGL_TRUE)
{
m_data->egl_display = display;
}
}
else
{
fprintf(stderr, "GetDisplay %d failed with error: %x\n", m_data->m_renderDevice, eglGetError());
}
}
if (!eglInitialize(m_data->egl_display, NULL, NULL))
{
fprintf(stderr, "eglInitialize() failed with error: %x\n", eglGetError());
exit(EXIT_FAILURE);
}
egl_version = gladLoaderLoadEGL(m_data->egl_display);
if (!egl_version)
{
fprintf(stderr, "Unable to reload EGL.\n");
exit(EXIT_FAILURE);
}
printf("Loaded EGL %d.%d after reload.\n", GLAD_VERSION_MAJOR(egl_version),
GLAD_VERSION_MINOR(egl_version));
m_data->success = eglBindAPI(EGL_OPENGL_API);
if (!m_data->success)
{
// TODO: Properly handle this error (requires change to default window
// API to change return on all window types to bool).
fprintf(stderr, "Failed to bind OpenGL API.\n");
exit(EXIT_FAILURE);
}
m_data->success =
eglChooseConfig(m_data->egl_display, egl_config_attribs,
&m_data->egl_config, 1, &m_data->num_configs);
if (!m_data->success)
{
// TODO: Properly handle this error (requires change to default window
// API to change return on all window types to bool).
fprintf(stderr, "Failed to choose config (eglError: %d)\n", eglGetError());
exit(EXIT_FAILURE);
}
if (m_data->num_configs != 1)
{
fprintf(stderr, "Didn't get exactly one config, but %d\n", m_data->num_configs);
exit(EXIT_FAILURE);
}
m_data->egl_surface = eglCreatePbufferSurface(
m_data->egl_display, m_data->egl_config, egl_pbuffer_attribs);
if (m_data->egl_surface == EGL_NO_SURFACE)
{
fprintf(stderr, "Unable to create EGL surface (eglError: %d)\n", eglGetError());
exit(EXIT_FAILURE);
}
m_data->egl_context = eglCreateContext(
m_data->egl_display, m_data->egl_config, EGL_NO_CONTEXT, NULL);
if (!m_data->egl_context)
{
fprintf(stderr, "Unable to create EGL context (eglError: %d)\n", eglGetError());
exit(EXIT_FAILURE);
}
m_data->success =
eglMakeCurrent(m_data->egl_display, m_data->egl_surface, m_data->egl_surface,
m_data->egl_context);
if (!m_data->success)
{
fprintf(stderr, "Failed to make context current (eglError: %d)\n", eglGetError());
exit(EXIT_FAILURE);
}
if (!gladLoadGL((GLADloadfunc)eglGetProcAddress))
{
fprintf(stderr, "failed to load GL with glad.\n");
exit(EXIT_FAILURE);
}
const GLubyte* ven = glGetString(GL_VENDOR);
printf("GL_VENDOR=%s\n", ven);
const GLubyte* ren = glGetString(GL_RENDERER);
printf("GL_RENDERER=%s\n", ren);
const GLubyte* ver = glGetString(GL_VERSION);
printf("GL_VERSION=%s\n", ver);
const GLubyte* sl = glGetString(GL_SHADING_LANGUAGE_VERSION);
printf("GL_SHADING_LANGUAGE_VERSION=%s\n", sl);
glViewport(0,0,m_data->m_windowWidth, m_data->m_windowHeight);
//int i = pthread_getconcurrency();
//printf("pthread_getconcurrency()=%d\n", i);
}
void EGLOpenGLWindow::closeWindow()
{
eglMakeCurrent(m_data->egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE,
EGL_NO_CONTEXT);
eglDestroySurface(m_data->egl_display, m_data->egl_surface);
eglDestroyContext(m_data->egl_display, m_data->egl_context);
printf("Destroy EGL OpenGL window.\n");
}
void EGLOpenGLWindow::runMainLoop() {}
float EGLOpenGLWindow::getTimeInSeconds() { return 0.; }
bool EGLOpenGLWindow::requestedExit() const { return false; }
void EGLOpenGLWindow::setRequestExit() {}
void EGLOpenGLWindow::startRendering()
{
// printf("EGL window start rendering.\n");
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
}
void EGLOpenGLWindow::endRendering()
{
// printf("EGL window end rendering.\n");
eglSwapBuffers(m_data->egl_display, m_data->egl_surface);
}
bool EGLOpenGLWindow::isModifierKeyPressed(int key) { return false; }
void EGLOpenGLWindow::setMouseMoveCallback(b3MouseMoveCallback mouseCallback)
{
m_data->m_mouseMoveCallback = mouseCallback;
}
b3MouseMoveCallback EGLOpenGLWindow::getMouseMoveCallback()
{
return m_data->m_mouseMoveCallback;
}
void EGLOpenGLWindow::setMouseButtonCallback(
b3MouseButtonCallback mouseCallback)
{
m_data->m_mouseButtonCallback = mouseCallback;
}
b3MouseButtonCallback EGLOpenGLWindow::getMouseButtonCallback()
{
return m_data->m_mouseButtonCallback;
}
void EGLOpenGLWindow::setResizeCallback(b3ResizeCallback resizeCallback)
{
m_data->m_resizeCallback = resizeCallback;
}
b3ResizeCallback EGLOpenGLWindow::getResizeCallback()
{
return m_data->m_resizeCallback;
}
void EGLOpenGLWindow::setWheelCallback(b3WheelCallback wheelCallback)
{
m_data->m_wheelCallback = wheelCallback;
}
b3WheelCallback EGLOpenGLWindow::getWheelCallback()
{
return m_data->m_wheelCallback;
}
void EGLOpenGLWindow::setKeyboardCallback(b3KeyboardCallback keyboardCallback)
{
m_data->m_keyboardCallback = keyboardCallback;
}
b3KeyboardCallback EGLOpenGLWindow::getKeyboardCallback()
{
return m_data->m_keyboardCallback;
}
void EGLOpenGLWindow::setRenderCallback(b3RenderCallback renderCallback) {}
void EGLOpenGLWindow::setWindowTitle(const char* title) {}
float EGLOpenGLWindow::getRetinaScale() const { return 1.f; }
void EGLOpenGLWindow::setAllowRetina(bool allow) {}
int EGLOpenGLWindow::getWidth() const { return m_data->m_windowWidth; }
int EGLOpenGLWindow::getHeight() const { return m_data->m_windowHeight; }
int EGLOpenGLWindow::fileOpenDialog(char* fileName, int maxFileNameLength)
{
return 0;
}
#endif // BT_USE_EGL

View file

@ -0,0 +1,71 @@
#ifndef EGL_OPENGL_WINDOW_H
#define EGL_OPENGL_WINDOW_H
#ifdef BT_USE_EGL
#include "../CommonInterfaces/CommonWindowInterface.h"
class EGLOpenGLWindow : public CommonWindowInterface
{
struct EGLInternalData2* m_data;
bool m_OpenGLInitialized;
bool m_requestedExit;
public:
EGLOpenGLWindow();
virtual ~EGLOpenGLWindow();
virtual void createDefaultWindow(int width, int height, const char* title)
{
b3gWindowConstructionInfo ci(width, height);
ci.m_title = title;
createWindow(ci);
}
virtual void createWindow(const b3gWindowConstructionInfo& ci);
virtual void closeWindow();
virtual void runMainLoop();
virtual float getTimeInSeconds();
virtual bool requestedExit() const;
virtual void setRequestExit();
virtual void startRendering();
virtual void endRendering();
virtual bool isModifierKeyPressed(int key);
virtual void setMouseMoveCallback(b3MouseMoveCallback mouseCallback);
virtual b3MouseMoveCallback getMouseMoveCallback();
virtual void setMouseButtonCallback(b3MouseButtonCallback mouseCallback);
virtual b3MouseButtonCallback getMouseButtonCallback();
virtual void setResizeCallback(b3ResizeCallback resizeCallback);
virtual b3ResizeCallback getResizeCallback();
virtual void setWheelCallback(b3WheelCallback wheelCallback);
virtual b3WheelCallback getWheelCallback();
virtual void setKeyboardCallback(b3KeyboardCallback keyboardCallback);
virtual b3KeyboardCallback getKeyboardCallback();
virtual void setRenderCallback(b3RenderCallback renderCallback);
virtual void setWindowTitle(const char* title);
virtual float getRetinaScale() const;
virtual void setAllowRetina(bool allow);
virtual int getWidth() const;
virtual int getHeight() const;
virtual int fileOpenDialog(char* fileName, int maxFileNameLength);
};
#endif //BT_USE_EGL
#endif //EGL_OPENGL_WINDOW_H

View file

@ -0,0 +1,593 @@
#ifdef B3_USE_GLFW
#include "GLFWOpenGLWindow.h"
#include <glad/gl.h>
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>
#include "LinearMath/btScalar.h"
struct GLFWOpenGLWindowInternalData
{
bool m_requestedExit;
bool m_hasCursorPos;
bool m_altPressed;
bool m_shiftPressed;
bool m_ctrlPressed;
float m_cursorXPos;
float m_cursorYPos;
b3MouseMoveCallback m_mouseMoveCallback;
b3MouseButtonCallback m_mouseButtonCallback;
b3ResizeCallback m_resizeCallback;
b3WheelCallback m_wheelCallback;
b3KeyboardCallback m_keyboardCallback;
b3RenderCallback m_renderCallback;
int m_width;
int m_height;
float m_retinaScaleFactor;
GLFWwindow* m_glfwWindow;
GLFWOpenGLWindowInternalData()
: m_requestedExit(false),
m_hasCursorPos(false),
m_altPressed(false),
m_shiftPressed(false),
m_ctrlPressed(false),
m_cursorXPos(0),
m_cursorYPos(0),
m_mouseMoveCallback(0),
m_mouseButtonCallback(0),
m_resizeCallback(0),
m_wheelCallback(0),
m_keyboardCallback(0),
m_renderCallback(0),
m_width(0),
m_height(0),
m_retinaScaleFactor(1),
m_glfwWindow(0)
{
}
};
static void GLFWErrorCallback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void GLFWMouseButtonCallback(GLFWwindow* window, int button, int glfwState, int)
{
GLFWOpenGLWindow* wnd = (GLFWOpenGLWindow*)glfwGetWindowUserPointer(window);
if (wnd && wnd->getMouseButtonCallback())
{
int state = (glfwState == GLFW_PRESS) ? 1 : 0;
wnd->mouseButtonCallbackInternal(button, state);
}
}
static void GLFWScrollCallback(GLFWwindow* window, double deltaX, double deltaY)
{
GLFWOpenGLWindow* wnd = (GLFWOpenGLWindow*)glfwGetWindowUserPointer(window);
if (wnd && wnd->getWheelCallback())
{
wnd->getWheelCallback()(deltaX * 100, deltaY * 100);
}
}
static void GLFWCursorPosCallback(GLFWwindow* window, double xPos, double yPos)
{
GLFWOpenGLWindow* wnd = (GLFWOpenGLWindow*)glfwGetWindowUserPointer(window);
if (wnd && wnd->getMouseMoveCallback())
{
wnd->mouseCursorCallbackInternal(xPos, yPos);
}
}
static void GLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
GLFWOpenGLWindow* wnd = (GLFWOpenGLWindow*)glfwGetWindowUserPointer(window);
if (wnd)
{
wnd->keyboardCallbackInternal(key, action);
}
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
}
static void GLFWSizeCallback(GLFWwindow* window, int width, int height)
{
GLFWOpenGLWindow* wnd = (GLFWOpenGLWindow*)glfwGetWindowUserPointer(window);
{
wnd->resizeInternal(width, height);
}
}
GLFWOpenGLWindow::GLFWOpenGLWindow()
{
m_data = new GLFWOpenGLWindowInternalData();
}
GLFWOpenGLWindow::~GLFWOpenGLWindow()
{
if (m_data->m_glfwWindow)
{
closeWindow();
}
delete m_data;
}
int getBulletKeyFromGLFWKeycode(int glfwKeyCode)
{
int keycode = -1;
if (glfwKeyCode >= 'A' && glfwKeyCode <= 'Z')
{
return glfwKeyCode + 32; //todo: fix the ascii A vs a input
}
if (glfwKeyCode >= '0' && glfwKeyCode <= '9')
{
return glfwKeyCode;
}
switch (glfwKeyCode)
{
case GLFW_KEY_ENTER:
{
keycode = B3G_RETURN;
break;
};
case GLFW_KEY_ESCAPE:
{
keycode = B3G_ESCAPE;
break;
};
case GLFW_KEY_F1:
{
keycode = B3G_F1;
break;
}
case GLFW_KEY_F2:
{
keycode = B3G_F2;
break;
}
case GLFW_KEY_F3:
{
keycode = B3G_F3;
break;
}
case GLFW_KEY_F4:
{
keycode = B3G_F4;
break;
}
case GLFW_KEY_F5:
{
keycode = B3G_F5;
break;
}
case GLFW_KEY_F6:
{
keycode = B3G_F6;
break;
}
case GLFW_KEY_F7:
{
keycode = B3G_F7;
break;
}
case GLFW_KEY_F8:
{
keycode = B3G_F8;
break;
}
case GLFW_KEY_F9:
{
keycode = B3G_F9;
break;
}
case GLFW_KEY_F10:
{
keycode = B3G_F10;
break;
}
//case GLFW_KEY_SPACE: {keycode= ' '; break;}
case GLFW_KEY_PAGE_DOWN:
{
keycode = B3G_PAGE_DOWN;
break;
}
case GLFW_KEY_PAGE_UP:
{
keycode = B3G_PAGE_UP;
break;
}
case GLFW_KEY_INSERT:
{
keycode = B3G_INSERT;
break;
}
case GLFW_KEY_BACKSPACE:
{
keycode = B3G_BACKSPACE;
break;
}
case GLFW_KEY_DELETE:
{
keycode = B3G_DELETE;
break;
}
case GLFW_KEY_END:
{
keycode = B3G_END;
break;
}
case GLFW_KEY_HOME:
{
keycode = B3G_HOME;
break;
}
case GLFW_KEY_LEFT:
{
keycode = B3G_LEFT_ARROW;
break;
}
case GLFW_KEY_UP:
{
keycode = B3G_UP_ARROW;
break;
}
case GLFW_KEY_RIGHT:
{
keycode = B3G_RIGHT_ARROW;
break;
}
case GLFW_KEY_DOWN:
{
keycode = B3G_DOWN_ARROW;
break;
}
case GLFW_KEY_RIGHT_SHIFT:
{
keycode = B3G_SHIFT;
break;
}
case GLFW_KEY_LEFT_SHIFT:
{
keycode = B3G_SHIFT;
break;
}
case GLFW_KEY_MENU:
{
keycode = B3G_ALT;
break;
}
case GLFW_KEY_RIGHT_CONTROL:
{
keycode = B3G_CONTROL;
break;
}
case GLFW_KEY_LEFT_CONTROL:
{
keycode = B3G_CONTROL;
break;
}
default:
{
//keycode = MapVirtualKey( virtualKeyCode, MAPGLFW_KEY_GLFW_KEY_TO_CHAR ) & 0x0000FFFF;
}
};
return keycode;
}
void GLFWOpenGLWindow::keyboardCallbackInternal(int key, int state)
{
if (getKeyboardCallback())
{
//convert keyboard codes from glfw to bullet
int btcode = getBulletKeyFromGLFWKeycode(key);
int btstate = (state == GLFW_RELEASE) ? 0 : 1;
switch (btcode)
{
case B3G_SHIFT:
{
m_data->m_shiftPressed = state != 0;
break;
}
case B3G_ALT:
{
m_data->m_altPressed = state != 0;
break;
}
case B3G_CONTROL:
{
m_data->m_ctrlPressed = state != 0;
break;
}
default:
{
}
}
getKeyboardCallback()(btcode, btstate);
}
}
void GLFWOpenGLWindow::mouseButtonCallbackInternal(int button, int state)
{
if (getMouseButtonCallback() && m_data->m_hasCursorPos)
{
getMouseButtonCallback()(button, state, m_data->m_cursorXPos, m_data->m_cursorYPos);
}
}
void GLFWOpenGLWindow::mouseCursorCallbackInternal(double xPos, double yPos)
{
if (getMouseMoveCallback())
{
m_data->m_hasCursorPos = true;
m_data->m_cursorXPos = xPos;
m_data->m_cursorYPos = yPos;
getMouseMoveCallback()(xPos, yPos);
}
}
void GLFWOpenGLWindow::resizeInternal(int width, int height)
{
glfwGetFramebufferSize(m_data->m_glfwWindow, &m_data->m_width, &m_data->m_height);
glViewport(0, 0, m_data->m_width, m_data->m_height);
if (getResizeCallback())
{
getResizeCallback()(m_data->m_width / m_data->m_retinaScaleFactor, m_data->m_height / m_data->m_retinaScaleFactor);
}
}
void GLFWOpenGLWindow::createDefaultWindow(int width, int height, const char* title)
{
b3gWindowConstructionInfo ci;
ci.m_width = width;
ci.m_height = height;
ci.m_title = title;
createWindow(ci);
}
void GLFWOpenGLWindow::createWindow(const b3gWindowConstructionInfo& ci)
{
btAssert(m_data->m_glfwWindow == 0);
if (m_data->m_glfwWindow == 0)
{
glfwSetErrorCallback(GLFWErrorCallback);
if (!glfwInit())
exit(EXIT_FAILURE);
if (ci.m_openglVersion == 2)
{
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
}
else
{
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
}
m_data->m_glfwWindow = glfwCreateWindow(ci.m_width, ci.m_height, ci.m_title, NULL, NULL);
if (!m_data->m_glfwWindow)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetKeyCallback(m_data->m_glfwWindow, GLFWKeyCallback);
glfwSetMouseButtonCallback(m_data->m_glfwWindow, GLFWMouseButtonCallback);
glfwSetCursorPosCallback(m_data->m_glfwWindow, GLFWCursorPosCallback);
glfwSetScrollCallback(m_data->m_glfwWindow, GLFWScrollCallback);
glfwSetWindowSizeCallback(m_data->m_glfwWindow, GLFWSizeCallback);
glfwSetWindowUserPointer(m_data->m_glfwWindow, this);
glfwMakeContextCurrent(m_data->m_glfwWindow);
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
glfwSwapInterval(0); //1);
glfwGetFramebufferSize(m_data->m_glfwWindow, &m_data->m_width, &m_data->m_height);
int windowWidth, windowHeight;
glfwGetWindowSize(m_data->m_glfwWindow, &windowWidth, &windowHeight);
m_data->m_retinaScaleFactor = float(m_data->m_width) / float(windowWidth);
glViewport(0, 0, m_data->m_width, m_data->m_height);
}
}
void GLFWOpenGLWindow::closeWindow()
{
if (m_data->m_glfwWindow)
{
glfwDestroyWindow(m_data->m_glfwWindow);
glfwTerminate();
m_data->m_glfwWindow = 0;
}
}
void GLFWOpenGLWindow::runMainLoop()
{
}
float GLFWOpenGLWindow::getTimeInSeconds()
{
return 0.f;
}
bool GLFWOpenGLWindow::requestedExit() const
{
bool shouldClose = m_data->m_requestedExit;
if (m_data->m_glfwWindow)
{
shouldClose = shouldClose || glfwWindowShouldClose(m_data->m_glfwWindow);
}
return shouldClose;
}
void GLFWOpenGLWindow::setRequestExit()
{
if (m_data->m_glfwWindow)
{
glfwSetWindowShouldClose(m_data->m_glfwWindow, GLFW_TRUE);
}
m_data->m_requestedExit = true;
}
void GLFWOpenGLWindow::startRendering()
{
if (m_data->m_glfwWindow)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
}
void GLFWOpenGLWindow::endRendering()
{
glfwPollEvents();
glfwSwapBuffers(m_data->m_glfwWindow);
}
bool GLFWOpenGLWindow::isModifierKeyPressed(int key)
{
bool result = false;
switch (key)
{
case B3G_SHIFT:
{
result = m_data->m_shiftPressed;
break;
}
case B3G_ALT:
{
result = m_data->m_altPressed;
break;
}
case B3G_CONTROL:
{
result = m_data->m_ctrlPressed;
break;
}
default:
{
}
}
return result;
}
void GLFWOpenGLWindow::setMouseMoveCallback(b3MouseMoveCallback mouseCallback)
{
m_data->m_mouseMoveCallback = mouseCallback;
}
b3MouseMoveCallback GLFWOpenGLWindow::getMouseMoveCallback()
{
return m_data->m_mouseMoveCallback;
}
void GLFWOpenGLWindow::setMouseButtonCallback(b3MouseButtonCallback mouseCallback)
{
m_data->m_mouseButtonCallback = mouseCallback;
}
b3MouseButtonCallback GLFWOpenGLWindow::getMouseButtonCallback()
{
return m_data->m_mouseButtonCallback;
}
void GLFWOpenGLWindow::setResizeCallback(b3ResizeCallback resizeCallback)
{
m_data->m_resizeCallback = resizeCallback;
getResizeCallback()(m_data->m_width / getRetinaScale(), m_data->m_height / getRetinaScale());
}
b3ResizeCallback GLFWOpenGLWindow::getResizeCallback()
{
return m_data->m_resizeCallback;
}
void GLFWOpenGLWindow::setWheelCallback(b3WheelCallback wheelCallback)
{
m_data->m_wheelCallback = wheelCallback;
}
b3WheelCallback GLFWOpenGLWindow::getWheelCallback()
{
return m_data->m_wheelCallback;
}
void GLFWOpenGLWindow::setKeyboardCallback(b3KeyboardCallback keyboardCallback)
{
m_data->m_keyboardCallback = keyboardCallback;
}
b3KeyboardCallback GLFWOpenGLWindow::getKeyboardCallback()
{
return m_data->m_keyboardCallback;
}
void GLFWOpenGLWindow::setRenderCallback(b3RenderCallback renderCallback)
{
m_data->m_renderCallback = renderCallback;
}
void GLFWOpenGLWindow::setWindowTitle(const char* title)
{
if (m_data->m_glfwWindow)
{
glfwSetWindowTitle(m_data->m_glfwWindow, title);
}
}
float GLFWOpenGLWindow::getRetinaScale() const
{
return m_data->m_retinaScaleFactor;
}
void GLFWOpenGLWindow::setAllowRetina(bool allow)
{
}
int GLFWOpenGLWindow::getWidth() const
{
if (m_data->m_glfwWindow)
{
glfwGetFramebufferSize(m_data->m_glfwWindow, &m_data->m_width, &m_data->m_height);
}
int width = m_data->m_width / m_data->m_retinaScaleFactor;
return width;
}
int GLFWOpenGLWindow::getHeight() const
{
if (m_data->m_glfwWindow)
{
glfwGetFramebufferSize(m_data->m_glfwWindow, &m_data->m_width, &m_data->m_height);
}
return m_data->m_height / m_data->m_retinaScaleFactor;
}
int GLFWOpenGLWindow::fileOpenDialog(char* fileName, int maxFileNameLength)
{
return 0;
}
#endif //B3_USE_GLFW

View file

@ -0,0 +1,72 @@
#ifndef GLFW_OPENGL_WINDOW_H
#define GLFW_OPENGL_WINDOW_H
#ifdef B3_USE_GLFW
#include "../CommonInterfaces/CommonWindowInterface.h"
#define b3gDefaultOpenGLWindow GLFWOpenGLWindow
class GLFWOpenGLWindow : public CommonWindowInterface
{
struct GLFWOpenGLWindowInternalData* m_data;
protected:
public:
GLFWOpenGLWindow();
virtual ~GLFWOpenGLWindow();
virtual void createDefaultWindow(int width, int height, const char* title);
virtual void createWindow(const b3gWindowConstructionInfo& ci);
virtual void closeWindow();
virtual void runMainLoop();
virtual float getTimeInSeconds();
virtual bool requestedExit() const;
virtual void setRequestExit();
virtual void startRendering();
virtual void endRendering();
virtual bool isModifierKeyPressed(int key);
virtual void setMouseMoveCallback(b3MouseMoveCallback mouseCallback);
virtual b3MouseMoveCallback getMouseMoveCallback();
virtual void setMouseButtonCallback(b3MouseButtonCallback mouseCallback);
virtual b3MouseButtonCallback getMouseButtonCallback();
virtual void setResizeCallback(b3ResizeCallback resizeCallback);
virtual b3ResizeCallback getResizeCallback();
virtual void setWheelCallback(b3WheelCallback wheelCallback);
virtual b3WheelCallback getWheelCallback();
virtual void setKeyboardCallback(b3KeyboardCallback keyboardCallback);
virtual b3KeyboardCallback getKeyboardCallback();
virtual void setRenderCallback(b3RenderCallback renderCallback);
virtual void setWindowTitle(const char* title);
virtual float getRetinaScale() const;
virtual void setAllowRetina(bool allow);
virtual int getWidth() const;
virtual int getHeight() const;
virtual int fileOpenDialog(char* fileName, int maxFileNameLength);
void keyboardCallbackInternal(int key, int state);
void mouseButtonCallbackInternal(int button, int state);
void mouseCursorCallbackInternal(double xPos, double yPos);
void resizeInternal(int width, int height);
};
#endif //B3_USE_GLFW
#endif //GLFW_OPENGL_WINDOW_H

View file

@ -0,0 +1,33 @@
#ifndef GL_INSTANCE_GRAPHICS_SHAPE_H
#define GL_INSTANCE_GRAPHICS_SHAPE_H
#include "Bullet3Common/b3AlignedObjectArray.h"
struct GLInstanceVertex
{
float xyzw[4];
float normal[3];
float uv[2];
};
struct GLInstanceGraphicsShape
{
b3AlignedObjectArray<GLInstanceVertex>* m_vertices;
int m_numvertices;
b3AlignedObjectArray<int>* m_indices;
int m_numIndices;
float m_scaling[4];
GLInstanceGraphicsShape()
: m_vertices(0),
m_indices(0)
{
}
virtual ~GLInstanceGraphicsShape()
{
delete m_vertices;
delete m_indices;
}
};
#endif //GL_INSTANCE_GRAPHICS_SHAPE_H

View file

@ -0,0 +1,21 @@
#ifndef GL_INSTANCE_RENDERER_INTERNAL_DATA_H
#define GL_INSTANCE_RENDERER_INTERNAL_DATA_H
#include "OpenGLInclude.h"
#include "Bullet3Common/b3AlignedObjectArray.h"
struct GLInstanceRendererInternalData
{
b3AlignedObjectArray<GLfloat> m_instance_positions_ptr;
b3AlignedObjectArray<GLfloat> m_instance_quaternion_ptr;
b3AlignedObjectArray<GLfloat> m_instance_colors_ptr;
b3AlignedObjectArray<GLfloat> m_instance_scale_ptr;
int m_vboSize;
GLuint m_vbo;
int m_totalNumInstances;
int m_maxNumObjectCapacity;
int m_maxShapeCapacityInBytes;
};
#endif //GL_INSTANCE_RENDERER_INTERNAL_DATA_H

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,156 @@
/*
Copyright (c) 2012 Advanced Micro Devices, Inc.
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
//Originally written by Erwin Coumans
#ifndef GL_INSTANCING_RENDERER_H
#define GL_INSTANCING_RENDERER_H
#include "Bullet3Common/b3AlignedObjectArray.h"
#include "../CommonInterfaces/CommonRenderInterface.h"
#include "SimpleCamera.h"
class GLInstancingRenderer : public CommonRenderInterface
{
b3AlignedObjectArray<struct b3GraphicsInstance*> m_graphicsInstances;
struct InternalDataRenderer* m_data;
bool m_textureenabled;
bool m_textureinitialized;
int m_screenWidth;
int m_screenHeight;
int m_upAxis;
int m_planeReflectionShapeIndex;
int registerGraphicsInstanceInternal(int shapeIndex, const float* position, const float* quaternion, const float* color, const float* scaling);
void rebuildGraphicsInstances();
public:
GLInstancingRenderer(int m_maxObjectCapacity, int maxShapeCapacityInBytes = 56 * 1024 * 1024);
virtual ~GLInstancingRenderer();
virtual void init();
virtual void renderScene();
virtual void renderSceneInternal(int orgRenderMode = B3_DEFAULT_RENDERMODE);
void InitShaders();
void CleanupShaders();
virtual void removeAllInstances();
virtual void removeGraphicsInstance(int instanceUid);
virtual void updateShape(int shapeIndex, const float* vertices, int numVertices);
///vertices must be in the format x,y,z, nx,ny,nz, u,v
virtual int registerShape(const float* vertices, int numvertices, const int* indices, int numIndices, int primitiveType = B3_GL_TRIANGLES, int textureIndex = -1);
virtual int registerTexture(const unsigned char* texels, int width, int height, bool flipPixelsY = true);
virtual void updateTexture(int textureIndex, const unsigned char* texels, bool flipPixelsY = true);
virtual void activateTexture(int textureIndex);
virtual void replaceTexture(int shapeIndex, int textureId);
virtual int getShapeIndexFromInstance(int srcIndex);
virtual void removeTexture(int textureIndex);
///position x,y,z, quaternion x,y,z,w, color r,g,b,a, scaling x,y,z
virtual int registerGraphicsInstance(int shapeIndex, const float* position, const float* quaternion, const float* color, const float* scaling);
virtual int registerGraphicsInstance(int shapeIndex, const double* position, const double* quaternion, const double* color, const double* scaling);
void writeTransforms();
virtual bool readSingleInstanceTransformToCPU(float* position, float* orientation, int srcIndex);
virtual void writeSingleInstanceTransformToCPU(const float* position, const float* orientation, int srcIndex);
virtual void writeSingleInstanceTransformToCPU(const double* position, const double* orientation, int srcIndex)
{
float pos[4];
float orn[4];
pos[0] = (float)position[0];
pos[1] = (float)position[1];
pos[2] = (float)position[2];
pos[3] = (float)position[3];
orn[0] = (float)orientation[0];
orn[1] = (float)orientation[1];
orn[2] = (float)orientation[2];
orn[3] = (float)orientation[3];
writeSingleInstanceTransformToCPU(pos, orn, srcIndex);
}
virtual void readSingleInstanceTransformFromCPU(int srcIndex, float* position, float* orientation);
virtual void writeSingleInstanceTransformToGPU(float* position, float* orientation, int srcIndex);
virtual void writeSingleInstanceColorToCPU(const float* color, int srcIndex);
virtual void writeSingleInstanceColorToCPU(const double* color, int srcIndex);
virtual void writeSingleInstanceFlagsToCPU(int flags, int srcIndex2);
virtual void writeSingleInstanceSpecularColorToCPU(const double* specular, int srcIndex2);
virtual void writeSingleInstanceSpecularColorToCPU(const float* specular, int srcIndex2);
virtual void writeSingleInstanceScaleToCPU(const float* scale, int srcIndex);
virtual void writeSingleInstanceScaleToCPU(const double* scale, int srcIndex);
virtual struct GLInstanceRendererInternalData* getInternalData();
virtual void drawLine(const float from[4], const float to[4], const float color[4], float lineWidth = 1);
virtual void drawLine(const double from[4], const double to[4], const double color[4], double lineWidth = 1);
virtual void drawLines(const float* positions, const float color[4], int numPoints, int pointStrideInBytes, const unsigned int* indices, int numIndices, float pointDrawSize);
virtual void drawPoints(const float* positions, const float color[4], int numPoints, int pointStrideInBytes, float pointDrawSize);
virtual void drawPoint(const float* position, const float color[4], float pointSize = 1);
virtual void drawPoint(const double* position, const double color[4], double pointDrawSize = 1);
virtual void drawTexturedTriangleMesh(float worldPosition[3], float worldOrientation[4], const float* vertices, int numvertices, const unsigned int* indices, int numIndices, float color[4], int textureIndex = -1, int vertexLayout = 0);
virtual void updateCamera(int upAxis = 1);
virtual const CommonCameraInterface* getActiveCamera() const;
virtual CommonCameraInterface* getActiveCamera();
virtual void setActiveCamera(CommonCameraInterface* cam);
virtual void setLightPosition(const float lightPos[3]);
virtual void setLightPosition(const double lightPos[3]);
virtual void setShadowMapResolution(int shadowMapResolution);
virtual void setShadowMapIntensity(double shadowMapIntensity);
virtual void setShadowMapWorldSize(float worldSize);
void setLightSpecularIntensity(const float lightSpecularIntensity[3]);
virtual void setProjectiveTextureMatrices(const float viewMatrix[16], const float projectionMatrix[16]);
virtual void setProjectiveTexture(bool useProjectiveTexture);
virtual void setBackgroundColor(const double rgbBackground[3]);
virtual void resize(int width, int height);
virtual int getScreenWidth()
{
return m_screenWidth;
}
virtual int getScreenHeight()
{
return m_screenHeight;
}
virtual int getMaxShapeCapacity() const;
virtual int getInstanceCapacity() const;
virtual int getTotalNumInstances() const;
virtual void enableShadowMap();
virtual void setPlaneReflectionShapeIndex(int index);
virtual void clearZBuffer();
virtual void setRenderFrameBuffer(unsigned int renderFrameBuffer);
};
#endif //GL_INSTANCING_RENDERER_H

View file

@ -0,0 +1,26 @@
#ifndef PRIM_INTERNAL_DATA
#define PRIM_INTERNAL_DATA
#include "OpenGLInclude.h"
struct PrimInternalData
{
GLuint m_shaderProg;
GLint m_viewmatUniform;
GLint m_projMatUniform;
GLint m_positionUniform;
GLint m_colourAttribute;
GLint m_positionAttribute;
GLint m_textureAttribute;
GLuint m_vertexBuffer;
GLuint m_vertexBuffer2;
GLuint m_vertexArrayObject;
GLuint m_vertexArrayObject2;
GLuint m_indexBuffer;
GLuint m_indexBuffer2;
GLuint m_texturehandle;
};
#endif //PRIM_INTERNAL_DATA

View file

@ -0,0 +1,487 @@
#ifndef NO_OPENGL3
#include "GLPrimitiveRenderer.h"
#include "GLPrimInternalData.h"
#include "Bullet3Common/b3Scalar.h"
#include "LoadShader.h"
static const char *vertexShader3D =
"#version 150 \n"
"\n"
"uniform mat4 viewMatrix, projMatrix;\n"
"in vec4 position;\n"
"in vec4 colour;\n"
"out vec4 colourV;\n"
"\n"
"in vec2 texuv;\n"
"out vec2 texuvV;\n"
"\n"
"\n"
"void main (void)\n"
"{\n"
" colourV = colour;\n"
" gl_Position = projMatrix * viewMatrix * position ;\n"
" texuvV=texuv;\n"
"}\n";
static const char *fragmentShader3D =
"#version 150\n"
"\n"
"uniform vec2 p;\n"
"in vec4 colourV;\n"
"out vec4 fragColour;\n"
"in vec2 texuvV;\n"
"\n"
"uniform sampler2D Diffuse;\n"
"\n"
"void main(void)\n"
"{\n"
" vec4 texcolor = texture(Diffuse,texuvV);\n"
" if (p.x==0.f)\n"
" {\n"
" texcolor = vec4(1,1,1,texcolor.x);\n"
" }\n"
" fragColour = colourV*texcolor;\n"
"}\n";
static unsigned int s_indexData[6] = {0, 1, 2, 0, 2, 3};
#define MAX_VERTICES2 8192
struct PrimInternalData2
{
PrimInternalData2()
: m_numVerticesText(0),
m_numVerticesRect(0)
{
}
int m_numVerticesText;
int m_numVerticesRect;
PrimVertex m_verticesText[MAX_VERTICES2];
PrimVertex m_verticesRect[MAX_VERTICES2];
};
GLPrimitiveRenderer::GLPrimitiveRenderer(int screenWidth, int screenHeight)
: m_screenWidth(screenWidth),
m_screenHeight(screenHeight)
{
m_data = new PrimInternalData;
m_data2 = new PrimInternalData2;
m_data->m_shaderProg = gltLoadShaderPair(vertexShader3D, fragmentShader3D);
m_data->m_viewmatUniform = glGetUniformLocation(m_data->m_shaderProg, "viewMatrix");
if (m_data->m_viewmatUniform < 0)
{
b3Assert(0);
}
m_data->m_projMatUniform = glGetUniformLocation(m_data->m_shaderProg, "projMatrix");
if (m_data->m_projMatUniform < 0)
{
b3Assert(0);
}
m_data->m_positionUniform = glGetUniformLocation(m_data->m_shaderProg, "p");
if (m_data->m_positionUniform < 0)
{
b3Assert(0);
}
m_data->m_colourAttribute = glGetAttribLocation(m_data->m_shaderProg, "colour");
if (m_data->m_colourAttribute < 0)
{
b3Assert(0);
}
m_data->m_positionAttribute = glGetAttribLocation(m_data->m_shaderProg, "position");
if (m_data->m_positionAttribute < 0)
{
b3Assert(0);
}
m_data->m_textureAttribute = glGetAttribLocation(m_data->m_shaderProg, "texuv");
if (m_data->m_textureAttribute < 0)
{
b3Assert(0);
}
loadBufferData();
}
void GLPrimitiveRenderer::loadBufferData()
{
PrimVertex vertexData[4] = {
PrimVertex(PrimVec4(-1, -1, 0.0, 1.0), PrimVec4(1.0, 0.0, 0.0, 1.0), PrimVec2(0, 0)),
PrimVertex(PrimVec4(-1, 1, 0.0, 1.0), PrimVec4(0.0, 1.0, 0.0, 1.0), PrimVec2(0, 1)),
PrimVertex(PrimVec4(1, 1, 0.0, 1.0), PrimVec4(0.0, 0.0, 1.0, 1.0), PrimVec2(1, 1)),
PrimVertex(PrimVec4(1, -1, 0.0, 1.0), PrimVec4(1.0, 1.0, 1.0, 1.0), PrimVec2(1, 0))};
glGenVertexArrays(1, &m_data->m_vertexArrayObject);
glBindVertexArray(m_data->m_vertexArrayObject);
glGenBuffers(1, &m_data->m_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_data->m_vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, 4 * sizeof(PrimVertex), vertexData, GL_DYNAMIC_DRAW);
glGenVertexArrays(1, &m_data->m_vertexArrayObject2);
glBindVertexArray(m_data->m_vertexArrayObject2);
glGenBuffers(1, &m_data->m_vertexBuffer2);
glBindBuffer(GL_ARRAY_BUFFER, m_data->m_vertexBuffer2);
glBufferData(GL_ARRAY_BUFFER, MAX_VERTICES2 * sizeof(PrimVertex), 0, GL_DYNAMIC_DRAW);
b3Assert(glGetError() == GL_NO_ERROR);
glGenBuffers(1, &m_data->m_indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_data->m_indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(int), s_indexData, GL_STATIC_DRAW);
unsigned int indexData[MAX_VERTICES2 * 2];
int count = 0;
for (int i = 0; i < MAX_VERTICES2; i += 4)
{
indexData[count++] = i;
indexData[count++] = i + 1;
indexData[count++] = i + 2;
indexData[count++] = i;
indexData[count++] = i + 2;
indexData[count++] = i + 3;
}
glGenBuffers(1, &m_data->m_indexBuffer2);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_data->m_indexBuffer2);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(int), indexData, GL_STATIC_DRAW);
glEnableVertexAttribArray(m_data->m_positionAttribute);
glEnableVertexAttribArray(m_data->m_colourAttribute);
b3Assert(glGetError() == GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_textureAttribute);
glVertexAttribPointer(m_data->m_positionAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(PrimVertex), (const GLvoid *)0);
glVertexAttribPointer(m_data->m_colourAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(PrimVertex), (const GLvoid *)sizeof(PrimVec4));
glVertexAttribPointer(m_data->m_textureAttribute, 2, GL_FLOAT, GL_FALSE, sizeof(PrimVertex), (const GLvoid *)(sizeof(PrimVec4) + sizeof(PrimVec4)));
b3Assert(glGetError() == GL_NO_ERROR);
glActiveTexture(GL_TEXTURE0);
GLubyte *image = new GLubyte[256 * 256 * 3];
for (int y = 0; y < 256; ++y)
{
// const int t=y>>5;
GLubyte *pi = image + y * 256 * 3;
for (int x = 0; x < 256; ++x)
{
if (x < y) //x<2||y<2||x>253||y>253)
{
pi[0] = 255;
pi[1] = 0;
pi[2] = 0;
}
else
{
pi[0] = 255;
pi[1] = 255;
pi[2] = 255;
}
pi += 3;
}
}
glGenTextures(1, (GLuint *)&m_data->m_texturehandle);
glBindTexture(GL_TEXTURE_2D, m_data->m_texturehandle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
b3Assert(glGetError() == GL_NO_ERROR);
delete[] image;
}
GLPrimitiveRenderer::~GLPrimitiveRenderer()
{
glBindTexture(GL_TEXTURE_2D, 0);
glUseProgram(0);
glBindTexture(GL_TEXTURE_2D, 0);
glDeleteProgram(m_data->m_shaderProg);
delete m_data;
delete m_data2;
}
void GLPrimitiveRenderer::drawLine()
{
}
void GLPrimitiveRenderer::drawRect(float x0, float y0, float x1, float y1, float color[4])
{
b3Assert(glGetError() == GL_NO_ERROR);
glActiveTexture(GL_TEXTURE0);
b3Assert(glGetError() == GL_NO_ERROR);
glBindTexture(GL_TEXTURE_2D, m_data->m_texturehandle);
b3Assert(glGetError() == GL_NO_ERROR);
drawTexturedRect(x0, y0, x1, y1, color, 0, 0, 1, 1);
b3Assert(glGetError() == GL_NO_ERROR);
}
void GLPrimitiveRenderer::drawTexturedRect3D(const PrimVertex &v0, const PrimVertex &v1, const PrimVertex &v2, const PrimVertex &v3, float viewMat[16], float projMat[16], bool useRGBA)
{
//B3_PROFILE("GLPrimitiveRenderer::drawTexturedRect3D");
b3Assert(glGetError() == GL_NO_ERROR);
glUseProgram(m_data->m_shaderProg);
glUniformMatrix4fv(m_data->m_viewmatUniform, 1, false, viewMat);
glUniformMatrix4fv(m_data->m_projMatUniform, 1, false, projMat);
b3Assert(glGetError() == GL_NO_ERROR);
glBindBuffer(GL_ARRAY_BUFFER, m_data->m_vertexBuffer);
glBindVertexArray(m_data->m_vertexArrayObject);
bool useFiltering = false;
if (useFiltering)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
PrimVertex vertexData[4] = {
v0, v1, v2, v3};
glBufferSubData(GL_ARRAY_BUFFER, 0, 4 * sizeof(PrimVertex), vertexData);
b3Assert(glGetError() == GL_NO_ERROR);
PrimVec2 p(0.f, 0.f); //?b?0.5f * sinf(timeValue), 0.5f * cosf(timeValue) );
if (useRGBA)
{
p.p[0] = 1.f;
p.p[1] = 1.f;
}
glUniform2fv(m_data->m_positionUniform, 1, (const GLfloat *)&p);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
b3Assert(glGetError() == GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_positionAttribute);
b3Assert(glGetError() == GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_colourAttribute);
b3Assert(glGetError() == GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_textureAttribute);
glVertexAttribPointer(m_data->m_positionAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(PrimVertex), (const GLvoid *)0);
glVertexAttribPointer(m_data->m_colourAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(PrimVertex), (const GLvoid *)sizeof(PrimVec4));
glVertexAttribPointer(m_data->m_textureAttribute, 2, GL_FLOAT, GL_FALSE, sizeof(PrimVertex), (const GLvoid *)(sizeof(PrimVec4) + sizeof(PrimVec4)));
b3Assert(glGetError() == GL_NO_ERROR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_data->m_indexBuffer);
//glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
int indexCount = 6;
b3Assert(glGetError() == GL_NO_ERROR);
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
b3Assert(glGetError() == GL_NO_ERROR);
glBindVertexArray(0);
b3Assert(glGetError() == GL_NO_ERROR);
glBindBuffer(GL_ARRAY_BUFFER, 0);
b3Assert(glGetError() == GL_NO_ERROR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
b3Assert(glGetError() == GL_NO_ERROR);
//glDisableVertexAttribArray(m_data->m_textureAttribute);
b3Assert(glGetError() == GL_NO_ERROR);
glUseProgram(0);
b3Assert(glGetError() == GL_NO_ERROR);
}
void GLPrimitiveRenderer::drawTexturedRect3D2Text(bool useRGBA)
{
drawTexturedRect3D2(&m_data2->m_verticesText[0], m_data2->m_numVerticesText, useRGBA);
m_data2->m_numVerticesText = 0;
}
void GLPrimitiveRenderer::drawTexturedRect3D2(PrimVertex *vertices, int numVertices, bool useRGBA)
{
//B3_PROFILE("drawTexturedRect3D2");
if (numVertices == 0)
{
return;
}
//B3_PROFILE("GLPrimitiveRenderer::drawTexturedRect3D");
b3Assert(glGetError() == GL_NO_ERROR);
float identity[16] = {1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1};
glUseProgram(m_data->m_shaderProg);
glUniformMatrix4fv(m_data->m_viewmatUniform, 1, false, identity);
glUniformMatrix4fv(m_data->m_projMatUniform, 1, false, identity);
b3Assert(glGetError() == GL_NO_ERROR);
glBindBuffer(GL_ARRAY_BUFFER, m_data->m_vertexBuffer2);
glBindVertexArray(m_data->m_vertexArrayObject2);
bool useFiltering = false;
if (useFiltering)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
/* PrimVertex vertexData[4] = {
v0,v1,v2,v3
};
*/
glBufferSubData(GL_ARRAY_BUFFER, 0, numVertices * sizeof(PrimVertex), vertices);
b3Assert(glGetError() == GL_NO_ERROR);
PrimVec2 p(0.f, 0.f); //?b?0.5f * sinf(timeValue), 0.5f * cosf(timeValue) );
if (useRGBA)
{
p.p[0] = 1.f;
p.p[1] = 1.f;
}
glUniform2fv(m_data->m_positionUniform, 1, (const GLfloat *)&p);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
b3Assert(glGetError() == GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_positionAttribute);
b3Assert(glGetError() == GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_colourAttribute);
b3Assert(glGetError() == GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_textureAttribute);
glVertexAttribPointer(m_data->m_positionAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(PrimVertex), (const GLvoid *)0);
glVertexAttribPointer(m_data->m_colourAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(PrimVertex), (const GLvoid *)sizeof(PrimVec4));
glVertexAttribPointer(m_data->m_textureAttribute, 2, GL_FLOAT, GL_FALSE, sizeof(PrimVertex), (const GLvoid *)(sizeof(PrimVec4) + sizeof(PrimVec4)));
b3Assert(glGetError() == GL_NO_ERROR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_data->m_indexBuffer2);
//glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
int indexCount = (numVertices / 4) * 6;
b3Assert(glGetError() == GL_NO_ERROR);
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
b3Assert(glGetError() == GL_NO_ERROR);
glBindVertexArray(0);
b3Assert(glGetError() == GL_NO_ERROR);
glBindBuffer(GL_ARRAY_BUFFER, 0);
b3Assert(glGetError() == GL_NO_ERROR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
b3Assert(glGetError() == GL_NO_ERROR);
//glDisableVertexAttribArray(m_data->m_textureAttribute);
b3Assert(glGetError() == GL_NO_ERROR);
glUseProgram(0);
b3Assert(glGetError() == GL_NO_ERROR);
}
void GLPrimitiveRenderer::drawTexturedRect2a(float x0, float y0, float x1, float y1, float color[4], float u0, float v0, float u1, float v1, int useRGBA)
{
PrimVertex vertexData[4] = {
PrimVertex(PrimVec4(-1.f + 2.f * x0 / float(m_screenWidth), 1.f - 2.f * y0 / float(m_screenHeight), 0.f, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u0, v0)),
PrimVertex(PrimVec4(-1.f + 2.f * x0 / float(m_screenWidth), 1.f - 2.f * y1 / float(m_screenHeight), 0.f, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u0, v1)),
PrimVertex(PrimVec4(-1.f + 2.f * x1 / float(m_screenWidth), 1.f - 2.f * y1 / float(m_screenHeight), 0.f, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u1, v1)),
PrimVertex(PrimVec4(-1.f + 2.f * x1 / float(m_screenWidth), 1.f - 2.f * y0 / float(m_screenHeight), 0.f, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u1, v0))};
// int sz = m_data2->m_numVerticesText;
m_data2->m_verticesRect[m_data2->m_numVerticesRect++] = vertexData[0];
m_data2->m_verticesRect[m_data2->m_numVerticesRect++] = vertexData[1];
m_data2->m_verticesRect[m_data2->m_numVerticesRect++] = vertexData[2];
m_data2->m_verticesRect[m_data2->m_numVerticesRect++] = vertexData[3];
if (m_data2->m_numVerticesRect >= MAX_VERTICES2)
{
flushBatchedRects();
}
}
void GLPrimitiveRenderer::flushBatchedRects()
{
if (m_data2->m_numVerticesRect == 0)
return;
glActiveTexture(GL_TEXTURE0);
b3Assert(glGetError() == GL_NO_ERROR);
glBindTexture(GL_TEXTURE_2D, m_data->m_texturehandle);
drawTexturedRect3D2(m_data2->m_verticesRect, m_data2->m_numVerticesRect, 0);
m_data2->m_numVerticesRect = 0;
}
void GLPrimitiveRenderer::drawTexturedRect2(float x0, float y0, float x1, float y1, float color[4], float u0, float v0, float u1, float v1, int useRGBA)
{
PrimVertex vertexData[4] = {
PrimVertex(PrimVec4(-1.f + 2.f * x0 / float(m_screenWidth), 1.f - 2.f * y0 / float(m_screenHeight), 0.f, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u0, v0)),
PrimVertex(PrimVec4(-1.f + 2.f * x0 / float(m_screenWidth), 1.f - 2.f * y1 / float(m_screenHeight), 0.f, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u0, v1)),
PrimVertex(PrimVec4(-1.f + 2.f * x1 / float(m_screenWidth), 1.f - 2.f * y1 / float(m_screenHeight), 0.f, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u1, v1)),
PrimVertex(PrimVec4(-1.f + 2.f * x1 / float(m_screenWidth), 1.f - 2.f * y0 / float(m_screenHeight), 0.f, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u1, v0))};
// int sz = m_data2->m_numVerticesText;
m_data2->m_verticesText[m_data2->m_numVerticesText++] = vertexData[0];
m_data2->m_verticesText[m_data2->m_numVerticesText++] = vertexData[1];
m_data2->m_verticesText[m_data2->m_numVerticesText++] = vertexData[2];
m_data2->m_verticesText[m_data2->m_numVerticesText++] = vertexData[3];
if (m_data2->m_numVerticesText >= MAX_VERTICES2)
{
drawTexturedRect3D2(m_data2->m_verticesText, m_data2->m_numVerticesText, useRGBA);
m_data2->m_numVerticesText = 0;
}
}
void GLPrimitiveRenderer::drawTexturedRect(float x0, float y0, float x1, float y1, float color[4], float u0, float v0, float u1, float v1, int useRGBA)
{
float identity[16] = {1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1};
PrimVertex vertexData[4] = {
PrimVertex(PrimVec4(-1.f + 2.f * x0 / float(m_screenWidth), 1.f - 2.f * y0 / float(m_screenHeight), 0.f, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u0, v0)),
PrimVertex(PrimVec4(-1.f + 2.f * x0 / float(m_screenWidth), 1.f - 2.f * y1 / float(m_screenHeight), 0.f, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u0, v1)),
PrimVertex(PrimVec4(-1.f + 2.f * x1 / float(m_screenWidth), 1.f - 2.f * y1 / float(m_screenHeight), 0.f, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u1, v1)),
PrimVertex(PrimVec4(-1.f + 2.f * x1 / float(m_screenWidth), 1.f - 2.f * y0 / float(m_screenHeight), 0.f, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u1, v0))};
drawTexturedRect3D(vertexData[0], vertexData[1], vertexData[2], vertexData[3], identity, identity, useRGBA);
}
void GLPrimitiveRenderer::setScreenSize(int width, int height)
{
m_screenWidth = width;
m_screenHeight = height;
}
#endif

View file

@ -0,0 +1,82 @@
#ifndef _GL_PRIMITIVE_RENDERER_H
#define _GL_PRIMITIVE_RENDERER_H
//#include "OpenGLInclude.h"
struct PrimVec2
{
PrimVec2()
{
}
PrimVec2(float x, float y)
{
p[0] = x;
p[1] = y;
}
float p[2];
};
struct PrimVec4
{
PrimVec4() {}
PrimVec4(float x, float y, float z, float w)
{
p[0] = x;
p[1] = y;
p[2] = z;
p[3] = w;
}
float p[4];
};
struct PrimVertex
{
PrimVertex(const PrimVec4& p, const PrimVec4& c, const PrimVec2& u)
: position(p),
colour(c),
uv(u)
{
}
PrimVertex()
{
}
PrimVec4 position;
PrimVec4 colour;
PrimVec2 uv;
};
class GLPrimitiveRenderer
{
int m_screenWidth;
int m_screenHeight;
struct PrimInternalData* m_data;
struct PrimInternalData2* m_data2;
void loadBufferData();
public:
GLPrimitiveRenderer(int screenWidth, int screenHeight);
virtual ~GLPrimitiveRenderer();
void drawRect(float x0, float y0, float x1, float y1, float color[4]);
void drawTexturedRect(float x0, float y0, float x1, float y1, float color[4], float u0, float v0, float u1, float v1, int useRGBA = 0);
void drawTexturedRect3D(const PrimVertex& v0, const PrimVertex& v1, const PrimVertex& v2, const PrimVertex& v3, float viewMat[16], float projMat[16], bool useRGBA = true);
void drawLine(); //float from[4], float to[4], float color[4]);
void setScreenSize(int width, int height);
void drawTexturedRect2(float x0, float y0, float x1, float y1, float color[4], float u0, float v0, float u1, float v1, int useRGBA = 0);
void drawTexturedRect2a(float x0, float y0, float x1, float y1, float color[4], float u0, float v0, float u1, float v1, int useRGBA = 0);
void flushBatchedRects();
void drawTexturedRect3D2Text(bool useRGBA = true);
void drawTexturedRect3D2(PrimVertex* vertices, int numVertices, bool useRGBA = true);
PrimInternalData* getData()
{
return m_data;
}
};
#endif //_GL_PRIMITIVE_RENDERER_H

View file

@ -0,0 +1,125 @@
#ifndef NO_OPENGL3
///See http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-14-render-to-texture/
#include "GLRenderToTexture.h"
#include "Bullet3Common/b3Scalar.h" // for b3Assert
#include <string.h>
#include <stdio.h>
bool gIntelLinuxglDrawBufferWorkaround = false;
GLRenderToTexture::GLRenderToTexture()
: m_framebufferName(0)
{
#if !defined(_WIN32) && !defined(__APPLE__)
const GLubyte* ven = glGetString(GL_VENDOR);
printf("ven = %s\n", ven);
if (strncmp((const char*)ven, "Intel", 5) == 0)
{
printf("Workaround for some crash in the Intel OpenGL driver on Linux/Ubuntu\n");
gIntelLinuxglDrawBufferWorkaround = true;
}
#endif //!defined(_WIN32) && !defined(__APPLE__)
}
void GLRenderToTexture::init(int width, int height, GLuint textureId, int renderTextureType)
{
m_renderTextureType = renderTextureType;
glGenFramebuffers(1, &m_framebufferName);
glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferName);
// The depth buffer
// glGenRenderbuffers(1, &m_depthrenderbuffer);
// glBindRenderbuffer(GL_RENDERBUFFER, m_depthrenderbuffer);
// glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height);
// glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthrenderbuffer);
switch (m_renderTextureType)
{
case RENDERTEXTURE_COLOR:
{
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureId, 0);
break;
}
case RENDERTEXTURE_DEPTH:
{
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, textureId, 0);
break;
}
default:
{
b3Assert(0);
}
};
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
bool GLRenderToTexture::enable()
{
bool status = false;
glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferName);
switch (m_renderTextureType)
{
case RENDERTEXTURE_COLOR:
{
// Set the list of draw buffers.
GLenum drawBuffers[2] = {GL_COLOR_ATTACHMENT0, 0};
glDrawBuffers(1, drawBuffers);
break;
}
case RENDERTEXTURE_DEPTH:
{
//Intel OpenGL driver crashes when using GL_NONE for glDrawBuffer on Linux, so use a workaround
if (gIntelLinuxglDrawBufferWorkaround)
{
GLenum drawBuffers[2] = {GL_COLOR_ATTACHMENT0, 0};
glDrawBuffers(1, drawBuffers);
}
else
{
glDrawBuffer(GL_NONE);
}
break;
}
default:
{
b3Assert(0);
}
};
// Always check that our framebuffer is ok
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
{
status = true;
}
return status;
}
void GLRenderToTexture::disable()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
GLRenderToTexture::~GLRenderToTexture()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
if (m_depthrenderbuffer)
{
glDeleteRenderbuffers(1, &m_depthrenderbuffer);
}
if (m_framebufferName)
{
glDeleteFramebuffers(1, &m_framebufferName);
}
}
#endif

View file

@ -0,0 +1,30 @@
#ifndef GL_RENDER_TO_TEXTURE_H
#define GL_RENDER_TO_TEXTURE_H
///See http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-14-render-to-texture/
#include "OpenGLInclude.h"
enum
{
RENDERTEXTURE_COLOR = 1,
RENDERTEXTURE_DEPTH,
};
struct GLRenderToTexture
{
GLuint m_framebufferName;
GLuint m_depthrenderbuffer;
bool m_initialized;
int m_renderTextureType;
public:
GLRenderToTexture();
void init(int width, int height, GLuint textureId, int renderTextureType = RENDERTEXTURE_COLOR);
bool enable();
void disable();
virtual ~GLRenderToTexture();
};
#endif //GL_RENDER_TO_TEXTURE_H

View file

@ -0,0 +1,372 @@
#ifndef __GWEN_OPENGL3_CORE_RENDERER_H
#define __GWEN_OPENGL3_CORE_RENDERER_H
#include "Gwen/Gwen.h"
#include "Gwen/BaseRender.h"
#include "GLPrimitiveRenderer.h"
#include "../OpenGLWindow/OpenGLInclude.h"
struct sth_stash;
#include "fontstash.h"
#include "Gwen/Texture.h"
#include "TwFonts.h"
static float extraSpacing = 0.; //6f;
#include <assert.h>
#include <math.h>
template <class T>
inline void MyClamp(T& a, const T& lb, const T& ub)
{
if (a < lb)
{
a = lb;
}
else if (ub < a)
{
a = ub;
}
}
static GLuint BindFont(const CTexFont* _Font)
{
GLuint TexID = 0;
glGenTextures(1, &TexID);
glBindTexture(GL_TEXTURE_2D, TexID);
glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, _Font->m_TexWidth, _Font->m_TexHeight, 0, GL_RED, GL_UNSIGNED_BYTE, _Font->m_TexBytes);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
return TexID;
}
struct MyTextureLoader
{
virtual ~MyTextureLoader()
{
}
virtual void LoadTexture(Gwen::Texture* pTexture) = 0;
virtual void FreeTexture(Gwen::Texture* pTexture) = 0;
};
class GwenOpenGL3CoreRenderer : public Gwen::Renderer::Base
{
GLPrimitiveRenderer* m_primitiveRenderer;
float m_currentColor[4];
float m_yOffset;
sth_stash* m_font;
float m_screenWidth;
float m_screenHeight;
float m_fontScaling;
float m_retinaScale;
bool m_useTrueTypeFont;
const CTexFont* m_currentFont;
GLuint m_fontTextureId;
MyTextureLoader* m_textureLoader;
public:
GwenOpenGL3CoreRenderer(GLPrimitiveRenderer* primRender, sth_stash* font, float screenWidth, float screenHeight, float retinaScale, MyTextureLoader* loader = 0)
: m_primitiveRenderer(primRender),
m_font(font),
m_screenWidth(screenWidth),
m_screenHeight(screenHeight),
m_retinaScale(retinaScale),
m_useTrueTypeFont(false),
m_textureLoader(loader)
{
///only enable true type fonts on Macbook Retina, it looks gorgeous
if (retinaScale == 2.0f)
{
m_useTrueTypeFont = true;
}
m_currentColor[0] = 1;
m_currentColor[1] = 1;
m_currentColor[2] = 1;
m_currentColor[3] = 1;
m_fontScaling = 16.f * m_retinaScale;
TwGenerateDefaultFonts();
m_currentFont = g_DefaultNormalFont;
//m_currentFont = g_DefaultNormalFontAA;
//m_currentFont = g_DefaultLargeFont;
m_fontTextureId = BindFont(m_currentFont);
}
virtual ~GwenOpenGL3CoreRenderer()
{
TwDeleteDefaultFonts();
}
virtual void Resize(int width, int height)
{
m_screenWidth = width;
m_screenHeight = height;
}
virtual void Begin()
{
m_yOffset = 0;
glEnable(GL_BLEND);
assert(glGetError() == GL_NO_ERROR);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
assert(glGetError() == GL_NO_ERROR);
assert(glGetError() == GL_NO_ERROR);
glDisable(GL_DEPTH_TEST);
assert(glGetError() == GL_NO_ERROR);
//glColor4ub(255,0,0,255);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// saveOpenGLState(width,height);//m_glutScreenWidth,m_glutScreenHeight);
assert(glGetError() == GL_NO_ERROR);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
assert(glGetError() == GL_NO_ERROR);
glEnable(GL_BLEND);
assert(glGetError() == GL_NO_ERROR);
}
virtual void End()
{
glDisable(GL_BLEND);
}
virtual void StartClip()
{
if (m_useTrueTypeFont)
sth_flush_draw(m_font);
Gwen::Rect rect = ClipRegion();
// OpenGL's coords are from the bottom left
// so we need to translate them here.
{
GLint view[4];
glGetIntegerv(GL_VIEWPORT, &view[0]);
rect.y = view[3] / m_retinaScale - (rect.y + rect.h);
}
glScissor(m_retinaScale * rect.x * Scale(), m_retinaScale * rect.y * Scale(), m_retinaScale * rect.w * Scale(), m_retinaScale * rect.h * Scale());
glEnable(GL_SCISSOR_TEST);
//glDisable( GL_SCISSOR_TEST );
};
virtual void EndClip()
{
if (m_useTrueTypeFont)
sth_flush_draw(m_font);
glDisable(GL_SCISSOR_TEST);
};
virtual void SetDrawColor(Gwen::Color color)
{
m_currentColor[0] = color.r / 256.f;
m_currentColor[1] = color.g / 256.f;
m_currentColor[2] = color.b / 256.f;
m_currentColor[3] = color.a / 256.f;
}
virtual void DrawFilledRect(Gwen::Rect rect)
{
// BT_PROFILE("GWEN_DrawFilledRect");
Translate(rect);
m_primitiveRenderer->drawRect(rect.x, rect.y + m_yOffset,
rect.x + rect.w, rect.y + rect.h + m_yOffset, m_currentColor);
// m_primitiveRenderer->drawTexturedRect2a(rect.x, rect.y+m_yOffset,
// rect.x+rect.w, rect.y+rect.h+m_yOffset, m_currentColor,0,0,1,1);
// m_yOffset+=rect.h+10;
}
void RenderText(Gwen::Font* pFont, Gwen::Point rasterPos, const Gwen::UnicodeString& text)
{
// BT_PROFILE("GWEN_RenderText");
Gwen::String str = Gwen::Utility::UnicodeToString(text);
const char* unicodeText = (const char*)str.c_str();
Gwen::Rect r;
r.x = rasterPos.x;
r.y = rasterPos.y;
r.w = 0;
r.h = 0;
//
//printf("str = %s\n",unicodeText);
//int xpos=0;
//int ypos=0;
float dx;
int measureOnly = 0;
if (m_useTrueTypeFont)
{
float yoffset = 0.f;
if (m_retinaScale == 2.0f)
{
yoffset = -12;
}
Translate(r);
sth_draw_text(m_font,
1, m_fontScaling,
r.x, r.y + yoffset,
unicodeText, &dx, m_screenWidth, m_screenHeight, measureOnly, m_retinaScale);
}
else
{
//float width = 0.f;
int pos = 0;
//float color[]={0.2f,0.2,0.2f,1.f};
glBindTexture(GL_TEXTURE_2D, m_fontTextureId);
float width = r.x;
while (unicodeText[pos])
{
int c = unicodeText[pos];
r.h = m_currentFont->m_CharHeight;
r.w = m_currentFont->m_CharWidth[c] + extraSpacing;
Gwen::Rect rect = r;
Translate(rect);
m_primitiveRenderer->drawTexturedRect2(rect.x, rect.y + m_yOffset, rect.x + rect.w, rect.y + rect.h + m_yOffset, m_currentColor, m_currentFont->m_CharU0[c], m_currentFont->m_CharV0[c], m_currentFont->m_CharU1[c], m_currentFont->m_CharV1[c]);
width += r.w;
r.x = width;
pos++;
}
{
m_primitiveRenderer->drawTexturedRect3D2Text(false);
}
glBindTexture(GL_TEXTURE_2D, 0);
}
}
Gwen::Point MeasureText(Gwen::Font* pFont, const Gwen::UnicodeString& text)
{
// BT_PROFILE("GWEN_MeasureText");
Gwen::String str = Gwen::Utility::UnicodeToString(text);
const char* unicodeText = (const char*)str.c_str();
// printf("str = %s\n",unicodeText);
int xpos = 0;
int ypos = 0;
int measureOnly = 1;
float dx = 0;
if (m_useTrueTypeFont)
{
sth_draw_text(m_font,
1, m_fontScaling,
xpos, ypos,
unicodeText, &dx, m_screenWidth, m_screenHeight, measureOnly);
Gwen::Point pt;
if (m_retinaScale == 2.0f)
{
pt.x = dx * Scale() / 2.f;
pt.y = m_fontScaling / 2 * Scale() + 1;
}
else
{
pt.x = dx * Scale();
pt.y = m_fontScaling * Scale() + 1;
}
return pt;
}
else
{
float width = 0.f;
int pos = 0;
while (unicodeText[pos])
{
width += m_currentFont->m_CharWidth[(int)unicodeText[pos]] + extraSpacing;
pos++;
}
Gwen::Point pt;
int fontHeight = m_currentFont->m_CharHeight;
pt.x = width * Scale();
pt.y = (fontHeight + 2) * Scale();
return pt;
}
return Gwen::Renderer::Base::MeasureText(pFont, text);
}
virtual void LoadTexture(Gwen::Texture* pTexture)
{
if (m_textureLoader)
m_textureLoader->LoadTexture(pTexture);
}
virtual void FreeTexture(Gwen::Texture* pTexture)
{
if (m_textureLoader)
m_textureLoader->FreeTexture(pTexture);
}
virtual void DrawTexturedRect(Gwen::Texture* pTexture, Gwen::Rect rect, float u1 = 0.0f, float v1 = 0.0f, float u2 = 1.0f, float v2 = 1.0f)
{
// BT_PROFILE("DrawTexturedRect");
Translate(rect);
//float eraseColor[4] = {0,0,0,0};
//m_primitiveRenderer->drawRect(rect.x, rect.y+m_yOffset, rect.x+rect.w, rect.y+rect.h+m_yOffset, eraseColor);
GLint texHandle = (GLint)pTexture->m_intData;
//if (!texHandle)
// return;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texHandle);
// glDisable(GL_DEPTH_TEST);
assert(glGetError() == GL_NO_ERROR);
/* bool useFiltering = true;
if (useFiltering)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
} else
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
*/
//glEnable(GL_TEXTURE_2D);
// glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE );
static float add = 0.0;
//add+=1./512.;//0.01;
float color[4] = {1, 1, 1, 1};
m_primitiveRenderer->drawTexturedRect(rect.x, rect.y + m_yOffset, rect.x + rect.w, rect.y + rect.h + m_yOffset, color, 0 + add, 0, 1 + add, 1, true);
assert(glGetError() == GL_NO_ERROR);
}
};
#endif //__GWEN_OPENGL3_CORE_RENDERER_H

View file

@ -0,0 +1,103 @@
#include "LoadShader.h"
#include "OpenGLInclude.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
// Load the shader from the source text
void gltLoadShaderSrc(const char *szShaderSrc, GLuint shader)
{
GLchar *fsStringPtr[1];
fsStringPtr[0] = (GLchar *)szShaderSrc;
glShaderSource(shader, 1, (const GLchar **)fsStringPtr, NULL);
}
GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg)
{
assert(glGetError() == GL_NO_ERROR);
// Temporary Shader objects
GLuint hVertexShader;
GLuint hFragmentShader;
GLuint hReturn = 0;
GLint testVal;
// Create shader objects
hVertexShader = glCreateShader(GL_VERTEX_SHADER);
hFragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
gltLoadShaderSrc(szVertexProg, hVertexShader);
gltLoadShaderSrc(szFragmentProg, hFragmentShader);
// Compile them
glCompileShader(hVertexShader);
assert(glGetError() == GL_NO_ERROR);
glGetShaderiv(hVertexShader, GL_COMPILE_STATUS, &testVal);
if (testVal == GL_FALSE)
{
char temp[256] = "";
glGetShaderInfoLog(hVertexShader, 256, NULL, temp);
fprintf(stderr, "Compile failed:\n%s\n", temp);
assert(0);
return 0;
glDeleteShader(hVertexShader);
glDeleteShader(hFragmentShader);
return (GLuint)0;
}
assert(glGetError() == GL_NO_ERROR);
glCompileShader(hFragmentShader);
assert(glGetError() == GL_NO_ERROR);
glGetShaderiv(hFragmentShader, GL_COMPILE_STATUS, &testVal);
if (testVal == GL_FALSE)
{
char temp[256] = "";
glGetShaderInfoLog(hFragmentShader, 256, NULL, temp);
fprintf(stderr, "Compile failed:\n%s\n", temp);
assert(0);
exit(EXIT_FAILURE);
glDeleteShader(hVertexShader);
glDeleteShader(hFragmentShader);
return (GLuint)0;
}
assert(glGetError() == GL_NO_ERROR);
// Check for errors
// Link them - assuming it works...
hReturn = glCreateProgram();
glAttachShader(hReturn, hVertexShader);
glAttachShader(hReturn, hFragmentShader);
glLinkProgram(hReturn);
// These are no longer needed
glDeleteShader(hVertexShader);
glDeleteShader(hFragmentShader);
// Make sure link worked too
glGetProgramiv(hReturn, GL_LINK_STATUS, &testVal);
if (testVal == GL_FALSE)
{
GLsizei maxLen = 4096;
GLchar infoLog[4096];
GLsizei actualLen;
glGetProgramInfoLog(hReturn,
maxLen,
&actualLen,
infoLog);
printf("Warning/Error in GLSL shader:\n");
printf("%s\n", infoLog);
glDeleteProgram(hReturn);
return (GLuint)0;
}
return hReturn;
}

View file

@ -0,0 +1,17 @@
#ifndef _LOAD_SHADER_H
#define _LOAD_SHADER_H
#include "OpenGLInclude.h"
#ifdef __cplusplus
extern "C"
{
#endif //__cplusplus
GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif //_LOAD_SHADER_H

View file

@ -0,0 +1,173 @@
#ifndef B3_USE_GLFW
#ifdef __APPLE__
#include "MacOpenGLWindow.h"
#include "OpenGLInclude.h"
#include "MacOpenGLWindowObjC.h"
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <string.h>
MacOpenGLWindow::MacOpenGLWindow()
: m_internalData(0)
{
m_internalData = Mac_createData();
}
MacOpenGLWindow::~MacOpenGLWindow()
{
Mac_destroyData(m_internalData);
}
void MacOpenGLWindow::closeWindow()
{
Mac_destroyData(m_internalData);
m_internalData = Mac_createData();
}
bool MacOpenGLWindow::isModifierKeyPressed(int key)
{
return Mac_isModifierKeyPressed(m_internalData, key);
}
float MacOpenGLWindow::getTimeInSeconds()
{
return 0.f;
}
void MacOpenGLWindow::setRenderCallback(b3RenderCallback renderCallback)
{
}
void MacOpenGLWindow::setWindowTitle(const char* windowTitle)
{
Mac_setWindowTitle(m_internalData, windowTitle);
}
void MacOpenGLWindow::createWindow(const b3gWindowConstructionInfo& ci)
{
MacWindowConstructionInfo windowCI;
windowCI.m_width = ci.m_width;
windowCI.m_height = ci.m_height;
windowCI.m_fullscreen = ci.m_fullscreen;
windowCI.m_colorBitsPerPixel = ci.m_colorBitsPerPixel;
windowCI.m_windowHandle = ci.m_windowHandle;
windowCI.m_title = ci.m_title;
windowCI.m_openglVersion = ci.m_openglVersion;
windowCI.m_allowRetina = true;
Mac_createWindow(m_internalData, &windowCI);
}
void MacOpenGLWindow::runMainLoop()
{
}
void MacOpenGLWindow::startRendering()
{
Mac_updateWindow(m_internalData);
}
void MacOpenGLWindow::endRendering()
{
Mac_swapBuffer(m_internalData);
}
bool MacOpenGLWindow::requestedExit() const
{
return Mac_requestedExit(m_internalData);
}
void MacOpenGLWindow::setRequestExit()
{
Mac_setRequestExit(m_internalData);
}
int MacOpenGLWindow::fileOpenDialog(char* filename, int maxNameLength)
{
return Mac_fileOpenDialog(filename, maxNameLength);
}
void MacOpenGLWindow::getMouseCoordinates(int& x, int& y)
{
int* xPtr = &x;
int* yPtr = &y;
Mac_getMouseCoordinates(m_internalData, xPtr, yPtr);
}
int MacOpenGLWindow::getWidth() const
{
return Mac_getWidth(m_internalData);
}
int MacOpenGLWindow::getHeight() const
{
return Mac_getHeight(m_internalData);
}
void MacOpenGLWindow::setResizeCallback(b3ResizeCallback resizeCallback)
{
Mac_setResizeCallback(m_internalData, resizeCallback);
}
b3ResizeCallback MacOpenGLWindow::getResizeCallback()
{
return Mac_getResizeCallback(m_internalData);
}
void MacOpenGLWindow::setMouseButtonCallback(b3MouseButtonCallback mouseCallback)
{
Mac_setMouseButtonCallback(m_internalData, mouseCallback);
}
void MacOpenGLWindow::setMouseMoveCallback(b3MouseMoveCallback mouseCallback)
{
Mac_setMouseMoveCallback(m_internalData, mouseCallback);
}
void MacOpenGLWindow::setKeyboardCallback(b3KeyboardCallback keyboardCallback)
{
Mac_setKeyboardCallback(m_internalData, keyboardCallback);
}
b3MouseMoveCallback MacOpenGLWindow::getMouseMoveCallback()
{
return Mac_getMouseMoveCallback(m_internalData);
}
b3MouseButtonCallback MacOpenGLWindow::getMouseButtonCallback()
{
return Mac_getMouseButtonCallback(m_internalData);
}
void MacOpenGLWindow::setWheelCallback(b3WheelCallback wheelCallback)
{
Mac_setWheelCallback(m_internalData, wheelCallback);
}
b3WheelCallback MacOpenGLWindow::getWheelCallback()
{
return Mac_getWheelCallback(m_internalData);
}
b3KeyboardCallback MacOpenGLWindow::getKeyboardCallback()
{
return Mac_getKeyboardCallback(m_internalData);
}
float MacOpenGLWindow::getRetinaScale() const
{
return Mac_getRetinaScale(m_internalData);
}
void MacOpenGLWindow::setAllowRetina(bool allow)
{
Mac_setAllowRetina(m_internalData, allow);
}
#endif //__APPLE__
#endif //B3_USE_GLFW

View file

@ -0,0 +1,72 @@
#ifndef MAC_OPENGL_WINDOW_H
#define MAC_OPENGL_WINDOW_H
#include "../CommonInterfaces/CommonWindowInterface.h"
#define b3gDefaultOpenGLWindow MacOpenGLWindow
class MacOpenGLWindow : public CommonWindowInterface
{
struct MacOpenGLWindowInternalData* m_internalData;
public:
MacOpenGLWindow();
virtual ~MacOpenGLWindow();
void init(int width, int height, const char* windowTitle);
void closeWindow();
void startRendering();
void endRendering(); //swap buffers
virtual bool requestedExit() const;
virtual void setRequestExit();
void getMouseCoordinates(int& x, int& y);
void runMainLoop();
virtual bool isModifierKeyPressed(int key);
void setMouseButtonCallback(b3MouseButtonCallback mouseCallback);
void setMouseMoveCallback(b3MouseMoveCallback mouseCallback);
void setResizeCallback(b3ResizeCallback resizeCallback);
void setKeyboardCallback(b3KeyboardCallback keyboardCallback);
virtual b3MouseMoveCallback getMouseMoveCallback();
virtual b3MouseButtonCallback getMouseButtonCallback();
virtual b3ResizeCallback getResizeCallback();
virtual b3WheelCallback getWheelCallback();
b3KeyboardCallback getKeyboardCallback();
void setWheelCallback(b3WheelCallback wheelCallback);
float getRetinaScale() const;
virtual void setAllowRetina(bool allow);
virtual void createWindow(const b3gWindowConstructionInfo& ci);
virtual float getTimeInSeconds();
virtual int getWidth() const;
virtual int getHeight() const;
virtual void setRenderCallback(b3RenderCallback renderCallback);
virtual void setWindowTitle(const char* title);
int fileOpenDialog(char* filename, int maxNameLength);
};
#endif

View file

@ -0,0 +1,72 @@
#ifndef MAC_OPENGL_WINDOW_OBJC_H
#define MAC_OPENGL_WINDOW_OBJC_H
struct MacOpenGLWindowInternalData;
#include "../CommonInterfaces/CommonCallbacks.h"
struct MacWindowConstructionInfo
{
int m_width;
int m_height;
int m_fullscreen;
int m_colorBitsPerPixel;
void* m_windowHandle;
const char* m_title;
int m_openglVersion;
int m_allowRetina;
};
enum
{
MY_MAC_ALTKEY = 1,
MY_MAC_SHIFTKEY = 2,
MY_MAC_CONTROL_KEY = 4
};
#ifdef __cplusplus
extern "C"
{
#endif
struct MacOpenGLWindowInternalData* Mac_createData();
void Mac_destroyData(struct MacOpenGLWindowInternalData* data);
int Mac_createWindow(struct MacOpenGLWindowInternalData* m_internalData, struct MacWindowConstructionInfo* ci);
void Mac_setWindowTitle(struct MacOpenGLWindowInternalData* data, const char* windowTitle);
int Mac_updateWindow(struct MacOpenGLWindowInternalData* m_internalData);
void Mac_swapBuffer(struct MacOpenGLWindowInternalData* m_internalData);
int Mac_requestedExit(struct MacOpenGLWindowInternalData* m_internalData);
void Mac_setRequestExit(struct MacOpenGLWindowInternalData* m_internalData);
float Mac_getRetinaScale(struct MacOpenGLWindowInternalData* m_internalData);
void Mac_setAllowRetina(struct MacOpenGLWindowInternalData* m_internalData, int allow);
int Mac_getWidth(struct MacOpenGLWindowInternalData* m_internalData);
int Mac_getHeight(struct MacOpenGLWindowInternalData* m_internalData);
int Mac_fileOpenDialog(char* filename, int maxNameLength);
void Mac_setKeyboardCallback(struct MacOpenGLWindowInternalData* m_internalData, b3KeyboardCallback keyboardCallback);
b3KeyboardCallback Mac_getKeyboardCallback(struct MacOpenGLWindowInternalData* m_internalData);
int Mac_isModifierKeyPressed(struct MacOpenGLWindowInternalData* m_internalData, int key);
void Mac_setMouseButtonCallback(struct MacOpenGLWindowInternalData* m_internalData, b3MouseButtonCallback mouseCallback);
b3MouseButtonCallback Mac_getMouseButtonCallback(struct MacOpenGLWindowInternalData* m_internalData);
void Mac_getMouseCoordinates(struct MacOpenGLWindowInternalData* m_internalData, int* xPtr, int* yPtr);
void Mac_setMouseMoveCallback(struct MacOpenGLWindowInternalData* m_internalData, b3MouseMoveCallback mouseCallback);
b3MouseMoveCallback Mac_getMouseMoveCallback(struct MacOpenGLWindowInternalData* m_internalData);
void Mac_setWheelCallback(struct MacOpenGLWindowInternalData* m_internalData, b3WheelCallback wheelCallback);
b3WheelCallback Mac_getWheelCallback(struct MacOpenGLWindowInternalData* m_internalData);
void Mac_setResizeCallback(struct MacOpenGLWindowInternalData* m_internalData, b3ResizeCallback resizeCallback);
b3ResizeCallback Mac_getResizeCallback(struct MacOpenGLWindowInternalData* m_internalData);
//void Mac_setRenderCallback(struct MacOpenGLWindowInternalData* m_internalData, b3RenderCallback renderCallback);
#ifdef __cplusplus
}
#endif
#endif //MAC_OPENGL_WINDOW_OBJC_H

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,48 @@
/*
Copyright (c) 2012 Advanced Micro Devices, Inc.
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
//Originally written by Erwin Coumans
#ifndef __OPENGL_INCLUDE_H
#define __OPENGL_INCLUDE_H
#ifdef BT_NO_GLAD
#include "third_party/GL/gl/include/EGL/egl.h"
#include "third_party/GL/gl/include/EGL/eglext.h"
#include "third_party/GL/gl/include/GL/gl.h"
#else
#ifdef B3_USE_GLFW
#include "glad/gl.h"
#include <GLFW/glfw3.h>
#else
#include "glad/gl.h"
#endif //B3_USE_GLFW
#endif //BT_NO_GLAD
//disable glGetError
//#undef glGetError
//#define glGetError MyGetError
//
//GLenum inline MyGetError()
//{
// return 0;
//}
///on Linux only glDrawElementsInstancedARB is defined?!?
//#ifdef __linux
//#define glDrawElementsInstanced glDrawElementsInstancedARB
//
//#endif //__linux
#endif //__OPENGL_INCLUDE_H

View file

@ -0,0 +1,31 @@
/*
Copyright (c) 2012 Advanced Micro Devices, Inc.
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
//Originally written by Erwin Coumans
#ifndef __OPENGL_INCLUDE_H
#define __OPENGL_INCLUDE_H
#ifdef BT_NO_GLAD
#include "third_party/GL/gl/include/EGL/egl.h"
#include "third_party/GL/gl/include/EGL/eglext.h"
#include "third_party/GL/gl/include/GL/gl.h"
#else
#ifdef B3_USE_GLFW
#include <glad/gl.h>
#include <GLFW/glfw3.h>
#else
#include "glad/gl.h"
#endif //B3_USE_GLFW
#endif //BT_NO_GLAD
#endif //__OPENGL_INCLUDE_H

File diff suppressed because it is too large Load diff

Binary file not shown.

View file

@ -0,0 +1,10 @@
#version 330
precision highp float;
layout(location = 0) out float fragmentdepth;
void main(void)
{
fragmentdepth = gl_FragCoord.z;
}

View file

@ -0,0 +1,10 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* createShadowMapInstancingFragmentShader= \
"#version 330\n"
"precision highp float;\n"
"layout(location = 0) out float fragmentdepth;\n"
"void main(void)\n"
"{\n"
" fragmentdepth = gl_FragCoord.z;\n"
"}\n"
;

View file

@ -0,0 +1,55 @@
#version 330
precision highp float;
layout (location = 0) in vec4 position;
layout (location = 1) in vec4 instance_position;
layout (location = 2) in vec4 instance_quaternion;
layout (location = 3) in vec2 uvcoords;
layout (location = 4) in vec3 vertexnormal;
layout (location = 5) in vec4 instance_color;
layout (location = 6) in vec4 instance_scale_obUid;
uniform mat4 depthMVP;
vec4 quatMul ( in vec4 q1, in vec4 q2 )
{
vec3 im = q1.w * q2.xyz + q1.xyz * q2.w + cross ( q1.xyz, q2.xyz );
vec4 dt = q1 * q2;
float re = dot ( dt, vec4 ( -1.0, -1.0, -1.0, 1.0 ) );
return vec4 ( im, re );
}
vec4 quatFromAxisAngle(vec4 axis, in float angle)
{
float cah = cos(angle*0.5);
float sah = sin(angle*0.5);
float d = inversesqrt(dot(axis,axis));
vec4 q = vec4(axis.x*sah*d,axis.y*sah*d,axis.z*sah*d,cah);
return q;
}
//
// vector rotation via quaternion
//
vec4 quatRotate3 ( in vec3 p, in vec4 q )
{
vec4 temp = quatMul ( q, vec4 ( p, 0.0 ) );
return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );
}
vec4 quatRotate ( in vec4 p, in vec4 q )
{
vec4 temp = quatMul ( q, p );
return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );
}
void main(void)
{
vec4 q = instance_quaternion;
vec4 localcoord = quatRotate3( position.xyz*instance_scale_obUid.xyz,q);
vec4 vertexPos = depthMVP * vec4( (instance_position+localcoord).xyz,1);
gl_Position = vertexPos;
}

View file

@ -0,0 +1,48 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* createShadowMapInstancingVertexShader= \
"#version 330\n"
"precision highp float;\n"
"layout (location = 0) in vec4 position;\n"
"layout (location = 1) in vec4 instance_position;\n"
"layout (location = 2) in vec4 instance_quaternion;\n"
"layout (location = 3) in vec2 uvcoords;\n"
"layout (location = 4) in vec3 vertexnormal;\n"
"layout (location = 5) in vec4 instance_color;\n"
"layout (location = 6) in vec4 instance_scale_obUid;\n"
"uniform mat4 depthMVP;\n"
"vec4 quatMul ( in vec4 q1, in vec4 q2 )\n"
"{\n"
" vec3 im = q1.w * q2.xyz + q1.xyz * q2.w + cross ( q1.xyz, q2.xyz );\n"
" vec4 dt = q1 * q2;\n"
" float re = dot ( dt, vec4 ( -1.0, -1.0, -1.0, 1.0 ) );\n"
" return vec4 ( im, re );\n"
"}\n"
"vec4 quatFromAxisAngle(vec4 axis, in float angle)\n"
"{\n"
" float cah = cos(angle*0.5);\n"
" float sah = sin(angle*0.5);\n"
" float d = inversesqrt(dot(axis,axis));\n"
" vec4 q = vec4(axis.x*sah*d,axis.y*sah*d,axis.z*sah*d,cah);\n"
" return q;\n"
"}\n"
"//\n"
"// vector rotation via quaternion\n"
"//\n"
"vec4 quatRotate3 ( in vec3 p, in vec4 q )\n"
"{\n"
" vec4 temp = quatMul ( q, vec4 ( p, 0.0 ) );\n"
" return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );\n"
"}\n"
"vec4 quatRotate ( in vec4 p, in vec4 q )\n"
"{\n"
" vec4 temp = quatMul ( q, p );\n"
" return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );\n"
"}\n"
"void main(void)\n"
"{\n"
" vec4 q = instance_quaternion;\n"
" vec4 localcoord = quatRotate3( position.xyz*instance_scale_obUid.xyz,q);\n"
" vec4 vertexPos = depthMVP * vec4( (instance_position+localcoord).xyz,1);\n"
" gl_Position = vertexPos;\n"
"}\n"
;

View file

@ -0,0 +1,37 @@
#version 330
precision highp float;
in Fragment
{
vec4 color;
} fragment;
in Vert
{
vec2 texcoord;
} vert;
uniform sampler2D Diffuse;
in vec3 lightDir,normal,ambient;
out vec4 color;
void main_textured(void)
{
color = vec4(0.1,0.2,0.3,0.3);
}
void main(void)
{
vec4 texel = fragment.color*texture(Diffuse,vert.texcoord);//fragment.color;
vec3 ct,cf;
float intensity,at,af;
intensity = 0.5+0.5*clamp( dot( normalize(normal),lightDir ), -1,1 );
cf = intensity*(vec3(1.0,1.0,1.0)-ambient)+ambient;
af = 1.0;
ct = texel.rgb;
at = texel.a;
color = vec4(ct * cf, at * af);
}

View file

@ -0,0 +1,35 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* instancingFragmentShader= \
"#version 330\n"
"precision highp float;\n"
"in Fragment\n"
"{\n"
" vec4 color;\n"
"} fragment;\n"
"in Vert\n"
"{\n"
" vec2 texcoord;\n"
"} vert;\n"
"uniform sampler2D Diffuse;\n"
"in vec3 lightDir,normal,ambient;\n"
"out vec4 color;\n"
"void main_textured(void)\n"
"{\n"
" color = vec4(0.1,0.2,0.3,0.3);\n"
"}\n"
"void main(void)\n"
"{\n"
" vec4 texel = fragment.color*texture(Diffuse,vert.texcoord);//fragment.color;\n"
" vec3 ct,cf;\n"
" float intensity,at,af;\n"
" \n"
" intensity = 0.5+0.5*clamp( dot( normalize(normal),lightDir ), -1,1 );\n"
" cf = intensity*(vec3(1.0,1.0,1.0)-ambient)+ambient;\n"
" af = 1.0;\n"
" \n"
" ct = texel.rgb;\n"
" at = texel.a;\n"
" \n"
" color = vec4(ct * cf, at * af); \n"
"}\n"
;

View file

@ -0,0 +1,79 @@
#version 330
precision highp float;
layout (location = 0) in vec4 position;
layout (location = 1) in vec4 instance_position;
layout (location = 2) in vec4 instance_quaternion;
layout (location = 3) in vec2 uvcoords;
layout (location = 4) in vec3 vertexnormal;
layout (location = 5) in vec4 instance_color;
layout (location = 6) in vec4 instance_scale_obUid;
uniform mat4 ModelViewMatrix;
uniform mat4 ProjectionMatrix;
uniform vec3 lightDirIn;
out Fragment
{
vec4 color;
} fragment;
out Vert
{
vec2 texcoord;
} vert;
vec4 quatMul ( in vec4 q1, in vec4 q2 )
{
vec3 im = q1.w * q2.xyz + q1.xyz * q2.w + cross ( q1.xyz, q2.xyz );
vec4 dt = q1 * q2;
float re = dot ( dt, vec4 ( -1.0, -1.0, -1.0, 1.0 ) );
return vec4 ( im, re );
}
vec4 quatFromAxisAngle(vec4 axis, in float angle)
{
float cah = cos(angle*0.5);
float sah = sin(angle*0.5);
float d = inversesqrt(dot(axis,axis));
vec4 q = vec4(axis.x*sah*d,axis.y*sah*d,axis.z*sah*d,cah);
return q;
}
//
// vector rotation via quaternion
//
vec4 quatRotate3 ( in vec3 p, in vec4 q )
{
vec4 temp = quatMul ( q, vec4 ( p, 0.0 ) );
return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );
}
vec4 quatRotate ( in vec4 p, in vec4 q )
{
vec4 temp = quatMul ( q, p );
return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );
}
out vec3 lightDir,normal,ambient;
void main(void)
{
vec4 q = instance_quaternion;
ambient = vec3(0.5,.5,0.5);
vec4 worldNormal = (quatRotate3( vertexnormal,q));
normal = normalize(worldNormal).xyz;
lightDir = lightDirIn;
vec4 localcoord = quatRotate3( position.xyz*instance_scale_obUid.xyz,q);
vec4 vertexPos = ProjectionMatrix * ModelViewMatrix *(instance_position+localcoord);
gl_Position = vertexPos;
fragment.color = instance_color;
vert.texcoord = uvcoords;
}

View file

@ -0,0 +1,69 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* instancingVertexShader= \
"#version 330\n"
"precision highp float;\n"
"layout (location = 0) in vec4 position;\n"
"layout (location = 1) in vec4 instance_position;\n"
"layout (location = 2) in vec4 instance_quaternion;\n"
"layout (location = 3) in vec2 uvcoords;\n"
"layout (location = 4) in vec3 vertexnormal;\n"
"layout (location = 5) in vec4 instance_color;\n"
"layout (location = 6) in vec4 instance_scale_obUid;\n"
"uniform mat4 ModelViewMatrix;\n"
"uniform mat4 ProjectionMatrix;\n"
"uniform vec3 lightDirIn;\n"
"out Fragment\n"
"{\n"
" vec4 color;\n"
"} fragment;\n"
"out Vert\n"
"{\n"
" vec2 texcoord;\n"
"} vert;\n"
"vec4 quatMul ( in vec4 q1, in vec4 q2 )\n"
"{\n"
" vec3 im = q1.w * q2.xyz + q1.xyz * q2.w + cross ( q1.xyz, q2.xyz );\n"
" vec4 dt = q1 * q2;\n"
" float re = dot ( dt, vec4 ( -1.0, -1.0, -1.0, 1.0 ) );\n"
" return vec4 ( im, re );\n"
"}\n"
"vec4 quatFromAxisAngle(vec4 axis, in float angle)\n"
"{\n"
" float cah = cos(angle*0.5);\n"
" float sah = sin(angle*0.5);\n"
" float d = inversesqrt(dot(axis,axis));\n"
" vec4 q = vec4(axis.x*sah*d,axis.y*sah*d,axis.z*sah*d,cah);\n"
" return q;\n"
"}\n"
"//\n"
"// vector rotation via quaternion\n"
"//\n"
"vec4 quatRotate3 ( in vec3 p, in vec4 q )\n"
"{\n"
" vec4 temp = quatMul ( q, vec4 ( p, 0.0 ) );\n"
" return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );\n"
"}\n"
"vec4 quatRotate ( in vec4 p, in vec4 q )\n"
"{\n"
" vec4 temp = quatMul ( q, p );\n"
" return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );\n"
"}\n"
"out vec3 lightDir,normal,ambient;\n"
"void main(void)\n"
"{\n"
" vec4 q = instance_quaternion;\n"
" ambient = vec3(0.5,.5,0.5);\n"
" \n"
" vec4 worldNormal = (quatRotate3( vertexnormal,q));\n"
" normal = normalize(worldNormal).xyz;\n"
" \n"
" lightDir = lightDirIn;\n"
" \n"
" vec4 localcoord = quatRotate3( position.xyz*instance_scale_obUid.xyz,q);\n"
" vec4 vertexPos = ProjectionMatrix * ModelViewMatrix *(instance_position+localcoord);\n"
" gl_Position = vertexPos;\n"
" \n"
" fragment.color = instance_color;\n"
" vert.texcoord = uvcoords;\n"
"}\n"
;

View file

@ -0,0 +1,10 @@
#version 150
in vec4 colourV;
out vec4 fragColour;
void main(void)
{
fragColour = colourV;
}

View file

@ -0,0 +1,10 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* linesFragmentShader= \
"#version 150\n"
"in vec4 colourV;\n"
"out vec4 fragColour;\n"
"void main(void)\n"
"{\n"
" fragColour = colourV;\n"
"}\n"
;

View file

@ -0,0 +1,17 @@
#version 150
uniform mat4 ModelViewMatrix;
uniform mat4 ProjectionMatrix;
uniform vec4 colour;
in vec4 position;
out vec4 colourV;
void main (void)
{
colourV = colour;
gl_Position = ProjectionMatrix * ModelViewMatrix * position;
}

View file

@ -0,0 +1,15 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* linesVertexShader= \
"#version 150 \n"
"uniform mat4 ModelViewMatrix;\n"
"uniform mat4 ProjectionMatrix;\n"
"uniform vec4 colour;\n"
"in vec4 position;\n"
"out vec4 colourV;\n"
"void main (void)\n"
"{\n"
" colourV = colour;\n"
" gl_Position = ProjectionMatrix * ModelViewMatrix * position;\n"
" \n"
"}\n"
;

View file

@ -0,0 +1,37 @@
#version 330
precision highp float;
in Fragment
{
vec4 color;
} fragment;
in vec3 ambient;
out vec4 color;
void main_textured(void)
{
color = fragment.color;//texture2D(Diffuse,vert.texcoord);//fragment.color;
}
void main(void)
{
vec3 N;
N.xy = gl_PointCoord.st*vec2(2.0, -2.0) + vec2(-1.0, 1.0);
float mag = dot(N.xy, N.xy);
if (mag > 1.0) discard;
vec4 texel = fragment.color;//vec4(1,0,0,1);//fragment.color*texture(Diffuse,vert.texcoord);//fragment.color;
vec3 ct;
float at,af;
af = 1.0;
ct = texel.rgb;
at = texel.a;
vec3 lightDir= vec3(1,0,0);
float diffuse = max(0.0, dot(lightDir, N));
color = vec4(ct * diffuse, at * af);
}

View file

@ -0,0 +1,33 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* pointSpriteFragmentShader= \
"#version 330\n"
"precision highp float;\n"
"in Fragment\n"
"{\n"
" vec4 color;\n"
"} fragment;\n"
"in vec3 ambient;\n"
"out vec4 color;\n"
"void main_textured(void)\n"
"{\n"
" color = fragment.color;//texture2D(Diffuse,vert.texcoord);//fragment.color;\n"
"}\n"
"void main(void)\n"
"{\n"
" vec3 N;\n"
" N.xy = gl_PointCoord.st*vec2(2.0, -2.0) + vec2(-1.0, 1.0);\n"
" float mag = dot(N.xy, N.xy);\n"
" if (mag > 1.0) discard; \n"
" vec4 texel = fragment.color;//vec4(1,0,0,1);//fragment.color*texture(Diffuse,vert.texcoord);//fragment.color;\n"
" vec3 ct;\n"
" float at,af;\n"
" af = 1.0;\n"
" \n"
" ct = texel.rgb;\n"
" at = texel.a;\n"
" \n"
" vec3 lightDir= vec3(1,0,0);\n"
" float diffuse = max(0.0, dot(lightDir, N));\n"
" color = vec4(ct * diffuse, at * af); \n"
"}\n"
;

View file

@ -0,0 +1,46 @@
#version 330
precision highp float;
layout (location = 0) in vec4 position;
layout (location = 1) in vec4 instance_position;
layout (location = 3) in vec2 uvcoords;
layout (location = 4) in vec3 vertexnormal;
layout (location = 5) in vec4 instance_color;
layout (location = 6) in vec4 instance_scale_obUid;
uniform float screenWidth = 700.f;
uniform mat4 ModelViewMatrix;
uniform mat4 ProjectionMatrix;
out Fragment
{
vec4 color;
} fragment;
//
// vector rotation via quaternion
//
out vec3 ambient;
void main(void)
{
ambient = vec3(0.3,.3,0.3);
vec4 axis = vec4(1,1,1,0);
vec4 vertexPos = ProjectionMatrix * ModelViewMatrix *(instance_position);
vec3 posEye = vec3(ModelViewMatrix * vec4(instance_position.xyz, 1.0));
float dist = length(posEye);
float pointRadius = 1.f;
gl_PointSize = instance_scale_obUid.x * pointRadius * (screenWidth / dist);
gl_Position = vertexPos;
fragment.color = instance_color;
}

View file

@ -0,0 +1,37 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* pointSpriteVertexShader= \
"#version 330\n"
"precision highp float;\n"
"layout (location = 0) in vec4 position;\n"
"layout (location = 1) in vec4 instance_position;\n"
"layout (location = 3) in vec2 uvcoords;\n"
"layout (location = 4) in vec3 vertexnormal;\n"
"layout (location = 5) in vec4 instance_color;\n"
"layout (location = 6) in vec4 instance_scale_obUid;\n"
"uniform float screenWidth = 700.f;\n"
"uniform mat4 ModelViewMatrix;\n"
"uniform mat4 ProjectionMatrix;\n"
"out Fragment\n"
"{\n"
" vec4 color;\n"
"} fragment;\n"
"//\n"
"// vector rotation via quaternion\n"
"//\n"
"out vec3 ambient;\n"
"void main(void)\n"
"{\n"
" ambient = vec3(0.3,.3,0.3);\n"
" \n"
" \n"
" vec4 axis = vec4(1,1,1,0);\n"
" vec4 vertexPos = ProjectionMatrix * ModelViewMatrix *(instance_position);\n"
" vec3 posEye = vec3(ModelViewMatrix * vec4(instance_position.xyz, 1.0));\n"
" float dist = length(posEye);\n"
" float pointRadius = 1.f;\n"
" gl_PointSize = instance_scale_obUid.x * pointRadius * (screenWidth / dist);\n"
" gl_Position = vertexPos;\n"
" \n"
" fragment.color = instance_color;\n"
"}\n"
;

View file

@ -0,0 +1,10 @@
#version 150
in vec4 colourV;
out vec4 fragColour;
void main(void)
{
fragColour = colourV;
}

View file

@ -0,0 +1,10 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* pointsFragmentShader= \
"#version 150\n"
"in vec4 colourV;\n"
"out vec4 fragColour;\n"
"void main(void)\n"
"{\n"
" fragColour = colourV;\n"
"}\n"
;

View file

@ -0,0 +1,15 @@
#version 150
uniform mat4 ModelViewMatrix;
uniform mat4 ProjectionMatrix;
uniform vec4 colour;
in vec4 position;
in vec4 colourIn;
out vec4 colourV;
void main (void)
{
colourV = (colour[3] == -1) ? colourIn : colour;
gl_Position = ProjectionMatrix * ModelViewMatrix * position;
}

View file

@ -0,0 +1,16 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* pointsVertexShader= \
"#version 150 \n"
"uniform mat4 ModelViewMatrix;\n"
"uniform mat4 ProjectionMatrix;\n"
"uniform vec4 colour;\n"
"in vec4 position;\n"
"in vec4 colourIn;\n"
"out vec4 colourV;\n"
"void main (void)\n"
"{\n"
" colourV = (colour[3] == -1) ? colourIn : colour;\n"
" gl_Position = ProjectionMatrix * ModelViewMatrix * position;\n"
" \n"
"}\n"
;

View file

@ -0,0 +1,69 @@
#version 330 core
//precision highp float;
in Fragment
{
vec4 color;
} fragment;
uniform sampler2D Diffuse;
uniform mat4 ViewMatrixInverse;
uniform mat4 TextureMVP;
in vec3 lightPos,cameraPosition, normal,ambient;
in vec4 vertexPos;
in float materialShininess;
in vec3 lightSpecularIntensity;
in vec3 materialSpecularColor;
out vec4 color;
void main(void)
{
vec4 projcoords = TextureMVP * vertexPos;
vec2 texturecoords = projcoords.xy/projcoords.w;
vec4 texel = fragment.color*texture(Diffuse,texturecoords);
vec3 ct,cf;
float intensity,at,af;
if (fragment.color.w==0)
discard;
vec3 lightDir = normalize(lightPos);
vec3 normalDir = normalize(normal);
intensity = 0.5+0.5*clamp( dot( normalDir,lightDir ), -1,1 );
af = 1.0;
ct = texel.rgb;
at = texel.a;
//float bias = 0.005f;
vec3 specularReflection;
if (dot(normalDir, lightDir) < 0.0)
{
specularReflection = vec3(0.0, 0.0, 0.0);
}
else // light source on the right side
{
vec3 surfaceToLight = normalize(lightPos - vertexPos.xyz);
vec3 surfaceToCamera = normalize(cameraPosition - vertexPos.xyz);
float specularCoefficient = 0.0;
specularCoefficient = pow(max(0.0, dot(surfaceToCamera, reflect(-surfaceToLight, normalDir))), materialShininess);
specularReflection = specularCoefficient * materialSpecularColor * lightSpecularIntensity;
}
float visibility = 1.0;
intensity = 0.7*intensity + 0.3*intensity*visibility;
cf = intensity*(vec3(1.0,1.0,1.0)-ambient)+ambient+specularReflection*visibility;
color = vec4(ct * cf, fragment.color.w);
}

View file

@ -0,0 +1,64 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* projectiveTextureInstancingFragmentShader= \
"#version 330 core\n"
"//precision highp float;\n"
"in Fragment\n"
"{\n"
" vec4 color;\n"
"} fragment;\n"
"uniform sampler2D Diffuse;\n"
"uniform mat4 ViewMatrixInverse;\n"
"uniform mat4 TextureMVP;\n"
"in vec3 lightPos,cameraPosition, normal,ambient;\n"
"in vec4 vertexPos;\n"
"in float materialShininess;\n"
"in vec3 lightSpecularIntensity;\n"
"in vec3 materialSpecularColor;\n"
"out vec4 color;\n"
"void main(void)\n"
"{\n"
" vec4 projcoords = TextureMVP * vertexPos;\n"
" vec2 texturecoords = projcoords.xy/projcoords.w;\n"
" vec4 texel = fragment.color*texture(Diffuse,texturecoords);\n"
" vec3 ct,cf;\n"
" float intensity,at,af;\n"
" if (fragment.color.w==0)\n"
" discard;\n"
" vec3 lightDir = normalize(lightPos);\n"
" \n"
" vec3 normalDir = normalize(normal);\n"
" \n"
" intensity = 0.5+0.5*clamp( dot( normalDir,lightDir ), -1,1 );\n"
" \n"
" af = 1.0;\n"
" \n"
" ct = texel.rgb;\n"
" at = texel.a;\n"
" \n"
" //float bias = 0.005f;\n"
" \n"
" vec3 specularReflection;\n"
" \n"
" if (dot(normalDir, lightDir) < 0.0) \n"
" {\n"
" specularReflection = vec3(0.0, 0.0, 0.0);\n"
" }\n"
" else // light source on the right side\n"
" {\n"
" vec3 surfaceToLight = normalize(lightPos - vertexPos.xyz);\n"
" vec3 surfaceToCamera = normalize(cameraPosition - vertexPos.xyz);\n"
" \n"
" \n"
" float specularCoefficient = 0.0;\n"
" specularCoefficient = pow(max(0.0, dot(surfaceToCamera, reflect(-surfaceToLight, normalDir))), materialShininess);\n"
" specularReflection = specularCoefficient * materialSpecularColor * lightSpecularIntensity;\n"
" \n"
" }\n"
" \n"
" float visibility = 1.0;\n"
" intensity = 0.7*intensity + 0.3*intensity*visibility;\n"
" \n"
" cf = intensity*(vec3(1.0,1.0,1.0)-ambient)+ambient+specularReflection*visibility;\n"
" color = vec4(ct * cf, fragment.color.w);\n"
"}\n"
;

View file

@ -0,0 +1,97 @@
#version 330
precision highp float;
layout (location = 0) in vec4 position;
layout (location = 1) in vec4 instance_position;
layout (location = 2) in vec4 instance_quaternion;
layout (location = 3) in vec2 uvcoords;
layout (location = 4) in vec3 vertexnormal;
layout (location = 5) in vec4 instance_color;
layout (location = 6) in vec4 instance_scale_obUid;
uniform mat4 TextureMVP;
uniform mat4 MVP;
uniform vec3 lightPosIn;
uniform vec3 cameraPositionIn;
uniform mat4 ViewMatrixInverse;
uniform float materialShininessIn;
uniform vec3 lightSpecularIntensityIn;
uniform vec3 materialSpecularColorIn;
out vec4 ShadowCoord;
out Fragment
{
vec4 color;
} fragment;
out Vert
{
vec2 texcoord;
} vert;
vec4 quatMul ( in vec4 q1, in vec4 q2 )
{
vec3 im = q1.w * q2.xyz + q1.xyz * q2.w + cross ( q1.xyz, q2.xyz );
vec4 dt = q1 * q2;
float re = dot ( dt, vec4 ( -1.0, -1.0, -1.0, 1.0 ) );
return vec4 ( im, re );
}
vec4 quatFromAxisAngle(vec4 axis, in float angle)
{
float cah = cos(angle*0.5);
float sah = sin(angle*0.5);
float d = inversesqrt(dot(axis,axis));
vec4 q = vec4(axis.x*sah*d,axis.y*sah*d,axis.z*sah*d,cah);
return q;
}
//
// vector rotation via quaternion
//
vec4 quatRotate3 ( in vec3 p, in vec4 q )
{
vec4 temp = quatMul ( q, vec4 ( p, 0.0 ) );
return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );
}
vec4 quatRotate ( in vec4 p, in vec4 q )
{
vec4 temp = quatMul ( q, p );
return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );
}
out vec3 lightPos,normal,ambient;
out vec4 vertexPos;
out vec3 cameraPosition;
out float materialShininess;
out vec3 lightSpecularIntensity;
out vec3 materialSpecularColor;
void main(void)
{
vec4 q = instance_quaternion;
ambient = vec3(0.5,.5,0.5);
vec4 worldNormal = (quatRotate3( vertexnormal,q));
normal = worldNormal.xyz;
lightPos = lightPosIn;
cameraPosition = cameraPositionIn;
materialShininess = materialShininessIn;
lightSpecularIntensity = lightSpecularIntensityIn;
materialSpecularColor = materialSpecularColorIn;
vec4 localcoord = quatRotate3( position.xyz*instance_scale_obUid.xyz,q);
vertexPos = vec4((instance_position+localcoord).xyz,1);
vec4 vertexLoc = MVP* vec4((instance_position+localcoord).xyz,1);
gl_Position = vertexLoc;
fragment.color = instance_color;
}

View file

@ -0,0 +1,84 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* projectiveTextureInstancingVertexShader= \
"#version 330 \n"
"precision highp float;\n"
"layout (location = 0) in vec4 position;\n"
"layout (location = 1) in vec4 instance_position;\n"
"layout (location = 2) in vec4 instance_quaternion;\n"
"layout (location = 3) in vec2 uvcoords;\n"
"layout (location = 4) in vec3 vertexnormal;\n"
"layout (location = 5) in vec4 instance_color;\n"
"layout (location = 6) in vec4 instance_scale_obUid;\n"
"uniform mat4 TextureMVP;\n"
"uniform mat4 MVP;\n"
"uniform vec3 lightPosIn;\n"
"uniform vec3 cameraPositionIn;\n"
"uniform mat4 ViewMatrixInverse;\n"
"uniform float materialShininessIn;\n"
"uniform vec3 lightSpecularIntensityIn;\n"
"uniform vec3 materialSpecularColorIn;\n"
"out vec4 ShadowCoord;\n"
"out Fragment\n"
"{\n"
" vec4 color;\n"
"} fragment;\n"
"out Vert\n"
"{\n"
" vec2 texcoord;\n"
"} vert;\n"
"vec4 quatMul ( in vec4 q1, in vec4 q2 )\n"
"{\n"
" vec3 im = q1.w * q2.xyz + q1.xyz * q2.w + cross ( q1.xyz, q2.xyz );\n"
" vec4 dt = q1 * q2;\n"
" float re = dot ( dt, vec4 ( -1.0, -1.0, -1.0, 1.0 ) );\n"
" return vec4 ( im, re );\n"
"}\n"
"vec4 quatFromAxisAngle(vec4 axis, in float angle)\n"
"{\n"
" float cah = cos(angle*0.5);\n"
" float sah = sin(angle*0.5);\n"
" float d = inversesqrt(dot(axis,axis));\n"
" vec4 q = vec4(axis.x*sah*d,axis.y*sah*d,axis.z*sah*d,cah);\n"
" return q;\n"
"}\n"
"//\n"
"// vector rotation via quaternion\n"
"//\n"
"vec4 quatRotate3 ( in vec3 p, in vec4 q )\n"
"{\n"
" vec4 temp = quatMul ( q, vec4 ( p, 0.0 ) );\n"
" return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );\n"
"}\n"
"vec4 quatRotate ( in vec4 p, in vec4 q )\n"
"{\n"
" vec4 temp = quatMul ( q, p );\n"
" return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );\n"
"}\n"
"out vec3 lightPos,normal,ambient;\n"
"out vec4 vertexPos;\n"
"out vec3 cameraPosition;\n"
"out float materialShininess;\n"
"out vec3 lightSpecularIntensity;\n"
"out vec3 materialSpecularColor;\n"
"void main(void)\n"
"{\n"
" vec4 q = instance_quaternion;\n"
" ambient = vec3(0.5,.5,0.5);\n"
" \n"
" vec4 worldNormal = (quatRotate3( vertexnormal,q));\n"
" \n"
" normal = worldNormal.xyz;\n"
" lightPos = lightPosIn;\n"
" cameraPosition = cameraPositionIn;\n"
" materialShininess = materialShininessIn;\n"
" lightSpecularIntensity = lightSpecularIntensityIn;\n"
" materialSpecularColor = materialSpecularColorIn;\n"
" \n"
" vec4 localcoord = quatRotate3( position.xyz*instance_scale_obUid.xyz,q);\n"
" vertexPos = vec4((instance_position+localcoord).xyz,1);\n"
" \n"
" vec4 vertexLoc = MVP* vec4((instance_position+localcoord).xyz,1);\n"
" gl_Position = vertexLoc;\n"
" fragment.color = instance_color;\n"
"}\n"
;

View file

@ -0,0 +1,16 @@
#version 330
precision highp float;
in vec4 scale_obuid;
out vec4 color;
void main(void)
{
highp int obuid = int(scale_obuid.w);
float r = ((obuid>>0 )&0xff)*(1./255.f);
float g = ((obuid>>8 )&0xff)*(1./255.f);
float b = ((obuid>>16)&0xff)*(1./255.f);
float a = ((obuid>>24)&0xff)*(1./255.f);
color = vec4(r,g,b,a);
}

View file

@ -0,0 +1,16 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* segmentationMaskInstancingFragmentShader= \
"#version 330\n"
"precision highp float;\n"
"in vec4 scale_obuid;\n"
"out vec4 color;\n"
"void main(void)\n"
"{\n"
" highp int obuid = int(scale_obuid.w);\n"
" float r = ((obuid>>0 )&0xff)*(1./255.f);\n"
" float g = ((obuid>>8 )&0xff)*(1./255.f);\n"
" float b = ((obuid>>16)&0xff)*(1./255.f);\n"
" float a = ((obuid>>24)&0xff)*(1./255.f);\n"
" color = vec4(r,g,b,a);\n"
"}\n"
;

View file

@ -0,0 +1,61 @@
#version 330
precision highp float;
layout (location = 0) in vec4 position;
layout (location = 1) in vec4 instance_position;
layout (location = 2) in vec4 instance_quaternion;
layout (location = 5) in vec4 instance_color;
layout (location = 6) in vec4 instance_scale_obUid;
uniform mat4 ModelViewMatrix;
uniform mat4 ProjectionMatrix;
out vec4 scale_obuid;
out Fragment
{
vec4 color;
} fragment;
vec4 quatMul ( in vec4 q1, in vec4 q2 )
{
vec3 im = q1.w * q2.xyz + q1.xyz * q2.w + cross ( q1.xyz, q2.xyz );
vec4 dt = q1 * q2;
float re = dot ( dt, vec4 ( -1.0, -1.0, -1.0, 1.0 ) );
return vec4 ( im, re );
}
vec4 quatFromAxisAngle(vec4 axis, in float angle)
{
float cah = cos(angle*0.5);
float sah = sin(angle*0.5);
float d = inversesqrt(dot(axis,axis));
vec4 q = vec4(axis.x*sah*d,axis.y*sah*d,axis.z*sah*d,cah);
return q;
}
//
// vector rotation via quaternion
//
vec4 quatRotate3 ( in vec3 p, in vec4 q )
{
vec4 temp = quatMul ( q, vec4 ( p, 0.0 ) );
return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );
}
vec4 quatRotate ( in vec4 p, in vec4 q )
{
vec4 temp = quatMul ( q, p );
return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );
}
void main(void)
{
vec4 q = instance_quaternion;
vec4 localcoord = quatRotate3( position.xyz*instance_scale_obUid.xyz,q);
vec4 vertexPos = ProjectionMatrix * ModelViewMatrix *(instance_position+localcoord);
scale_obuid = instance_scale_obUid;
gl_Position = vertexPos;
fragment.color = instance_color;
}

View file

@ -0,0 +1,54 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* segmentationMaskInstancingVertexShader= \
"#version 330\n"
"precision highp float;\n"
"layout (location = 0) in vec4 position;\n"
"layout (location = 1) in vec4 instance_position;\n"
"layout (location = 2) in vec4 instance_quaternion;\n"
"layout (location = 5) in vec4 instance_color;\n"
"layout (location = 6) in vec4 instance_scale_obUid;\n"
"uniform mat4 ModelViewMatrix;\n"
"uniform mat4 ProjectionMatrix;\n"
"out vec4 scale_obuid;\n"
"out Fragment\n"
"{\n"
" vec4 color;\n"
"} fragment;\n"
"vec4 quatMul ( in vec4 q1, in vec4 q2 )\n"
"{\n"
" vec3 im = q1.w * q2.xyz + q1.xyz * q2.w + cross ( q1.xyz, q2.xyz );\n"
" vec4 dt = q1 * q2;\n"
" float re = dot ( dt, vec4 ( -1.0, -1.0, -1.0, 1.0 ) );\n"
" return vec4 ( im, re );\n"
"}\n"
"vec4 quatFromAxisAngle(vec4 axis, in float angle)\n"
"{\n"
" float cah = cos(angle*0.5);\n"
" float sah = sin(angle*0.5);\n"
" float d = inversesqrt(dot(axis,axis));\n"
" vec4 q = vec4(axis.x*sah*d,axis.y*sah*d,axis.z*sah*d,cah);\n"
" return q;\n"
"}\n"
"//\n"
"// vector rotation via quaternion\n"
"//\n"
"vec4 quatRotate3 ( in vec3 p, in vec4 q )\n"
"{\n"
" vec4 temp = quatMul ( q, vec4 ( p, 0.0 ) );\n"
" return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );\n"
"}\n"
"vec4 quatRotate ( in vec4 p, in vec4 q )\n"
"{\n"
" vec4 temp = quatMul ( q, p );\n"
" return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );\n"
"}\n"
"void main(void)\n"
"{\n"
" vec4 q = instance_quaternion;\n"
" vec4 localcoord = quatRotate3( position.xyz*instance_scale_obUid.xyz,q);\n"
" vec4 vertexPos = ProjectionMatrix * ModelViewMatrix *(instance_position+localcoord);\n"
" scale_obuid = instance_scale_obUid;\n"
" gl_Position = vertexPos;\n"
" fragment.color = instance_color;\n"
"}\n"
;

View file

@ -0,0 +1,77 @@
#version 330 core
//precision highp float;
in Fragment
{
vec4 color;
} fragment;
in Vert
{
vec2 texcoord;
} vert;
uniform sampler2D Diffuse;
uniform sampler2DShadow shadowMap;
uniform mat4 ViewMatrixInverse;
in vec3 lightPos,cameraPosition, normal,ambient;
in vec4 ShadowCoord;
in vec4 vertexPos;
in float materialShininess;
in float shadowmapIntensity;
in vec3 lightSpecularIntensity;
in vec3 materialSpecularColor;
out vec4 color;
void main(void)
{
vec4 texel = fragment.color*texture(Diffuse,vert.texcoord);
vec3 ct,cf;
float intensity,at,af;
if (fragment.color.w==0)
discard;
vec3 lightDir = normalize(lightPos);
vec3 normalDir = normalize(normal);
intensity = 0.5+0.5*clamp( dot( normalDir,lightDir ), -1,1 );
af = 1.0;
ct = texel.rgb;
at = texel.a;
//float bias = 0.005f;
vec3 specularReflection;
if (dot(normalDir, lightDir) < 0.0)
{
specularReflection = vec3(0.0, 0.0, 0.0);
}
else // light source on the right side
{
vec3 surfaceToLight = normalize(lightPos - vertexPos.xyz);
vec3 surfaceToCamera = normalize(cameraPosition - vertexPos.xyz);
float specularCoefficient = 0.0;
specularCoefficient = pow(max(0.0, dot(surfaceToCamera, reflect(-surfaceToLight, normalDir))), materialShininess);
specularReflection = specularCoefficient * materialSpecularColor * lightSpecularIntensity;
}
float visibility = texture(shadowMap, vec3(ShadowCoord.xy,(ShadowCoord.z)/ShadowCoord.w));
if (intensity<0.5)
visibility = 0;
intensity = (1.0-shadowmapIntensity)*intensity + shadowmapIntensity*intensity*visibility;
cf = intensity*(vec3(1.0,1.0,1.0)-ambient)+ambient+specularReflection*visibility;
color = vec4(ct * cf, fragment.color.w);
}

View file

@ -0,0 +1,70 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* useShadowMapInstancingFragmentShader= \
"#version 330 core\n"
"//precision highp float;\n"
"in Fragment\n"
"{\n"
" vec4 color;\n"
"} fragment;\n"
"in Vert\n"
"{\n"
" vec2 texcoord;\n"
"} vert;\n"
"uniform sampler2D Diffuse;\n"
"uniform sampler2DShadow shadowMap;\n"
"uniform mat4 ViewMatrixInverse;\n"
"in vec3 lightPos,cameraPosition, normal,ambient;\n"
"in vec4 ShadowCoord;\n"
"in vec4 vertexPos;\n"
"in float materialShininess;\n"
"in float shadowmapIntensity;\n"
"in vec3 lightSpecularIntensity;\n"
"in vec3 materialSpecularColor;\n"
"out vec4 color;\n"
"void main(void)\n"
"{\n"
" vec4 texel = fragment.color*texture(Diffuse,vert.texcoord);\n"
" vec3 ct,cf;\n"
" float intensity,at,af;\n"
" if (fragment.color.w==0)\n"
" discard;\n"
" vec3 lightDir = normalize(lightPos);\n"
" \n"
" vec3 normalDir = normalize(normal);\n"
" \n"
" intensity = 0.5+0.5*clamp( dot( normalDir,lightDir ), -1,1 );\n"
" \n"
" af = 1.0;\n"
" \n"
" ct = texel.rgb;\n"
" at = texel.a;\n"
" \n"
" //float bias = 0.005f;\n"
" \n"
" vec3 specularReflection;\n"
" \n"
" if (dot(normalDir, lightDir) < 0.0) \n"
" {\n"
" specularReflection = vec3(0.0, 0.0, 0.0);\n"
" }\n"
" else // light source on the right side\n"
" {\n"
" vec3 surfaceToLight = normalize(lightPos - vertexPos.xyz);\n"
" vec3 surfaceToCamera = normalize(cameraPosition - vertexPos.xyz);\n"
" \n"
" \n"
" float specularCoefficient = 0.0;\n"
" specularCoefficient = pow(max(0.0, dot(surfaceToCamera, reflect(-surfaceToLight, normalDir))), materialShininess);\n"
" specularReflection = specularCoefficient * materialSpecularColor * lightSpecularIntensity;\n"
" \n"
" }\n"
" \n"
" float visibility = texture(shadowMap, vec3(ShadowCoord.xy,(ShadowCoord.z)/ShadowCoord.w));\n"
" if (intensity<0.5)\n"
" visibility = 0;\n"
" intensity = (1.0-shadowmapIntensity)*intensity + shadowmapIntensity*intensity*visibility;\n"
" \n"
" cf = intensity*(vec3(1.0,1.0,1.0)-ambient)+ambient+specularReflection*visibility;\n"
" color = vec4(ct * cf, fragment.color.w);\n"
"}\n"
;

View file

@ -0,0 +1,105 @@
#version 330
precision highp float;
layout (location = 0) in vec4 position;
layout (location = 1) in vec4 instance_position;
layout (location = 2) in vec4 instance_quaternion;
layout (location = 3) in vec2 uvcoords;
layout (location = 4) in vec3 vertexnormal;
layout (location = 5) in vec4 instance_color;
layout (location = 6) in vec4 instance_scale_obUid;
uniform mat4 ModelViewMatrix;
uniform mat4 ProjectionMatrix;
uniform mat4 DepthBiasModelViewProjectionMatrix;
uniform mat4 MVP;
uniform vec3 lightPosIn;
uniform vec3 cameraPositionIn;
uniform mat4 ViewMatrixInverse;
uniform float materialShininessIn;
uniform float shadowmapIntensityIn;
uniform vec3 lightSpecularIntensityIn;
uniform vec3 materialSpecularColorIn;
out vec4 ShadowCoord;
out Fragment
{
vec4 color;
} fragment;
out Vert
{
vec2 texcoord;
} vert;
vec4 quatMul ( in vec4 q1, in vec4 q2 )
{
vec3 im = q1.w * q2.xyz + q1.xyz * q2.w + cross ( q1.xyz, q2.xyz );
vec4 dt = q1 * q2;
float re = dot ( dt, vec4 ( -1.0, -1.0, -1.0, 1.0 ) );
return vec4 ( im, re );
}
vec4 quatFromAxisAngle(vec4 axis, in float angle)
{
float cah = cos(angle*0.5);
float sah = sin(angle*0.5);
float d = inversesqrt(dot(axis,axis));
vec4 q = vec4(axis.x*sah*d,axis.y*sah*d,axis.z*sah*d,cah);
return q;
}
//
// vector rotation via quaternion
//
vec4 quatRotate3 ( in vec3 p, in vec4 q )
{
vec4 temp = quatMul ( q, vec4 ( p, 0.0 ) );
return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );
}
vec4 quatRotate ( in vec4 p, in vec4 q )
{
vec4 temp = quatMul ( q, p );
return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );
}
out vec3 lightPos,normal,ambient;
out vec4 vertexPos;
out vec3 cameraPosition;
out float materialShininess;
out float shadowmapIntensity;
out vec3 lightSpecularIntensity;
out vec3 materialSpecularColor;
void main(void)
{
vec4 q = instance_quaternion;
ambient = vec3(0.5,.5,0.5);
vec4 worldNormal = (quatRotate3( vertexnormal,q));
normal = worldNormal.xyz;
lightPos = lightPosIn;
cameraPosition = cameraPositionIn;
materialShininess = materialShininessIn;
shadowmapIntensity = shadowmapIntensityIn;
lightSpecularIntensity = lightSpecularIntensityIn;
materialSpecularColor = materialSpecularColorIn;
vec4 localcoord = quatRotate3( position.xyz*instance_scale_obUid.xyz,q);
vertexPos = vec4((instance_position+localcoord).xyz,1);
vec4 vertexLoc = MVP* vec4((instance_position+localcoord).xyz,1);
gl_Position = vertexLoc;
ShadowCoord = DepthBiasModelViewProjectionMatrix * vec4((instance_position+localcoord).xyz,1);
fragment.color = instance_color;
vert.texcoord = uvcoords;
}

View file

@ -0,0 +1,92 @@
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* useShadowMapInstancingVertexShader= \
"#version 330 \n"
"precision highp float;\n"
"layout (location = 0) in vec4 position;\n"
"layout (location = 1) in vec4 instance_position;\n"
"layout (location = 2) in vec4 instance_quaternion;\n"
"layout (location = 3) in vec2 uvcoords;\n"
"layout (location = 4) in vec3 vertexnormal;\n"
"layout (location = 5) in vec4 instance_color;\n"
"layout (location = 6) in vec4 instance_scale_obUid;\n"
"uniform mat4 ModelViewMatrix;\n"
"uniform mat4 ProjectionMatrix;\n"
"uniform mat4 DepthBiasModelViewProjectionMatrix;\n"
"uniform mat4 MVP;\n"
"uniform vec3 lightPosIn;\n"
"uniform vec3 cameraPositionIn;\n"
"uniform mat4 ViewMatrixInverse;\n"
"uniform float materialShininessIn;\n"
"uniform float shadowmapIntensityIn;\n"
"uniform vec3 lightSpecularIntensityIn;\n"
"uniform vec3 materialSpecularColorIn;\n"
"out vec4 ShadowCoord;\n"
"out Fragment\n"
"{\n"
" vec4 color;\n"
"} fragment;\n"
"out Vert\n"
"{\n"
" vec2 texcoord;\n"
"} vert;\n"
"vec4 quatMul ( in vec4 q1, in vec4 q2 )\n"
"{\n"
" vec3 im = q1.w * q2.xyz + q1.xyz * q2.w + cross ( q1.xyz, q2.xyz );\n"
" vec4 dt = q1 * q2;\n"
" float re = dot ( dt, vec4 ( -1.0, -1.0, -1.0, 1.0 ) );\n"
" return vec4 ( im, re );\n"
"}\n"
"vec4 quatFromAxisAngle(vec4 axis, in float angle)\n"
"{\n"
" float cah = cos(angle*0.5);\n"
" float sah = sin(angle*0.5);\n"
" float d = inversesqrt(dot(axis,axis));\n"
" vec4 q = vec4(axis.x*sah*d,axis.y*sah*d,axis.z*sah*d,cah);\n"
" return q;\n"
"}\n"
"//\n"
"// vector rotation via quaternion\n"
"//\n"
"vec4 quatRotate3 ( in vec3 p, in vec4 q )\n"
"{\n"
" vec4 temp = quatMul ( q, vec4 ( p, 0.0 ) );\n"
" return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );\n"
"}\n"
"vec4 quatRotate ( in vec4 p, in vec4 q )\n"
"{\n"
" vec4 temp = quatMul ( q, p );\n"
" return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );\n"
"}\n"
"out vec3 lightPos,normal,ambient;\n"
"out vec4 vertexPos;\n"
"out vec3 cameraPosition;\n"
"out float materialShininess;\n"
"out float shadowmapIntensity;\n"
"out vec3 lightSpecularIntensity;\n"
"out vec3 materialSpecularColor;\n"
"void main(void)\n"
"{\n"
" vec4 q = instance_quaternion;\n"
" ambient = vec3(0.5,.5,0.5);\n"
" \n"
" vec4 worldNormal = (quatRotate3( vertexnormal,q));\n"
" \n"
" normal = worldNormal.xyz;\n"
" lightPos = lightPosIn;\n"
" cameraPosition = cameraPositionIn;\n"
" materialShininess = materialShininessIn;\n"
" \n"
" shadowmapIntensity = shadowmapIntensityIn;\n"
" lightSpecularIntensity = lightSpecularIntensityIn;\n"
" materialSpecularColor = materialSpecularColorIn;\n"
" \n"
" vec4 localcoord = quatRotate3( position.xyz*instance_scale_obUid.xyz,q);\n"
" vertexPos = vec4((instance_position+localcoord).xyz,1);\n"
" \n"
" vec4 vertexLoc = MVP* vec4((instance_position+localcoord).xyz,1);\n"
" gl_Position = vertexLoc;\n"
" ShadowCoord = DepthBiasModelViewProjectionMatrix * vec4((instance_position+localcoord).xyz,1);\n"
" fragment.color = instance_color;\n"
" vert.texcoord = uvcoords;\n"
"}\n"
;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,433 @@
#include "SimpleCamera.h"
#include "Bullet3Common/b3Vector3.h"
#include "Bullet3Common/b3Quaternion.h"
#include "Bullet3Common/b3Matrix3x3.h"
#include "Bullet3Common/b3Transform.h"
B3_ATTRIBUTE_ALIGNED16(struct)
SimpleCameraInternalData
{
SimpleCameraInternalData()
: m_cameraTargetPosition(b3MakeVector3(0, 0, 0)),
m_cameraDistance(20),
m_cameraUp(b3MakeVector3(0, 1, 0)),
m_cameraForward(b3MakeVector3(1, 0, 0)),
m_cameraUpAxis(1),
m_yaw(20),
m_pitch(0),
m_aspect(1),
m_frustumZNear(0.01),
m_frustumZFar(1000),
m_enableVR(false)
{
b3Transform tr;
tr.setIdentity();
tr.getOpenGLMatrix(m_offsetTransformVR);
}
B3_DECLARE_ALIGNED_ALLOCATOR();
B3_ATTRIBUTE_ALIGNED16(float)
m_offsetTransformVR[16];
b3Vector3 m_cameraTargetPosition;
float m_cameraDistance;
b3Vector3 m_cameraUp;
b3Vector3 m_cameraForward;
int m_cameraUpAxis;
//the m_cameraPosition is a cached value, recomputed from other values
b3Vector3 m_cameraPosition;
float m_yaw;
float m_pitch;
float m_aspect;
float m_frustumZNear;
float m_frustumZFar;
bool m_enableVR;
float m_viewMatrixVR[16];
float m_projectionMatrixVR[16];
};
SimpleCamera::SimpleCamera()
{
m_data = new SimpleCameraInternalData;
}
SimpleCamera::~SimpleCamera()
{
delete m_data;
}
void SimpleCamera::setVRCamera(const float viewMat[16], const float projectionMatrix[16])
{
m_data->m_enableVR = true;
b3Matrix3x3 vm;
vm.setValue(viewMat[0], viewMat[4], viewMat[8],
viewMat[1], viewMat[5], viewMat[9],
viewMat[2], viewMat[6], viewMat[10]);
b3Vector3 vp = b3MakeVector3(viewMat[12], viewMat[13], viewMat[14]);
b3Transform tr;
tr.setBasis(vm);
tr.setOrigin(vp);
b3Transform cp = tr.inverse();
m_data->m_cameraPosition = cp.getOrigin();
for (int i = 0; i < 16; i++)
{
m_data->m_viewMatrixVR[i] = viewMat[i];
m_data->m_projectionMatrixVR[i] = projectionMatrix[i];
m_data->m_frustumZNear = m_data->m_projectionMatrixVR[14] / (m_data->m_projectionMatrixVR[10] - 1);
m_data->m_frustumZFar = m_data->m_projectionMatrixVR[14] / (m_data->m_projectionMatrixVR[10] + 1);
}
}
bool SimpleCamera::getVRCamera(float viewMat[16], float projectionMatrix[16])
{
if (m_data->m_enableVR)
{
for (int i = 0; i < 16; i++)
{
viewMat[i] = m_data->m_viewMatrixVR[i];
projectionMatrix[i] = m_data->m_projectionMatrixVR[i];
}
}
return false;
}
void SimpleCamera::disableVRCamera()
{
m_data->m_enableVR = false;
}
bool SimpleCamera::isVRCamera() const
{
return m_data->m_enableVR;
}
static void b3CreateFrustum(
float left,
float right,
float bottom,
float top,
float nearVal,
float farVal,
float frustum[16])
{
frustum[0 * 4 + 0] = (float(2) * nearVal) / (right - left);
frustum[0 * 4 + 1] = float(0);
frustum[0 * 4 + 2] = float(0);
frustum[0 * 4 + 3] = float(0);
frustum[1 * 4 + 0] = float(0);
frustum[1 * 4 + 1] = (float(2) * nearVal) / (top - bottom);
frustum[1 * 4 + 2] = float(0);
frustum[1 * 4 + 3] = float(0);
frustum[2 * 4 + 0] = (right + left) / (right - left);
frustum[2 * 4 + 1] = (top + bottom) / (top - bottom);
frustum[2 * 4 + 2] = -(farVal + nearVal) / (farVal - nearVal);
frustum[2 * 4 + 3] = float(-1);
frustum[3 * 4 + 0] = float(0);
frustum[3 * 4 + 1] = float(0);
frustum[3 * 4 + 2] = -(float(2) * farVal * nearVal) / (farVal - nearVal);
frustum[3 * 4 + 3] = float(0);
}
#if 0
static void b3CreateDiagonalMatrix(float value, float result[4][4])
{
for (int i=0;i<4;i++)
{
for (int j=0;j<4;j++)
{
if (i==j)
{
result[i][j] = value;
} else
{
result[i][j] = 0.f;
}
}
}
}
static void b3CreateOrtho(float left, float right, float bottom, float top, float zNear, float zFar, float result[4][4])
{
b3CreateDiagonalMatrix(1.f,result);
result[0][0] = 2.f / (right - left);
result[1][1] = 2.f / (top - bottom);
result[2][2] = - 2.f / (zFar - zNear);
result[3][0] = - (right + left) / (right - left);
result[3][1] = - (top + bottom) / (top - bottom);
result[3][2] = - (zFar + zNear) / (zFar - zNear);
}
#endif
static void b3CreateLookAt(const b3Vector3& eye, const b3Vector3& center, const b3Vector3& up, float result[16])
{
b3Vector3 f = (center - eye).normalized();
b3Vector3 u = up.normalized();
b3Vector3 s = (f.cross(u)).normalized();
u = s.cross(f);
result[0 * 4 + 0] = s.x;
result[1 * 4 + 0] = s.y;
result[2 * 4 + 0] = s.z;
result[0 * 4 + 1] = u.x;
result[1 * 4 + 1] = u.y;
result[2 * 4 + 1] = u.z;
result[0 * 4 + 2] = -f.x;
result[1 * 4 + 2] = -f.y;
result[2 * 4 + 2] = -f.z;
result[0 * 4 + 3] = 0.f;
result[1 * 4 + 3] = 0.f;
result[2 * 4 + 3] = 0.f;
result[3 * 4 + 0] = -s.dot(eye);
result[3 * 4 + 1] = -u.dot(eye);
result[3 * 4 + 2] = f.dot(eye);
result[3 * 4 + 3] = 1.f;
}
void SimpleCamera::setCameraUpAxis(int upAxis)
{
m_data->m_cameraUpAxis = upAxis;
update();
}
int SimpleCamera::getCameraUpAxis() const
{
return m_data->m_cameraUpAxis;
}
void SimpleCamera::update()
{
b3Scalar yawRad = m_data->m_yaw * b3Scalar(0.01745329251994329547); // rads per deg
b3Scalar pitchRad = m_data->m_pitch * b3Scalar(0.01745329251994329547); // rads per deg
b3Scalar rollRad = 0.0;
b3Quaternion eyeRot;
int forwardAxis(-1);
switch (m_data->m_cameraUpAxis)
{
case 1:
forwardAxis = 2;
m_data->m_cameraUp = b3MakeVector3(0, 1, 0);
//gLightPos = b3MakeVector3(-50.f,100,30);
eyeRot.setEulerZYX(rollRad, yawRad, -pitchRad);
break;
case 2:
forwardAxis = 1;
m_data->m_cameraUp = b3MakeVector3(0, 0, 1);
//gLightPos = b3MakeVector3(-50.f,30,100);
eyeRot.setEulerZYX(yawRad, rollRad, pitchRad);
break;
default:
{
//b3Assert(0);
return;
}
};
b3Vector3 eyePos = b3MakeVector3(0, 0, 0);
eyePos[forwardAxis] = -m_data->m_cameraDistance;
eyePos = b3Matrix3x3(eyeRot) * eyePos;
m_data->m_cameraPosition = eyePos;
m_data->m_cameraPosition += m_data->m_cameraTargetPosition;
m_data->m_cameraForward = m_data->m_cameraTargetPosition - m_data->m_cameraPosition;
if (m_data->m_cameraForward.length2() < B3_EPSILON)
{
m_data->m_cameraForward.setValue(1.f, 0.f, 0.f);
}
else
{
m_data->m_cameraForward.normalize();
}
}
void SimpleCamera::getCameraProjectionMatrix(float projectionMatrix[16]) const
{
if (m_data->m_enableVR)
{
for (int i = 0; i < 16; i++)
{
projectionMatrix[i] = m_data->m_projectionMatrixVR[i];
}
}
else
{
b3CreateFrustum(-m_data->m_aspect * m_data->m_frustumZNear, m_data->m_aspect * m_data->m_frustumZNear, -m_data->m_frustumZNear, m_data->m_frustumZNear, m_data->m_frustumZNear, m_data->m_frustumZFar, projectionMatrix);
}
}
void SimpleCamera::setVRCameraOffsetTransform(const float offset[16])
{
for (int i = 0; i < 16; i++)
{
m_data->m_offsetTransformVR[i] = offset[i];
}
}
void SimpleCamera::getCameraViewMatrix(float viewMatrix[16]) const
{
if (m_data->m_enableVR)
{
for (int i = 0; i < 16; i++)
{
b3Transform tr;
tr.setFromOpenGLMatrix(m_data->m_viewMatrixVR);
b3Transform shift = b3Transform::getIdentity();
shift.setFromOpenGLMatrix(m_data->m_offsetTransformVR);
tr = tr * shift;
tr.getOpenGLMatrix(viewMatrix);
//viewMatrix[i] = m_data->m_viewMatrixVR[i];
}
}
else
{
b3CreateLookAt(m_data->m_cameraPosition, m_data->m_cameraTargetPosition, m_data->m_cameraUp, viewMatrix);
}
}
void SimpleCamera::getCameraTargetPosition(double pos[3]) const
{
pos[0] = m_data->m_cameraTargetPosition[0];
pos[1] = m_data->m_cameraTargetPosition[1];
pos[2] = m_data->m_cameraTargetPosition[2];
}
void SimpleCamera::getCameraPosition(double pos[3]) const
{
pos[0] = m_data->m_cameraPosition[0];
pos[1] = m_data->m_cameraPosition[1];
pos[2] = m_data->m_cameraPosition[2];
}
void SimpleCamera::getCameraTargetPosition(float pos[3]) const
{
pos[0] = m_data->m_cameraTargetPosition[0];
pos[1] = m_data->m_cameraTargetPosition[1];
pos[2] = m_data->m_cameraTargetPosition[2];
}
void SimpleCamera::getCameraPosition(float pos[3]) const
{
pos[0] = m_data->m_cameraPosition[0];
pos[1] = m_data->m_cameraPosition[1];
pos[2] = m_data->m_cameraPosition[2];
}
void SimpleCamera::setCameraTargetPosition(float x, float y, float z)
{
m_data->m_cameraTargetPosition.setValue(x, y, z);
update();
}
float SimpleCamera::getCameraDistance() const
{
return m_data->m_cameraDistance;
}
void SimpleCamera::setCameraDistance(float dist)
{
m_data->m_cameraDistance = dist;
update();
}
void SimpleCamera::setCameraUpVector(float x, float y, float z)
{
m_data->m_cameraUp.setValue(x, y, z);
update();
}
void SimpleCamera::getCameraUpVector(float up[3]) const
{
if (m_data->m_enableVR)
{
float viewMatTotal[16];
getCameraViewMatrix(viewMatTotal);
up[0] = viewMatTotal[0];
up[1] = viewMatTotal[4];
up[2] = viewMatTotal[8];
}
else
{
up[0] = float(m_data->m_cameraUp[0]);
up[1] = float(m_data->m_cameraUp[1]);
up[2] = float(m_data->m_cameraUp[2]);
}
}
void SimpleCamera::getCameraForwardVector(float fwd[3]) const
{
if (m_data->m_enableVR)
{
float viewMatTotal[16];
getCameraViewMatrix(viewMatTotal);
fwd[0] = viewMatTotal[2];
fwd[1] = viewMatTotal[6];
fwd[2] = viewMatTotal[10];
}
else
{
fwd[0] = float(m_data->m_cameraForward[0]);
fwd[1] = float(m_data->m_cameraForward[1]);
fwd[2] = float(m_data->m_cameraForward[2]);
}
}
void SimpleCamera::setCameraYaw(float yaw)
{
m_data->m_yaw = yaw;
update();
}
float SimpleCamera::getCameraYaw() const
{
return m_data->m_yaw;
}
void SimpleCamera::setCameraPitch(float pitch)
{
m_data->m_pitch = pitch;
update();
}
void SimpleCamera::setAspectRatio(float ratio)
{
m_data->m_aspect = ratio;
update();
}
float SimpleCamera::getCameraPitch() const
{
return m_data->m_pitch;
}
float SimpleCamera::getAspectRatio() const
{
return m_data->m_aspect;
}
float SimpleCamera::getCameraFrustumFar() const
{
return m_data->m_frustumZFar;
}
float SimpleCamera::getCameraFrustumNear() const
{
return m_data->m_frustumZNear;
}
void SimpleCamera::setCameraFrustumFar(float far)
{
m_data->m_frustumZFar = far;
}
void SimpleCamera::setCameraFrustumNear(float near)
{
m_data->m_frustumZNear = near;
}

View file

@ -0,0 +1,60 @@
#ifndef SIMPLE_CAMERA_H
#define SIMPLE_CAMERA_H
#include "../CommonInterfaces/CommonCameraInterface.h"
struct SimpleCamera : public CommonCameraInterface
{
struct SimpleCameraInternalData* m_data;
SimpleCamera();
virtual ~SimpleCamera();
void update();
virtual void getCameraProjectionMatrix(float m[16]) const;
virtual void getCameraViewMatrix(float m[16]) const;
virtual void setVRCamera(const float viewMat[16], const float projectionMatrix[16]);
virtual bool getVRCamera(float viewMat[16], float projectionMatrix[16]);
virtual void setVRCameraOffsetTransform(const float offset[16]);
virtual void disableVRCamera();
virtual bool isVRCamera() const;
virtual void getCameraTargetPosition(float pos[3]) const;
virtual void getCameraPosition(float pos[3]) const;
virtual void getCameraTargetPosition(double pos[3]) const;
virtual void getCameraPosition(double pos[3]) const;
virtual void setCameraTargetPosition(float x, float y, float z);
virtual void setCameraDistance(float dist);
virtual float getCameraDistance() const;
virtual void setCameraUpVector(float x, float y, float z);
void getCameraUpVector(float up[3]) const;
void getCameraForwardVector(float fwd[3]) const;
///the setCameraUpAxis will call the 'setCameraUpVector' and 'setCameraForwardVector'
virtual void setCameraUpAxis(int axis);
virtual int getCameraUpAxis() const;
virtual void setCameraYaw(float yaw);
virtual float getCameraYaw() const;
virtual void setCameraPitch(float pitch);
virtual float getCameraPitch() const;
virtual void setAspectRatio(float ratio);
virtual float getAspectRatio() const;
virtual float getCameraFrustumFar() const;
virtual float getCameraFrustumNear() const;
virtual void setCameraFrustumFar(float far);
virtual void setCameraFrustumNear(float near);
};
#endif //SIMPLE_CAMERA_H

View file

@ -0,0 +1,564 @@
#include "SimpleOpenGL2App.h"
#define USE_OPENGL2
#include "OpenGLInclude.h"
#include "ShapeData.h"
#include "Bullet3Common/b3Logging.h" //b3Assert?
#include "Bullet3Common/b3Scalar.h"
#include "Bullet3Common/b3AlignedObjectArray.h"
#include "Bullet3Common/b3Vector3.h"
#include "Bullet3Common/b3Quaternion.h"
#include "../CommonInterfaces/CommonRenderInterface.h"
#include "../OpenGLWindow/GLPrimitiveRenderer.h"
#include "GLInstanceGraphicsShape.h"
#include "stdlib.h"
#include "TwFonts.h"
#include "SimpleOpenGL2Renderer.h"
#ifdef B3_USE_GLFW
#include "GLFWOpenGLWindow.h"
#else
#ifdef __APPLE__
#include "MacOpenGLWindow.h"
#else
//#include "GL/glew.h"
#ifdef _WIN32
#include "Win32OpenGLWindow.h"
#else
//let's cross the fingers it is Linux/X11
#include "X11OpenGLWindow.h"
#ifdef BT_USE_EGL
#include "EGLOpenGLWindow.h"
#else
#endif //BT_USE_EGL
#endif //_WIN32
#endif //__APPLE__
#endif //#ifdef B3_USE_GLFW
#include <stdio.h>
#include "../CommonInterfaces/CommonRenderInterface.h"
static SimpleOpenGL2App* gApp2 = 0;
static void Simple2ResizeCallback(float widthf, float heightf)
{
int width = (int)widthf;
int height = (int)heightf;
if (gApp2->m_renderer && gApp2->m_window)
gApp2->m_renderer->resize(width, height); //*gApp2->m_window->getRetinaScale(),height*gApp2->m_window->getRetinaScale());
}
static void Simple2KeyboardCallback(int key, int state)
{
if (key == B3G_ESCAPE && gApp2 && gApp2->m_window)
{
gApp2->m_window->setRequestExit();
}
else
{
//gApp2->defaultKeyboardCallback(key,state);
}
}
void Simple2MouseButtonCallback(int button, int state, float x, float y)
{
if (gApp2 && gApp2->m_window)
{
gApp2->defaultMouseButtonCallback(button, state, x, y);
}
}
void Simple2MouseMoveCallback(float x, float y)
{
if (gApp2 && gApp2->m_window)
{
gApp2->defaultMouseMoveCallback(x, y);
}
}
void Simple2WheelCallback(float deltax, float deltay)
{
gApp2->defaultWheelCallback(deltax, deltay);
}
struct SimpleOpenGL2AppInternalData
{
GLuint m_fontTextureId;
GLuint m_largeFontTextureId;
int m_upAxis;
SimpleOpenGL2AppInternalData()
: m_upAxis(1)
{
}
};
static GLuint BindFont2(const CTexFont* _Font)
{
GLuint TexID = 0;
glGenTextures(1, &TexID);
glBindTexture(GL_TEXTURE_2D, TexID);
glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, _Font->m_TexWidth, _Font->m_TexHeight, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, _Font->m_TexBytes);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
return TexID;
}
SimpleOpenGL2App::SimpleOpenGL2App(const char* title, int width, int height)
{
gApp2 = this;
m_data = new SimpleOpenGL2AppInternalData;
m_window = new b3gDefaultOpenGLWindow();
b3gWindowConstructionInfo ci;
ci.m_title = title;
ci.m_openglVersion = 2;
ci.m_width = width;
ci.m_height = height;
m_window->createWindow(ci);
m_window->setWindowTitle(title);
#ifndef NO_GLEW
#ifndef __APPLE__
#ifndef _WIN32
#ifndef B3_USE_GLFW
//some Linux implementations need the 'glewExperimental' to be true
#endif //B3_USE_GLFW
#endif //_WIN32
#ifndef B3_USE_GLFW
//gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
#if 0
if (glewInit() != GLEW_OK)
{
b3Error("glewInit failed");
exit(1);
}
if (!GLEW_VERSION_2_1) // check that the machine supports the 2.1 API.
{
b3Error("GLEW_VERSION_2_1 needs to support 2_1");
exit(1); // or handle the error in a nicer way
}
#endif
#endif //B3_USE_GLFW
#endif //__APPLE__
#endif //NO_GLEW
TwGenerateDefaultFonts();
m_data->m_fontTextureId = BindFont2(g_DefaultNormalFont);
m_data->m_largeFontTextureId = BindFont2(g_DefaultLargeFont);
glGetError(); //don't remove this call, it is needed for Ubuntu
glClearColor(m_backgroundColorRGB[0],
m_backgroundColorRGB[1],
m_backgroundColorRGB[2],
1.f);
b3Assert(glGetError() == GL_NO_ERROR);
//m_primRenderer = new GLPrimitiveRenderer(width,height);
m_parameterInterface = 0;
b3Assert(glGetError() == GL_NO_ERROR);
//m_renderer = new GLInstancingRenderer(128*1024,32*1024*1024);
//m_renderer->init();
//m_renderer->resize(width,height);
b3Assert(glGetError() == GL_NO_ERROR);
//m_renderer->InitShaders();
m_window->setMouseMoveCallback(Simple2MouseMoveCallback);
m_window->setMouseButtonCallback(Simple2MouseButtonCallback);
m_window->setKeyboardCallback(Simple2KeyboardCallback);
m_window->setWheelCallback(Simple2WheelCallback);
m_window->setResizeCallback(Simple2ResizeCallback);
m_renderer = new SimpleOpenGL2Renderer(width, height);
}
SimpleOpenGL2App::~SimpleOpenGL2App()
{
gApp2 = 0;
delete m_data;
}
void SimpleOpenGL2App::setBackgroundColor(float red, float green, float blue)
{
CommonGraphicsApp::setBackgroundColor(red, green, blue);
glClearColor(m_backgroundColorRGB[0], m_backgroundColorRGB[1], m_backgroundColorRGB[2], 1.f);
}
void SimpleOpenGL2App::drawGrid(DrawGridData data)
{
glEnable(GL_COLOR_MATERIAL);
int gridSize = data.gridSize;
float upOffset = data.upOffset;
int upAxis = data.upAxis;
float gridColor[4];
gridColor[0] = data.gridColor[0];
gridColor[1] = data.gridColor[1];
gridColor[2] = data.gridColor[2];
gridColor[3] = data.gridColor[3];
int sideAxis = -1;
int forwardAxis = -1;
switch (upAxis)
{
case 1:
forwardAxis = 2;
sideAxis = 0;
break;
case 2:
forwardAxis = 1;
sideAxis = 0;
break;
default:
b3Assert(0);
};
//b3Vector3 gridColor = b3MakeVector3(0.5,0.5,0.5);
b3AlignedObjectArray<unsigned int> indices;
b3AlignedObjectArray<b3Vector3> vertices;
int lineIndex = 0;
for (int i = -gridSize; i <= gridSize; i++)
{
{
b3Assert(glGetError() == GL_NO_ERROR);
b3Vector3 from = b3MakeVector3(0, 0, 0);
from[sideAxis] = float(i);
from[upAxis] = upOffset;
from[forwardAxis] = float(-gridSize);
b3Vector3 to = b3MakeVector3(0, 0, 0);
to[sideAxis] = float(i);
to[upAxis] = upOffset;
to[forwardAxis] = float(gridSize);
vertices.push_back(from);
indices.push_back(lineIndex++);
vertices.push_back(to);
indices.push_back(lineIndex++);
// m_renderer->drawLine(from,to,gridColor);
}
b3Assert(glGetError() == GL_NO_ERROR);
{
b3Assert(glGetError() == GL_NO_ERROR);
b3Vector3 from = b3MakeVector3(0, 0, 0);
from[sideAxis] = float(-gridSize);
from[upAxis] = upOffset;
from[forwardAxis] = float(i);
b3Vector3 to = b3MakeVector3(0, 0, 0);
to[sideAxis] = float(gridSize);
to[upAxis] = upOffset;
to[forwardAxis] = float(i);
vertices.push_back(from);
indices.push_back(lineIndex++);
vertices.push_back(to);
indices.push_back(lineIndex++);
// m_renderer->drawLine(from,to,gridColor);
}
}
m_renderer->drawLines(&vertices[0].x,
gridColor,
vertices.size(), sizeof(b3Vector3), &indices[0], indices.size(), 1);
m_renderer->drawLine(b3MakeVector3(0, 0, 0), b3MakeVector3(1, 0, 0), b3MakeVector3(1, 0, 0), 3);
m_renderer->drawLine(b3MakeVector3(0, 0, 0), b3MakeVector3(0, 1, 0), b3MakeVector3(0, 1, 0), 3);
m_renderer->drawLine(b3MakeVector3(0, 0, 0), b3MakeVector3(0, 0, 1), b3MakeVector3(0, 0, 1), 3);
// void GLInstancingRenderer::drawPoints(const float* positions, const float color[4], int numPoints, int pointStrideInBytes, float pointDrawSize)
//we don't use drawPoints because all points would have the same color
// b3Vector3 points[3] = { b3MakeVector3(1, 0, 0), b3MakeVector3(0, 1, 0), b3MakeVector3(0, 0, 1) };
// m_renderer->drawPoints(&points[0].x, b3MakeVector3(1, 0, 0), 3, sizeof(b3Vector3), 6);
}
void SimpleOpenGL2App::setUpAxis(int axis)
{
this->m_data->m_upAxis = axis;
}
int SimpleOpenGL2App::getUpAxis() const
{
return this->m_data->m_upAxis;
}
void SimpleOpenGL2App::swapBuffer()
{
m_window->endRendering();
m_window->startRendering();
}
void SimpleOpenGL2App::drawText(const char* txt, int posXi, int posYi, float size, float colorRGBA[4])
{
}
static void restoreOpenGLState()
{
glPopClientAttrib();
glPopAttrib();
}
static void saveOpenGLState(int screenWidth, int screenHeight)
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
glDisable(GL_TEXTURE_GEN_R);
glDisable(GL_LINE_SMOOTH);
// glDisable(GL_LINE_STIPPLE);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glDisable(GL_TEXTURE_2D);
}
void SimpleOpenGL2App::drawText3D(const char* txt, float position[3], float orientation[4], float color[4], float size, int optionFlag)
{
}
void SimpleOpenGL2App::drawText3D(const char* txt, float worldPosX, float worldPosY, float worldPosZ, float size1)
{
saveOpenGLState(gApp2->m_renderer->getScreenWidth(), gApp2->m_renderer->getScreenHeight());
float viewMat[16];
float projMat[16];
CommonCameraInterface* cam = gApp2->m_renderer->getActiveCamera();
cam->getCameraViewMatrix(viewMat);
cam->getCameraProjectionMatrix(projMat);
float camPos[4];
cam->getCameraPosition(camPos);
//b3Vector3 cp= b3MakeVector3(camPos[0],camPos[2],camPos[1]);
// b3Vector3 p = b3MakeVector3(worldPosX,worldPosY,worldPosZ);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glAlphaFunc(GL_GREATER, 1.0f);
int viewport[4] = {0, 0, gApp2->m_renderer->getScreenWidth(), gApp2->m_renderer->getScreenHeight()};
float posX = 450.f;
float posY = 100.f;
float winx, winy, winz;
if (!projectWorldCoordToScreen(worldPosX, worldPosY, worldPosZ, viewMat, projMat, viewport, &winx, &winy, &winz))
{
return;
}
posX = winx;
posY = gApp2->m_renderer->getScreenHeight() / 2 + (gApp2->m_renderer->getScreenHeight() / 2) - winy;
{
//float width = 0.f;
int pos = 0;
//float color[]={0.2f,0.2,0.2f,1.f};
glActiveTexture(GL_TEXTURE0);
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glBindTexture(GL_TEXTURE_2D, m_data->m_largeFontTextureId);
glEnable(GL_TEXTURE_2D); //BindTexture
//float width = r.x;
//float extraSpacing = 0.;
float startX = posX;
float startY = posY - g_DefaultLargeFont->m_CharHeight * size1;
glEnable(GL_COLOR_MATERIAL);
while (txt[pos])
{
int c = txt[pos];
//r.h = g_DefaultNormalFont->m_CharHeight;
//r.w = g_DefaultNormalFont->m_CharWidth[c]+extraSpacing;
float endX = startX + g_DefaultLargeFont->m_CharWidth[c] * size1;
float endY = posY;
float currentColor[] = {1.f, 0.2, 0.2f, 1.f};
float u0 = g_DefaultLargeFont->m_CharU0[c];
float u1 = g_DefaultLargeFont->m_CharU1[c];
float v0 = g_DefaultLargeFont->m_CharV0[c];
float v1 = g_DefaultLargeFont->m_CharV1[c];
float color[4] = {currentColor[0], currentColor[1], currentColor[2], currentColor[3]};
float x0 = startX;
float x1 = endX;
float y0 = startY;
float y1 = endY;
int screenWidth = gApp2->m_renderer->getScreenWidth();
int screenHeight = gApp2->m_renderer->getScreenHeight();
float z = 2.f * winz - 1.f; //*(far
/*float identity[16]={1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1};
*/
PrimVertex vertexData[4] = {
PrimVertex(PrimVec4(-1.f + 2.f * x0 / float(screenWidth), 1.f - 2.f * y0 / float(screenHeight), z, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u0, v0)),
PrimVertex(PrimVec4(-1.f + 2.f * x0 / float(screenWidth), 1.f - 2.f * y1 / float(screenHeight), z, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u0, v1)),
PrimVertex(PrimVec4(-1.f + 2.f * x1 / float(screenWidth), 1.f - 2.f * y1 / float(screenHeight), z, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u1, v1)),
PrimVertex(PrimVec4(-1.f + 2.f * x1 / float(screenWidth), 1.f - 2.f * y0 / float(screenHeight), z, 1.f), PrimVec4(color[0], color[1], color[2], color[3]), PrimVec2(u1, v0))};
glBegin(GL_TRIANGLES);
//use red colored text for now
glColor4f(1, 0, 0, 1);
float scaling = 1;
glTexCoord2f(vertexData[0].uv.p[0], vertexData[0].uv.p[1]);
glVertex3d(vertexData[0].position.p[0] * scaling, vertexData[0].position.p[1] * scaling, vertexData[0].position.p[2] * scaling);
glTexCoord2f(vertexData[1].uv.p[0], vertexData[1].uv.p[1]);
glVertex3d(vertexData[1].position.p[0] * scaling, vertexData[1].position.p[1] * scaling, vertexData[1].position.p[2] * scaling);
glTexCoord2f(vertexData[2].uv.p[0], vertexData[2].uv.p[1]);
glVertex3d(vertexData[2].position.p[0] * scaling, vertexData[2].position.p[1] * scaling, vertexData[2].position.p[2] * scaling);
glTexCoord2f(vertexData[0].uv.p[0], vertexData[0].uv.p[1]);
glVertex3d(vertexData[0].position.p[0] * scaling, vertexData[0].position.p[1] * scaling, vertexData[0].position.p[2] * scaling);
glTexCoord2f(vertexData[2].uv.p[0], vertexData[2].uv.p[1]);
glVertex3d(vertexData[2].position.p[0] * scaling, vertexData[2].position.p[1] * scaling, vertexData[2].position.p[2] * scaling);
glTexCoord2f(vertexData[3].uv.p[0], vertexData[3].uv.p[1]);
glVertex3d(vertexData[3].position.p[0] * scaling, vertexData[3].position.p[1] * scaling, vertexData[3].position.p[2] * scaling);
glEnd();
startX = endX;
pos++;
}
}
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
restoreOpenGLState();
}
void SimpleOpenGL2App::registerGrid(int cells_x, int cells_z, float color0[4], float color1[4])
{
b3Vector3 cubeExtents = b3MakeVector3(0.5, 0.5, 0.5);
double halfHeight = 0.1;
cubeExtents[m_data->m_upAxis] = halfHeight;
int cubeId = registerCubeShape(cubeExtents[0], cubeExtents[1], cubeExtents[2]);
b3Quaternion orn(0, 0, 0, 1);
b3Vector3 center = b3MakeVector3(0, 0, 0, 1);
b3Vector3 scaling = b3MakeVector3(1, 1, 1, 1);
for (int i = 0; i < cells_x; i++)
{
for (int j = 0; j < cells_z; j++)
{
float* color = 0;
if ((i + j) % 2 == 0)
{
color = (float*)color0;
}
else
{
color = (float*)color1;
}
if (this->m_data->m_upAxis == 1)
{
center = b3MakeVector3((i + 0.5f) - cells_x * 0.5f, -halfHeight, (j + 0.5f) - cells_z * 0.5f);
}
else
{
center = b3MakeVector3((i + 0.5f) - cells_x * 0.5f, (j + 0.5f) - cells_z * 0.5f, -halfHeight);
}
m_renderer->registerGraphicsInstance(cubeId, center, orn, color, scaling);
}
}
}
int SimpleOpenGL2App::registerGraphicsUnitSphereShape(EnumSphereLevelOfDetail lod, int textureId)
{
int strideInBytes = 9 * sizeof(float);
int graphicsShapeIndex = -1;
switch (lod)
{
case SPHERE_LOD_POINT_SPRITE:
{
int numVertices = sizeof(point_sphere_vertices) / strideInBytes;
int numIndices = sizeof(point_sphere_indices) / sizeof(int);
graphicsShapeIndex = m_renderer->registerShape(&point_sphere_vertices[0], numVertices, point_sphere_indices, numIndices, B3_GL_POINTS, textureId);
break;
}
case SPHERE_LOD_LOW:
{
int numVertices = sizeof(low_sphere_vertices) / strideInBytes;
int numIndices = sizeof(low_sphere_indices) / sizeof(int);
graphicsShapeIndex = m_renderer->registerShape(&low_sphere_vertices[0], numVertices, low_sphere_indices, numIndices, B3_GL_TRIANGLES, textureId);
break;
}
case SPHERE_LOD_MEDIUM:
{
int numVertices = sizeof(medium_sphere_vertices) / strideInBytes;
int numIndices = sizeof(medium_sphere_indices) / sizeof(int);
graphicsShapeIndex = m_renderer->registerShape(&medium_sphere_vertices[0], numVertices, medium_sphere_indices, numIndices, B3_GL_TRIANGLES, textureId);
break;
}
case SPHERE_LOD_HIGH:
default:
{
int numVertices = sizeof(detailed_sphere_vertices) / strideInBytes;
int numIndices = sizeof(detailed_sphere_indices) / sizeof(int);
graphicsShapeIndex = m_renderer->registerShape(&detailed_sphere_vertices[0], numVertices, detailed_sphere_indices, numIndices, B3_GL_TRIANGLES, textureId);
break;
}
};
return graphicsShapeIndex;
}
int SimpleOpenGL2App::registerCubeShape(float halfExtentsX, float halfExtentsY, float halfExtentsZ, int textureIndex, float textureScaling)
{
int strideInBytes = 9 * sizeof(float);
int numVertices = sizeof(cube_vertices_textured) / strideInBytes;
int numIndices = sizeof(cube_indices) / sizeof(int);
b3AlignedObjectArray<GLInstanceVertex> verts;
verts.resize(numVertices);
for (int i = 0; i < numVertices; i++)
{
verts[i].xyzw[0] = halfExtentsX * cube_vertices_textured[i * 9];
verts[i].xyzw[1] = halfExtentsY * cube_vertices_textured[i * 9 + 1];
verts[i].xyzw[2] = halfExtentsZ * cube_vertices_textured[i * 9 + 2];
verts[i].xyzw[3] = cube_vertices_textured[i * 9 + 3];
verts[i].normal[0] = cube_vertices_textured[i * 9 + 4];
verts[i].normal[1] = cube_vertices_textured[i * 9 + 5];
verts[i].normal[2] = cube_vertices_textured[i * 9 + 6];
verts[i].uv[0] = cube_vertices_textured[i * 9 + 7] * textureScaling;
verts[i].uv[1] = cube_vertices_textured[i * 9 + 8] * textureScaling;
}
int shapeId = m_renderer->registerShape(&verts[0].xyzw[0], numVertices, cube_indices, numIndices, B3_GL_TRIANGLES, textureIndex);
return shapeId;
}

View file

@ -0,0 +1,32 @@
#ifndef SIMPLE_OPENGL2_APP_H
#define SIMPLE_OPENGL2_APP_H
#include "../CommonInterfaces/CommonGraphicsAppInterface.h"
class SimpleOpenGL2App : public CommonGraphicsApp
{
protected:
struct SimpleOpenGL2AppInternalData* m_data;
public:
SimpleOpenGL2App(const char* title, int width, int height);
virtual ~SimpleOpenGL2App();
virtual void drawGrid(DrawGridData data = DrawGridData());
virtual void setUpAxis(int axis);
virtual int getUpAxis() const;
virtual void swapBuffer();
virtual void drawText(const char* txt, int posX, int posY, float size, float colorRGBA[4]);
virtual void drawTexturedRect(float x0, float y0, float x1, float y1, float color[4], float u0, float v0, float u1, float v1, int useRGBA){};
virtual void setBackgroundColor(float red, float green, float blue);
virtual int registerCubeShape(float halfExtentsX, float halfExtentsY, float halfExtentsZ, int textureIndex = -1, float textureScaling = 1);
virtual int registerGraphicsUnitSphereShape(EnumSphereLevelOfDetail lod, int textureId = -1);
virtual void drawText3D(const char* txt, float posX, float posZY, float posZ, float size);
virtual void drawText3D(const char* txt, float position[3], float orientation[4], float color[4], float size, int optionFlag);
virtual void registerGrid(int xres, int yres, float color0[4], float color1[4]);
};
#endif //SIMPLE_OPENGL2_APP_H

View file

@ -0,0 +1,670 @@
#include "SimpleOpenGL2Renderer.h"
#include "OpenGL2Include.h"
#include "Bullet3Common/b3Vector3.h"
#include "Bullet3Common/b3AlignedObjectArray.h"
#include "GLInstanceGraphicsShape.h"
#include "Bullet3Common/b3Quaternion.h"
#include "Bullet3Common/b3Transform.h"
#include "Bullet3Common/b3ResizablePool.h"
B3_ATTRIBUTE_ALIGNED16(struct)
SimpleGL2Shape
{
B3_DECLARE_ALIGNED_ALLOCATOR();
int m_textureIndex;
int m_primitiveType;
b3AlignedObjectArray<int> m_indices;
b3AlignedObjectArray<GLInstanceVertex> m_vertices;
b3Vector3 m_scaling;
};
B3_ATTRIBUTE_ALIGNED16(struct)
SimpleGL2Instance
{
B3_DECLARE_ALIGNED_ALLOCATOR();
int m_shapeIndex;
b3Vector3 m_position;
b3Quaternion orn;
b3Vector4 m_rgbColor;
b3Vector3 m_scaling;
void clear()
{
}
};
struct InternalTextureHandle2
{
GLuint m_glTexture;
int m_width;
int m_height;
};
typedef b3PoolBodyHandle<SimpleGL2Instance> SimpleGL2InstanceHandle;
struct SimpleOpenGL2RendererInternalData
{
int m_width;
int m_height;
SimpleCamera m_camera;
b3AlignedObjectArray<SimpleGL2Shape*> m_shapes;
//b3AlignedObjectArray<SimpleGL2Instance> m_graphicsInstances1;
b3ResizablePool<SimpleGL2InstanceHandle> m_graphicsInstancesPool;
b3AlignedObjectArray<InternalTextureHandle2> m_textureHandles;
};
SimpleOpenGL2Renderer::SimpleOpenGL2Renderer(int width, int height)
{
m_data = new SimpleOpenGL2RendererInternalData;
m_data->m_width = width;
m_data->m_height = height;
}
SimpleOpenGL2Renderer::~SimpleOpenGL2Renderer()
{
delete m_data;
}
void SimpleOpenGL2Renderer::init()
{
}
const CommonCameraInterface* SimpleOpenGL2Renderer::getActiveCamera() const
{
return &m_data->m_camera;
}
CommonCameraInterface* SimpleOpenGL2Renderer::getActiveCamera()
{
return &m_data->m_camera;
}
void SimpleOpenGL2Renderer::setActiveCamera(CommonCameraInterface* cam)
{
b3Assert(0); //not supported yet
}
void SimpleOpenGL2Renderer::setLightPosition(const float lightPos[3])
{
}
void SimpleOpenGL2Renderer::setLightPosition(const double lightPos[3])
{
}
void SimpleOpenGL2Renderer::updateCamera(int upAxis)
{
float projection[16];
float view[16];
getActiveCamera()->setAspectRatio((float)m_data->m_width / (float)m_data->m_height);
getActiveCamera()->setCameraUpAxis(upAxis);
m_data->m_camera.update(); //??
getActiveCamera()->getCameraProjectionMatrix(projection);
getActiveCamera()->getCameraViewMatrix(view);
GLfloat projMat[16];
GLfloat viewMat[16];
for (int i = 0; i < 16; i++)
{
viewMat[i] = view[i];
projMat[i] = projection[i];
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMultMatrixf(projMat);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMultMatrixf(viewMat);
}
void SimpleOpenGL2Renderer::removeAllInstances()
{
for (int i = 0; i < m_data->m_shapes.size(); i++)
{
delete m_data->m_shapes[i];
}
m_data->m_shapes.clear();
m_data->m_graphicsInstancesPool.exitHandles();
m_data->m_graphicsInstancesPool.initHandles();
//also destroy textures?
m_data->m_textureHandles.clear();
}
void SimpleOpenGL2Renderer::removeGraphicsInstance(int instanceUid)
{
m_data->m_graphicsInstancesPool.freeHandle(instanceUid);
}
bool SimpleOpenGL2Renderer::readSingleInstanceTransformToCPU(float* position, float* orientation, int srcIndex)
{
return false;
}
void SimpleOpenGL2Renderer::writeSingleInstanceColorToCPU(const float* color, int srcIndex)
{
}
void SimpleOpenGL2Renderer::writeSingleInstanceColorToCPU(const double* color, int srcIndex)
{
}
void SimpleOpenGL2Renderer::writeSingleInstanceScaleToCPU(const float* scale, int srcIndex)
{
}
void SimpleOpenGL2Renderer::writeSingleInstanceScaleToCPU(const double* scale, int srcIndex)
{
}
int SimpleOpenGL2Renderer::getTotalNumInstances() const
{
return m_data->m_graphicsInstancesPool.getNumHandles();
}
void SimpleOpenGL2Renderer::getCameraViewMatrix(float viewMat[16]) const
{
b3Assert(0);
}
void SimpleOpenGL2Renderer::getCameraProjectionMatrix(float projMat[16]) const
{
b3Assert(0);
}
void SimpleOpenGL2Renderer::drawOpenGL(int instanceIndex)
{
const SimpleGL2Instance* instPtr = m_data->m_graphicsInstancesPool.getHandle(instanceIndex);
if (0 == instPtr)
{
b3Assert(0);
return;
}
const SimpleGL2Instance& inst = *instPtr;
const SimpleGL2Shape* shape = m_data->m_shapes[inst.m_shapeIndex];
if (inst.m_rgbColor[3] == 0)
{
return;
}
glPushMatrix();
b3Transform tr;
tr.setOrigin(b3MakeVector3(inst.m_position[0], inst.m_position[1], inst.m_position[2]));
tr.setRotation(b3Quaternion(inst.orn[0], inst.orn[1], inst.orn[2], inst.orn[3]));
b3Scalar m[16];
tr.getOpenGLMatrix(m);
#ifdef B3_USE_DOUBLE_PRECISION
glMultMatrixd(m);
#else
glMultMatrixf(m);
#endif
#if 0
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glScalef(0.025f,0.025f,0.025f);
glMatrixMode(GL_MODELVIEW);
static const GLfloat planex[]={1,0,0,0};
// static const GLfloat planey[]={0,1,0,0};
static const GLfloat planez[]={0,0,1,0};
glTexGenfv(GL_S,GL_OBJECT_PLANE,planex);
glTexGenfv(GL_T,GL_OBJECT_PLANE,planez);
glTexGeni(GL_S,GL_TEXTURE_GEN_MODE,GL_OBJECT_LINEAR);
glTexGeni(GL_T,GL_TEXTURE_GEN_MODE,GL_OBJECT_LINEAR);
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);
glEnable(GL_TEXTURE_GEN_R);
m_textureinitialized=true;
#endif
//drawCoordSystem();
//glPushMatrix();
// glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
// glMatrixMode(GL_TEXTURE);
// glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glEnable(GL_COLOR_MATERIAL);
if (shape->m_textureIndex >= 0)
{
glEnable(GL_TEXTURE_2D);
activateTexture(shape->m_textureIndex);
}
else
{
glDisable(GL_TEXTURE_2D);
}
glColor3f(inst.m_rgbColor[0], inst.m_rgbColor[1], inst.m_rgbColor[2]);
glScalef(inst.m_scaling[0], inst.m_scaling[1], inst.m_scaling[2]);
glShadeModel(GL_SMOOTH);
glBegin(GL_TRIANGLES);
for (int i = 0; i < shape->m_indices.size(); i += 3)
{
for (int v = 0; v < 3; v++)
{
const GLInstanceVertex& vtx0 = shape->m_vertices[shape->m_indices[i + v]];
glNormal3f(vtx0.normal[0], vtx0.normal[1], vtx0.normal[2]);
glTexCoord2f(vtx0.uv[0], vtx0.uv[1]);
glVertex3f(vtx0.xyzw[0], vtx0.xyzw[1], vtx0.xyzw[2]);
}
}
glEnd();
glPopMatrix();
}
void SimpleOpenGL2Renderer::drawSceneInternal(int pass, int cameraUpAxis)
{
b3AlignedObjectArray<int> usedHandles;
m_data->m_graphicsInstancesPool.getUsedHandles(usedHandles);
for (int i = 0; i < usedHandles.size(); i++)
{
drawOpenGL(usedHandles[i]);
}
#if 0
b3Scalar m[16];
b3Matrix3x3 rot;rot.setIdentity();
const int numObjects=dynamicsWorld->getNumCollisionObjects();
btVector3 wireColor(1,0,0);
//glDisable(GL_CULL_FACE);
for(int i=0;i<numObjects;i++)
{
const btCollisionObject* colObj=dynamicsWorld->getCollisionObjectArray()[i];
const btRigidBody* body=btRigidBody::upcast(colObj);
if(body&&body->getMotionState())
{
btDefaultMotionState* myMotionState = (btDefaultMotionState*)body->getMotionState();
myMotionState->m_graphicsWorldTrans.getOpenGLMatrix(m);
rot=myMotionState->m_graphicsWorldTrans.getBasis();
}
else
{
colObj->getWorldTransform().getOpenGLMatrix(m);
rot=colObj->getWorldTransform().getBasis();
}
btVector3 wireColor(1.f,1.0f,0.5f); //wants deactivation
if(i&1) wireColor=btVector3(0.f,0.0f,1.f);
///color differently for active, sleeping, wantsdeactivation states
if (colObj->getActivationState() == 1) //active
{
if (i & 1)
{
wireColor += btVector3 (1.f,0.f,0.f);
}
else
{
wireColor += btVector3 (.5f,0.f,0.f);
}
}
if(colObj->getActivationState()==2) //ISLAND_SLEEPING
{
if(i&1)
{
wireColor += btVector3 (0.f,1.f, 0.f);
}
else
{
wireColor += btVector3 (0.f,0.5f,0.f);
}
}
btVector3 aabbMin(0,0,0),aabbMax(0,0,0);
//m_dynamicsWorld->getBroadphase()->getBroadphaseAabb(aabbMin,aabbMax);
aabbMin-=btVector3(BT_LARGE_FLOAT,BT_LARGE_FLOAT,BT_LARGE_FLOAT);
aabbMax+=btVector3(BT_LARGE_FLOAT,BT_LARGE_FLOAT,BT_LARGE_FLOAT);
// printf("aabbMin=(%f,%f,%f)\n",aabbMin.getX(),aabbMin.getY(),aabbMin.getZ());
// printf("aabbMax=(%f,%f,%f)\n",aabbMax.getX(),aabbMax.getY(),aabbMax.getZ());
// m_dynamicsWorld->getDebugDrawer()->drawAabb(aabbMin,aabbMax,btVector3(1,1,1));
//switch(pass)
//if (!(getDebugMode()& btIDebugDraw::DBG_DrawWireframe))
int debugMode = 0;//getDebugMode()
//btVector3 m_sundirection(-1,-1,-1);
btVector3 m_sundirection(btVector3(1,-2,1)*1000);
if (cameraUpAxis==2)
{
m_sundirection = btVector3(1,1,-2)*1000;
}
switch(pass)
{
case 0: drawOpenGL(m,colObj->getCollisionShape(),wireColor,debugMode,aabbMin,aabbMax);break;
case 1: drawShadow(m,m_sundirection*rot,colObj->getCollisionShape(),aabbMin,aabbMax);break;
case 2: drawOpenGL(m,colObj->getCollisionShape(),wireColor*b3Scalar(0.3),0,aabbMin,aabbMax);break;
}
}
#endif
}
void SimpleOpenGL2Renderer::renderScene()
{
GLfloat light_ambient[] = {b3Scalar(0.2), b3Scalar(0.2), b3Scalar(0.2), b3Scalar(1.0)};
GLfloat light_diffuse[] = {b3Scalar(1.0), b3Scalar(1.0), b3Scalar(1.0), b3Scalar(1.0)};
GLfloat light_specular[] = {b3Scalar(1.0), b3Scalar(1.0), b3Scalar(1.0), b3Scalar(1.0)};
/* light_position is NOT default value */
GLfloat light_position0[] = {b3Scalar(1.0), b3Scalar(10.0), b3Scalar(1.0), b3Scalar(0.0)};
GLfloat light_position1[] = {b3Scalar(-1.0), b3Scalar(-10.0), b3Scalar(-1.0), b3Scalar(0.0)};
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position0);
glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT1, GL_POSITION, light_position1);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
drawSceneInternal(0, 0);
}
int SimpleOpenGL2Renderer::registerTexture(const unsigned char* texels, int width, int height, bool flipTexelsY)
{
b3Assert(glGetError() == GL_NO_ERROR);
glActiveTexture(GL_TEXTURE0);
int textureIndex = m_data->m_textureHandles.size();
// const GLubyte* image= (const GLubyte*)texels;
GLuint textureHandle;
glGenTextures(1, (GLuint*)&textureHandle);
glBindTexture(GL_TEXTURE_2D, textureHandle);
b3Assert(glGetError() == GL_NO_ERROR);
InternalTextureHandle2 h;
h.m_glTexture = textureHandle;
h.m_width = width;
h.m_height = height;
m_data->m_textureHandles.push_back(h);
updateTexture(textureIndex, texels, flipTexelsY);
return textureIndex;
}
void SimpleOpenGL2Renderer::updateTexture(int textureIndex, const unsigned char* texels, bool flipTexelsY)
{
if (textureIndex >= 0)
{
glActiveTexture(GL_TEXTURE0);
b3Assert(glGetError() == GL_NO_ERROR);
InternalTextureHandle2& h = m_data->m_textureHandles[textureIndex];
glBindTexture(GL_TEXTURE_2D, h.m_glTexture);
b3Assert(glGetError() == GL_NO_ERROR);
if (flipTexelsY)
{
//textures need to be flipped for OpenGL...
b3AlignedObjectArray<unsigned char> flippedTexels;
flippedTexels.resize(h.m_width * h.m_height * 3);
for (int i = 0; i < h.m_width; i++)
{
for (int j = 0; j < h.m_height; j++)
{
flippedTexels[(i + j * h.m_width) * 3] = texels[(i + (h.m_height - 1 - j) * h.m_width) * 3];
flippedTexels[(i + j * h.m_width) * 3 + 1] = texels[(i + (h.m_height - 1 - j) * h.m_width) * 3 + 1];
flippedTexels[(i + j * h.m_width) * 3 + 2] = texels[(i + (h.m_height - 1 - j) * h.m_width) * 3 + 2];
}
}
// const GLubyte* image= (const GLubyte*)texels;
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, h.m_width, h.m_height, 0, GL_RGB, GL_UNSIGNED_BYTE, &flippedTexels[0]);
}
else
{
// const GLubyte* image= (const GLubyte*)texels;
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, h.m_width, h.m_height, 0, GL_RGB, GL_UNSIGNED_BYTE, &texels[0]);
}
b3Assert(glGetError() == GL_NO_ERROR);
//glGenerateMipmap(GL_TEXTURE_2D);
b3Assert(glGetError() == GL_NO_ERROR);
}
}
void SimpleOpenGL2Renderer::removeTexture(int textureIndex)
{
if ((textureIndex >= 0) && (textureIndex < m_data->m_textureHandles.size()))
{
glDeleteTextures(1, &m_data->m_textureHandles[textureIndex].m_glTexture);
}
}
void SimpleOpenGL2Renderer::activateTexture(int textureIndex)
{
glActiveTexture(GL_TEXTURE0);
if (textureIndex >= 0)
{
glBindTexture(GL_TEXTURE_2D, m_data->m_textureHandles[textureIndex].m_glTexture);
}
else
{
glBindTexture(GL_TEXTURE_2D, 0);
}
}
int SimpleOpenGL2Renderer::registerGraphicsInstance(int shapeIndex, const double* position, const double* quaternion, const double* color, const double* scaling)
{
int newHandle = m_data->m_graphicsInstancesPool.allocHandle();
// int sz = m_data->m_graphicsInstances.size();
SimpleGL2Instance& instance = *m_data->m_graphicsInstancesPool.getHandle(newHandle);
instance.m_shapeIndex = shapeIndex;
instance.m_position[0] = position[0];
instance.m_position[1] = position[1];
instance.m_position[2] = position[2];
instance.orn[0] = quaternion[0];
instance.orn[1] = quaternion[1];
instance.orn[2] = quaternion[2];
instance.orn[3] = quaternion[3];
instance.m_rgbColor[0] = color[0];
instance.m_rgbColor[1] = color[1];
instance.m_rgbColor[2] = color[2];
instance.m_rgbColor[3] = color[3];
instance.m_scaling[0] = scaling[0];
instance.m_scaling[1] = scaling[1];
instance.m_scaling[2] = scaling[2];
return newHandle;
}
int SimpleOpenGL2Renderer::registerGraphicsInstance(int shapeIndex, const float* position, const float* quaternion, const float* color, const float* scaling)
{
int newHandle = m_data->m_graphicsInstancesPool.allocHandle();
SimpleGL2Instance& instance = *m_data->m_graphicsInstancesPool.getHandle(newHandle);
instance.m_shapeIndex = shapeIndex;
instance.m_position[0] = position[0];
instance.m_position[1] = position[1];
instance.m_position[2] = position[2];
instance.orn[0] = quaternion[0];
instance.orn[1] = quaternion[1];
instance.orn[2] = quaternion[2];
instance.orn[3] = quaternion[3];
instance.m_rgbColor[0] = color[0];
instance.m_rgbColor[1] = color[1];
instance.m_rgbColor[2] = color[2];
instance.m_rgbColor[3] = color[3];
instance.m_scaling[0] = scaling[0];
instance.m_scaling[1] = scaling[1];
instance.m_scaling[2] = scaling[2];
return newHandle;
}
void SimpleOpenGL2Renderer::drawLines(const float* positions, const float color[4], int numPoints, int pointStrideInBytes, const unsigned int* indices, int numIndices, float pointDrawSize)
{
int pointStrideInFloats = pointStrideInBytes / 4;
glLineWidth(pointDrawSize);
for (int i = 0; i < numIndices; i += 2)
{
int index0 = indices[i];
int index1 = indices[i + 1];
b3Vector3 fromColor = b3MakeVector3(color[0], color[1], color[2]);
b3Vector3 toColor = b3MakeVector3(color[0], color[1], color[2]);
b3Vector3 from = b3MakeVector3(positions[index0 * pointStrideInFloats], positions[index0 * pointStrideInFloats + 1], positions[index0 * pointStrideInFloats + 2]);
b3Vector3 to = b3MakeVector3(positions[index1 * pointStrideInFloats], positions[index1 * pointStrideInFloats + 1], positions[index1 * pointStrideInFloats + 2]);
glBegin(GL_LINES);
glColor3f(fromColor.getX(), fromColor.getY(), fromColor.getZ());
glVertex3d(from.getX(), from.getY(), from.getZ());
glColor3f(toColor.getX(), toColor.getY(), toColor.getZ());
glVertex3d(to.getX(), to.getY(), to.getZ());
glEnd();
}
}
void SimpleOpenGL2Renderer::drawLine(const float from[4], const float to[4], const float color[4], float lineWidth)
{
glLineWidth(lineWidth);
glBegin(GL_LINES);
glColor3f(color[0], color[1], color[2]);
glVertex3d(from[0], from[1], from[2]);
glVertex3d(to[0], to[1], to[2]);
glEnd();
}
int SimpleOpenGL2Renderer::registerShape(const float* vertices, int numvertices, const int* indices, int numIndices, int primitiveType, int textureIndex)
{
SimpleGL2Shape* shape = new SimpleGL2Shape();
shape->m_textureIndex = textureIndex;
shape->m_indices.resize(numIndices);
for (int i = 0; i < numIndices; i++)
{
shape->m_indices[i] = indices[i];
}
shape->m_vertices.resize(numvertices);
for (int v = 0; v < numvertices; v++)
{
GLInstanceVertex& vtx = shape->m_vertices[v];
vtx.xyzw[0] = vertices[9 * v + 0];
vtx.xyzw[1] = vertices[9 * v + 1];
vtx.xyzw[2] = vertices[9 * v + 2];
vtx.xyzw[3] = vertices[9 * v + 3];
vtx.normal[0] = vertices[9 * v + 4];
vtx.normal[1] = vertices[9 * v + 5];
vtx.normal[2] = vertices[9 * v + 6];
vtx.uv[0] = vertices[9 * v + 7];
vtx.uv[1] = vertices[9 * v + 8];
}
int sz = m_data->m_shapes.size();
m_data->m_shapes.push_back(shape);
return sz;
}
void SimpleOpenGL2Renderer::writeSingleInstanceTransformToCPU(const float* position, const float* orientation, int srcIndex)
{
SimpleGL2Instance& graphicsInstance = *m_data->m_graphicsInstancesPool.getHandle(srcIndex);
graphicsInstance.m_position[0] = position[0];
graphicsInstance.m_position[1] = position[1];
graphicsInstance.m_position[2] = position[2];
graphicsInstance.orn[0] = orientation[0];
graphicsInstance.orn[1] = orientation[1];
graphicsInstance.orn[2] = orientation[2];
graphicsInstance.orn[3] = orientation[3];
}
void SimpleOpenGL2Renderer::writeSingleInstanceTransformToCPU(const double* position, const double* orientation, int srcIndex)
{
SimpleGL2Instance& graphicsInstance = *m_data->m_graphicsInstancesPool.getHandle(srcIndex);
graphicsInstance.m_position[0] = position[0];
graphicsInstance.m_position[1] = position[1];
graphicsInstance.m_position[2] = position[2];
graphicsInstance.orn[0] = orientation[0];
graphicsInstance.orn[1] = orientation[1];
graphicsInstance.orn[2] = orientation[2];
graphicsInstance.orn[3] = orientation[3];
}
void SimpleOpenGL2Renderer::writeTransforms()
{
}
void SimpleOpenGL2Renderer::resize(int width, int height)
{
m_data->m_width = width;
m_data->m_height = height;
}
int SimpleOpenGL2Renderer::getScreenWidth()
{
return m_data->m_width;
}
int SimpleOpenGL2Renderer::getScreenHeight()
{
return m_data->m_height;
}
void SimpleOpenGL2Renderer::drawLine(const double from[4], const double to[4], const double color[4], double lineWidth)
{
glLineWidth(lineWidth);
glBegin(GL_LINES);
glColor3f(color[0], color[1], color[2]);
glVertex3d(from[0], from[1], from[2]);
glVertex3d(to[0], to[1], to[2]);
glEnd();
}
void SimpleOpenGL2Renderer::drawPoint(const float* position, const float color[4], float pointDrawSize)
{
}
void SimpleOpenGL2Renderer::drawPoint(const double* position, const double color[4], double pointDrawSize)
{
}
void SimpleOpenGL2Renderer::drawPoints(const float* positions, const float* colors, int numPoints, int pointStrideInBytes, float pointDrawSize)
{
}
void SimpleOpenGL2Renderer::updateShape(int shapeIndex, const float* vertices, int numVertices)
{
SimpleGL2Shape* shape = m_data->m_shapes[shapeIndex];
int numvertices = shape->m_vertices.size();
b3Assert(numVertices = numvertices);
if (numVertices != numvertices)
return;
for (int i = 0; i < numvertices; i++)
{
shape->m_vertices[i].xyzw[0] = vertices[9 * i + 0];
shape->m_vertices[i].xyzw[1] = vertices[9 * i + 1];
shape->m_vertices[i].xyzw[2] = vertices[9 * i + 2];
shape->m_vertices[i].xyzw[3] = vertices[9 * i + 3];
shape->m_vertices[i].normal[0] = vertices[9 * i + 4];
shape->m_vertices[i].normal[1] = vertices[9 * i + 5];
shape->m_vertices[i].normal[2] = vertices[9 * i + 6];
shape->m_vertices[i].uv[0] = vertices[9 * i + 7];
shape->m_vertices[i].uv[1] = vertices[9 * i + 8];
}
}
void SimpleOpenGL2Renderer::clearZBuffer()
{
glClear(GL_DEPTH_BUFFER_BIT);
}

View file

@ -0,0 +1,96 @@
#ifndef SIMPLE_OPENGL2_RENDERER_H
#define SIMPLE_OPENGL2_RENDERER_H
#include "../CommonInterfaces/CommonRenderInterface.h"
#include "SimpleCamera.h"
class SimpleOpenGL2Renderer : public CommonRenderInterface
{
struct SimpleOpenGL2RendererInternalData* m_data;
void drawSceneInternal(int pass, int cameraUpAxis);
void drawOpenGL(int instanceIndex);
public:
SimpleOpenGL2Renderer(int width, int height);
virtual ~SimpleOpenGL2Renderer();
virtual void init();
virtual void updateCamera(int upAxis);
virtual const CommonCameraInterface* getActiveCamera() const;
virtual CommonCameraInterface* getActiveCamera();
virtual void setActiveCamera(CommonCameraInterface* cam);
virtual void setLightPosition(const float lightPos[3]);
virtual void setLightPosition(const double lightPos[3]);
virtual void setShadowMapResolution(int shadowMapResolution) {}
virtual void setShadowMapIntensity(double shadowMapIntensity) {}
virtual void setShadowMapWorldSize(float worldSize) {}
virtual void resize(int width, int height);
virtual void setBackgroundColor(const double rgbBackground[3]) {}
virtual void removeAllInstances();
virtual void removeGraphicsInstance(int instanceUid);
virtual bool readSingleInstanceTransformToCPU(float* position, float* orientation, int srcIndex);
virtual void writeSingleInstanceColorToCPU(const float* color, int srcIndex);
virtual void writeSingleInstanceColorToCPU(const double* color, int srcIndex);
virtual void writeSingleInstanceScaleToCPU(const float* scale, int srcIndex);
virtual void writeSingleInstanceScaleToCPU(const double* scale, int srcIndex);
virtual void writeSingleInstanceSpecularColorToCPU(const double* specular, int srcIndex) {}
virtual void writeSingleInstanceSpecularColorToCPU(const float* specular, int srcIndex) {}
virtual void writeSingleInstanceFlagsToCPU(int flags, int srcIndex) {}
virtual void getCameraViewMatrix(float viewMat[16]) const;
virtual void getCameraProjectionMatrix(float projMat[16]) const;
virtual void drawTexturedTriangleMesh(float worldPosition[3], float worldOrientation[4], const float* vertices, int numvertices, const unsigned int* indices, int numIndices, float color[4], int textureIndex = -1, int vertexLayout = 0)
{
}
virtual void renderScene();
virtual int getScreenWidth();
virtual int getScreenHeight();
virtual int registerTexture(const unsigned char* texels, int width, int height, bool flipTexelsY);
virtual void updateTexture(int textureIndex, const unsigned char* texels, bool flipTexelsY);
virtual void activateTexture(int textureIndex);
virtual void removeTexture(int textureIndex);
virtual int registerGraphicsInstance(int shapeIndex, const double* position, const double* quaternion, const double* color, const double* scaling);
virtual int registerGraphicsInstance(int shapeIndex, const float* position, const float* quaternion, const float* color, const float* scaling);
virtual void drawLines(const float* positions, const float color[4], int numPoints, int pointStrideInBytes, const unsigned int* indices, int numIndices, float pointDrawSize);
virtual void drawLine(const float from[4], const float to[4], const float color[4], float lineWidth);
virtual int registerShape(const float* vertices, int numvertices, const int* indices, int numIndices, int primitiveType = B3_GL_TRIANGLES, int textureIndex = -1);
virtual void writeSingleInstanceTransformToCPU(const float* position, const float* orientation, int srcIndex);
virtual void writeSingleInstanceTransformToCPU(const double* position, const double* orientation, int srcIndex);
virtual int getTotalNumInstances() const;
virtual void writeTransforms();
virtual void drawLine(const double from[4], const double to[4], const double color[4], double lineWidth);
virtual void drawPoint(const float* position, const float color[4], float pointDrawSize);
virtual void drawPoint(const double* position, const double color[4], double pointDrawSize);
virtual void drawPoints(const float* positions, const float* colors, int numPoints, int pointStrideInBytes, float pointDrawSize);
virtual void updateShape(int shapeIndex, const float* vertices, int numVertices);
virtual void clearZBuffer();
virtual struct GLInstanceRendererInternalData* getInternalData()
{
return 0;
}
};
#endif //SIMPLE_OPENGL2_RENDERER_H

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,44 @@
#ifndef SIMPLE_OPENGL3_APP_H
#define SIMPLE_OPENGL3_APP_H
#include "../OpenGLWindow/GLInstancingRenderer.h"
#include "../OpenGLWindow/GLPrimitiveRenderer.h"
#include "../CommonInterfaces/CommonWindowInterface.h"
#include "../CommonInterfaces/CommonGraphicsAppInterface.h"
struct SimpleOpenGL3App : public CommonGraphicsApp
{
struct SimpleInternalData* m_data;
class GLPrimitiveRenderer* m_primRenderer;
class GLInstancingRenderer* m_instancingRenderer;
virtual void setBackgroundColor(float red, float green, float blue);
virtual void setMp4Fps(int fps);
SimpleOpenGL3App(const char* title, int width, int height, bool allowRetina = true, int windowType = 0, int renderDevice = -1, int maxNumObjectCapacity = 128 * 1024, int maxShapeCapacityInBytes = 128 * 1024 * 1024);
virtual ~SimpleOpenGL3App();
virtual int registerCubeShape(float halfExtentsX = 1.f, float halfExtentsY = 1.f, float halfExtentsZ = 1.f, int textureIndex = -1, float textureScaling = 1);
virtual int registerGraphicsUnitSphereShape(EnumSphereLevelOfDetail lod, int textureId = -1);
virtual void registerGrid(int xres, int yres, float color0[4], float color1[4]);
void dumpNextFrameToPng(const char* pngFilename);
void dumpFramesToVideo(const char* mp4Filename);
virtual void getScreenPixels(unsigned char* rgbaBuffer, int bufferSizeInBytes, float* depthBuffer, int depthBufferSizeInBytes);
virtual void setViewport(int width, int height);
void drawGrid(DrawGridData data = DrawGridData());
virtual void setUpAxis(int axis);
virtual int getUpAxis() const;
virtual void swapBuffer();
virtual void drawText(const char* txt, int posX, int posY, float size, float colorRGBA[4]);
virtual void drawText3D(const char* txt, float posX, float posZY, float posZ, float size);
virtual void drawText3D(const char* txt, float position[3], float orientation[4], float color[4], float size, int optionFlag);
virtual void drawTexturedRect(float x0, float y0, float x1, float y1, float color[4], float u0, float v0, float u1, float v1, int useRGBA);
struct sth_stash* getFontStash();
};
#endif //SIMPLE_OPENGL3_APP_H

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,62 @@
// ---------------------------------------------------------------------------
//
// @file TwFonts.h
// @brief Bitmaps fonts
// @author Philippe Decaudin - http://www.antisphere.com
// @license This file is part of the AntTweakBar library.
// For conditions of distribution and use, see License.txt
//
// note: Private header
//
// ---------------------------------------------------------------------------
#if !defined ANT_TW_FONTS_INCLUDED
#define ANT_TW_FONTS_INCLUDED
//#include <AntTweakBar.h>
/*
A source bitmap includes 224 characters starting from ascii char 32 (i.e. space) to ascii char 255:
!"#$%&'()*+,-./0123456789:;<=>?
@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_
`abcdefghijklmnopqrstuvwxyz{|}~
<EFBFBD>ƒˆŠŒ<EFBFBD>Ž<EFBFBD><EFBFBD>˜šœ<EFBFBD>žŸ
 ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ·¸¹º»¼½¾¿
ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞß
àáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
First column of a source bitmap is a delimiter with color=zero at the end of each line of characters.
Last row of a line of characters is a delimiter with color=zero at the last pixel of each character.
*/
struct CTexFont
{
unsigned char *m_TexBytes;
int m_TexWidth; // power of 2
int m_TexHeight; // power of 2
float m_CharU0[256];
float m_CharV0[256];
float m_CharU1[256];
float m_CharV1[256];
int m_CharWidth[256];
int m_CharHeight;
int m_NbCharRead;
CTexFont();
~CTexFont();
};
CTexFont *TwGenerateFont(const unsigned char *_Bitmap, int _BmWidth, int _BmHeight);
extern CTexFont *g_DefaultSmallFont;
extern CTexFont *g_DefaultNormalFont;
extern CTexFont *g_DefaultNormalFontAA;
extern CTexFont *g_DefaultLargeFont;
extern CTexFont *g_DefaultFixed1Font;
void TwGenerateDefaultFonts();
void TwDeleteDefaultFonts();
#endif // !defined ANT_TW_FONTS_INCLUDED

View file

@ -0,0 +1,65 @@
#ifndef WIN32_INTERNAL_WINDOW_DATA_H
#define WIN32_INTERNAL_WINDOW_DATA_H
#include <windows.h>
struct InternalData2
{
HWND m_hWnd;
;
int m_fullWindowWidth; //includes borders etc
int m_fullWindowHeight;
int m_openglViewportWidth; //just the 3d viewport/client area
int m_openglViewportHeight;
HDC m_hDC;
HGLRC m_hRC;
bool m_OpenGLInitialized;
int m_oldScreenWidth;
int m_oldHeight;
int m_oldBitsPerPel;
bool m_quit;
int m_mouseLButton;
int m_mouseRButton;
int m_mouseMButton;
int m_mouseXpos;
int m_mouseYpos;
int m_internalKeyModifierFlags;
b3WheelCallback m_wheelCallback;
b3MouseMoveCallback m_mouseMoveCallback;
b3MouseButtonCallback m_mouseButtonCallback;
b3ResizeCallback m_resizeCallback;
b3KeyboardCallback m_keyboardCallback;
InternalData2()
{
m_hWnd = 0;
m_mouseLButton = 0;
m_mouseRButton = 0;
m_mouseMButton = 0;
m_internalKeyModifierFlags = 0;
m_fullWindowWidth = 0;
m_fullWindowHeight = 0;
m_openglViewportHeight = 0;
m_openglViewportWidth = 0;
m_hDC = 0;
m_hRC = 0;
m_OpenGLInitialized = false;
m_oldScreenWidth = 0;
m_oldHeight = 0;
m_oldBitsPerPel = 0;
m_quit = false;
m_keyboardCallback = 0;
m_mouseMoveCallback = 0;
m_mouseButtonCallback = 0;
m_resizeCallback = 0;
m_wheelCallback = 0;
}
};
#endif //WIN32_INTERNAL_WINDOW_DATA_H

View file

@ -0,0 +1,170 @@
#ifndef B3_USE_GLFW
#ifdef _WIN32
/*
Copyright (c) 2012 Advanced Micro Devices, Inc.
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
//Originally written by Erwin Coumans
#include "Win32OpenGLWindow.h"
#include "OpenGLInclude.h"
//#include "Bullet3Common/b3Vector3.h"
#include "Win32InternalWindowData.h"
#include <stdio.h>
#include <stdlib.h>
void Win32OpenGLWindow::enableOpenGL()
{
PIXELFORMATDESCRIPTOR pfd;
int format;
// get the device context (DC)
m_data->m_hDC = GetDC(m_data->m_hWnd);
// set the pixel format for the DC
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cRedBits = 8;
pfd.cGreenBits = 8;
pfd.cBlueBits = 8;
pfd.cAlphaBits = 8;
pfd.cDepthBits = 24;
pfd.cStencilBits = 8; //1;
pfd.iLayerType = PFD_MAIN_PLANE;
format = ChoosePixelFormat(m_data->m_hDC, &pfd);
SetPixelFormat(m_data->m_hDC, format, &pfd);
// create and enable the render context (RC)
m_data->m_hRC = wglCreateContext(m_data->m_hDC);
wglMakeCurrent(m_data->m_hDC, m_data->m_hRC);
//printGLString("Extensions", GL_EXTENSIONS);
}
void Win32OpenGLWindow::disableOpenGL()
{
wglMakeCurrent(NULL, NULL);
wglDeleteContext(m_data->m_hRC);
// ReleaseDC( m_data->m_hWnd, m_data->m_hDC );
}
void Win32OpenGLWindow::createWindow(const b3gWindowConstructionInfo& ci)
{
Win32Window::createWindow(ci);
//VideoDriver = video::createOpenGLDriver(CreationParams, FileSystem, this);
enableOpenGL();
if (!gladLoaderLoadGL())
{
printf("gladLoaderLoadGL failed!\n");
exit(-1);
}
}
Win32OpenGLWindow::Win32OpenGLWindow()
{
}
Win32OpenGLWindow::~Win32OpenGLWindow()
{
}
void Win32OpenGLWindow::closeWindow()
{
disableOpenGL();
Win32Window::closeWindow();
}
void Win32OpenGLWindow::startRendering()
{
pumpMessage();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
//glCullFace(GL_BACK);
//glFrontFace(GL_CCW);
glEnable(GL_DEPTH_TEST);
}
void Win32OpenGLWindow::renderAllObjects()
{
}
void Win32OpenGLWindow::endRendering()
{
SwapBuffers(m_data->m_hDC);
}
int Win32OpenGLWindow::fileOpenDialog(char* fileName, int maxFileNameLength)
{
#if 0
//wchar_t wideChars[1024];
OPENFILENAME ofn ;
ZeroMemory( &ofn , sizeof( ofn));
ofn.lStructSize = sizeof ( ofn );
ofn.hwndOwner = NULL ;
#ifdef UNICODE
WCHAR bla[1024];
ofn.lpstrFile = bla;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = 1023;
ofn.lpstrFilter = L"All Files\0*.*\0URDF\0*.urdf\0.bullet\0*.bullet\0";
#else
ofn.lpstrFile = fileName;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = 1023;
//ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
ofn.lpstrFilter = "All Files\0*.*\0URDF\0*.urdf\0.bullet\0*.bullet\0";
#endif
ofn.nFilterIndex =1;
ofn.lpstrFileTitle = NULL ;
ofn.nMaxFileTitle = 0 ;
ofn.lpstrInitialDir=NULL ;
ofn.Flags = OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST ;
GetOpenFileName( &ofn );
return strlen(fileName);
#else
return 0;
#endif
}
int Win32OpenGLWindow::getWidth() const
{
if (m_data)
return m_data->m_openglViewportWidth;
return 0;
}
int Win32OpenGLWindow::getHeight() const
{
if (m_data)
return m_data->m_openglViewportHeight;
return 0;
}
#endif
#endif //B3_USE_GLFW

View file

@ -0,0 +1,56 @@
/*
Copyright (c) 2012 Advanced Micro Devices, Inc.
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
//Originally written by Erwin Coumans
#ifndef _WIN32_OPENGL_RENDER_MANAGER_H
#define _WIN32_OPENGL_RENDER_MANAGER_H
#include "Win32Window.h"
#define b3gDefaultOpenGLWindow Win32OpenGLWindow
class Win32OpenGLWindow : public Win32Window
{
bool m_OpenGLInitialized;
protected:
void enableOpenGL();
void disableOpenGL();
public:
Win32OpenGLWindow();
virtual ~Win32OpenGLWindow();
virtual void createWindow(const b3gWindowConstructionInfo& ci);
virtual void closeWindow();
virtual void startRendering();
virtual void renderAllObjects();
virtual void endRendering();
virtual float getRetinaScale() const { return 1.f; }
virtual void setAllowRetina(bool /*allowRetina*/){};
virtual int getWidth() const;
virtual int getHeight() const;
virtual int fileOpenDialog(char* fileName, int maxFileNameLength);
};
#endif //_WIN32_OPENGL_RENDER_MANAGER_H

View file

@ -0,0 +1,879 @@
#ifdef _WIN32
/*
Copyright (c) 2012 Advanced Micro Devices, Inc.
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
//Originally written by Erwin Coumans
#include "Win32Window.h"
#include "OpenGLInclude.h"
#include <wchar.h>
static InternalData2* sData = 0;
#include "Win32InternalWindowData.h"
enum
{
INTERNAL_SHIFT_MODIFIER = 1,
INTERNAL_ALT_MODIFIER = 2,
INTERNAL_CONTROL_MODIFIER = 4,
};
void Win32Window::pumpMessage()
{
MSG msg;
// check for messages
//'if' instead of 'while' can make mainloop smoother.
//@todo: use separate threads for input and rendering
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// handle or dispatch messages
if (msg.message == WM_QUIT)
{
m_data->m_quit = TRUE;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// gDemoApplication->displayCallback();
};
}
int getSpecialKeyFromVirtualKeycode(int virtualKeyCode)
{
int keycode = -1;
if (virtualKeyCode >= 'A' && virtualKeyCode <= 'Z')
{
return virtualKeyCode + 32; //todo: fix the ascii A vs a input
}
if (virtualKeyCode >= '0' && virtualKeyCode <= '9')
{
return virtualKeyCode;
}
switch (virtualKeyCode)
{
case VK_SPACE:
{
keycode = B3G_SPACE;
break;
}
case VK_RETURN:
{
keycode = B3G_RETURN;
break;
};
case VK_ESCAPE:
{
keycode = B3G_ESCAPE;
break;
};
case VK_F1:
{
keycode = B3G_F1;
break;
}
case VK_F2:
{
keycode = B3G_F2;
break;
}
case VK_F3:
{
keycode = B3G_F3;
break;
}
case VK_F4:
{
keycode = B3G_F4;
break;
}
case VK_F5:
{
keycode = B3G_F5;
break;
}
case VK_F6:
{
keycode = B3G_F6;
break;
}
case VK_F7:
{
keycode = B3G_F7;
break;
}
case VK_F8:
{
keycode = B3G_F8;
break;
}
case VK_F9:
{
keycode = B3G_F9;
break;
}
case VK_F10:
{
keycode = B3G_F10;
break;
}
//case VK_SPACE: {keycode= ' '; break;}
case VK_NEXT:
{
keycode = B3G_PAGE_DOWN;
break;
}
case VK_PRIOR:
{
keycode = B3G_PAGE_UP;
break;
}
case VK_INSERT:
{
keycode = B3G_INSERT;
break;
}
case VK_BACK:
{
keycode = B3G_BACKSPACE;
break;
}
case VK_DELETE:
{
keycode = B3G_DELETE;
break;
}
case VK_END:
{
keycode = B3G_END;
break;
}
case VK_HOME:
{
keycode = B3G_HOME;
break;
}
case VK_LEFT:
{
keycode = B3G_LEFT_ARROW;
break;
}
case VK_UP:
{
keycode = B3G_UP_ARROW;
break;
}
case VK_RIGHT:
{
keycode = B3G_RIGHT_ARROW;
break;
}
case VK_DOWN:
{
keycode = B3G_DOWN_ARROW;
break;
}
case VK_SHIFT:
{
keycode = B3G_SHIFT;
break;
}
case VK_MENU:
{
keycode = B3G_ALT;
break;
}
case VK_CONTROL:
{
keycode = B3G_CONTROL;
break;
}
default:
{
//keycode = MapVirtualKey( virtualKeyCode, MAPVK_VK_TO_CHAR ) & 0x0000FFFF;
}
};
return keycode;
}
int getAsciiCodeFromVirtualKeycode(int virtualKeyCode)
{
int keycode = 0xffffffff;
if (virtualKeyCode >= 'a' && virtualKeyCode <= 'z')
{
return virtualKeyCode;
}
if (virtualKeyCode >= 'A' && virtualKeyCode <= 'Z')
{
return virtualKeyCode + 32; //todo: fix the ascii A vs a input
}
return keycode;
}
bool Win32Window::isModifierKeyPressed(int key)
{
bool isPressed = false;
switch (key)
{
case B3G_ALT:
{
isPressed = ((sData->m_internalKeyModifierFlags & INTERNAL_ALT_MODIFIER) != 0);
break;
};
case B3G_SHIFT:
{
isPressed = ((sData->m_internalKeyModifierFlags & INTERNAL_SHIFT_MODIFIER) != 0);
break;
};
case B3G_CONTROL:
{
isPressed = ((sData->m_internalKeyModifierFlags & INTERNAL_CONTROL_MODIFIER) != 0);
break;
};
default:
{
}
};
return isPressed; //m_internalKeyModifierFlags
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
//printf("msg = %d\n", message);
switch (message)
{
case WM_PAINT:
{
PAINTSTRUCT ps;
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
}
return 1;
case WM_ERASEBKGND:
return 1;
case WM_CLOSE:
if (sData)
sData->m_quit = true;
//PostQuitMessage(0);
return 1;
case WM_DESTROY:
if (sData)
sData->m_quit = true;
//PostQuitMessage(0);
return 1;
case WM_SYSKEYUP:
case WM_KEYUP:
{
int keycode = getSpecialKeyFromVirtualKeycode(wParam);
switch (keycode)
{
case B3G_ALT:
{
sData->m_internalKeyModifierFlags &= ~INTERNAL_ALT_MODIFIER;
break;
};
case B3G_SHIFT:
{
sData->m_internalKeyModifierFlags &= ~INTERNAL_SHIFT_MODIFIER;
break;
};
case B3G_CONTROL:
{
sData->m_internalKeyModifierFlags &= ~INTERNAL_CONTROL_MODIFIER;
break;
};
}
if (keycode >= 0 && sData && sData->m_keyboardCallback)
{
int state = 0;
(*sData->m_keyboardCallback)(keycode, state);
}
return 0;
}
case WM_CHAR:
{
#if 0
//skip 'enter' key, it is processed in WM_KEYUP/WM_KEYDOWN
int keycode = getAsciiCodeFromVirtualKeycode(wParam);
if (keycode < 0)
{
if (sData && sData->m_keyboardCallback && ((HIWORD(lParam) & KF_REPEAT) == 0))
{
int state = 1;
(*sData->m_keyboardCallback)(wParam, state);
}
}
#endif
return 0;
}
case WM_SYSKEYDOWN:
case WM_KEYDOWN:
{
int keycode = getSpecialKeyFromVirtualKeycode(wParam);
switch (keycode)
{
case B3G_ALT:
{
sData->m_internalKeyModifierFlags |= INTERNAL_ALT_MODIFIER;
break;
};
case B3G_SHIFT:
{
sData->m_internalKeyModifierFlags |= INTERNAL_SHIFT_MODIFIER;
break;
};
case B3G_CONTROL:
{
sData->m_internalKeyModifierFlags |= INTERNAL_CONTROL_MODIFIER;
break;
};
}
if (keycode >= 0 && sData && sData->m_keyboardCallback && ((HIWORD(lParam) & KF_REPEAT) == 0))
{
int state = 1;
(*sData->m_keyboardCallback)(keycode, state);
return 1;
}
return 0;
}
case WM_MBUTTONUP:
{
int xPos = LOWORD(lParam);
int yPos = HIWORD(lParam);
if (sData)
{
sData->m_mouseMButton = 0;
sData->m_mouseXpos = xPos;
sData->m_mouseYpos = yPos;
if (sData && sData->m_mouseButtonCallback)
(*sData->m_mouseButtonCallback)(1, 0, xPos, yPos);
}
break;
}
case WM_MBUTTONDOWN:
{
int xPos = LOWORD(lParam);
int yPos = HIWORD(lParam);
if (sData)
{
sData->m_mouseMButton = 1;
sData->m_mouseXpos = xPos;
sData->m_mouseYpos = yPos;
if (sData && sData->m_mouseButtonCallback)
(*sData->m_mouseButtonCallback)(1, 1, xPos, yPos);
}
break;
}
case WM_LBUTTONUP:
{
int xPos = LOWORD(lParam);
int yPos = HIWORD(lParam);
if (sData)
{
sData->m_mouseLButton = 0;
sData->m_mouseXpos = xPos;
sData->m_mouseYpos = yPos;
if (sData && sData->m_mouseButtonCallback)
(*sData->m_mouseButtonCallback)(0, 0, xPos, yPos);
}
// gDemoApplication->mouseFunc(0,1,xPos,yPos);
break;
}
case WM_LBUTTONDOWN:
{
int xPos = LOWORD(lParam);
int yPos = HIWORD(lParam);
if (sData)
{
sData->m_mouseLButton = 1;
sData->m_mouseXpos = xPos;
sData->m_mouseYpos = yPos;
if (sData && sData->m_mouseButtonCallback)
(*sData->m_mouseButtonCallback)(0, 1, xPos, yPos);
}
break;
}
case 0x020e: //WM_MOUSEWHEEL_LEFT_RIGHT
{
int zDelta = (short)HIWORD(wParam);
int xPos = LOWORD(lParam);
int yPos = HIWORD(lParam);
//m_cameraDistance -= zDelta*0.01;
if (sData && sData->m_wheelCallback)
(*sData->m_wheelCallback)(-float(zDelta) * 0.05f, 0);
return 1;
break;
}
case 0x020A: //WM_MOUSEWHEEL:
{
int zDelta = (short)HIWORD(wParam);
int xPos = LOWORD(lParam);
int yPos = HIWORD(lParam);
//m_cameraDistance -= zDelta*0.01;
if (sData && sData->m_wheelCallback)
(*sData->m_wheelCallback)(0, float(zDelta) * 0.05f);
return 1;
break;
}
case WM_MOUSEMOVE:
{
int xPos = LOWORD(lParam);
int yPos = HIWORD(lParam);
sData->m_mouseXpos = xPos;
sData->m_mouseYpos = yPos;
if (sData && sData->m_mouseMoveCallback)
(*sData->m_mouseMoveCallback)(xPos, yPos);
break;
}
case WM_RBUTTONUP:
{
int xPos = LOWORD(lParam);
int yPos = HIWORD(lParam);
sData->m_mouseRButton = 1;
if (sData && sData->m_mouseButtonCallback)
(*sData->m_mouseButtonCallback)(2, 0, sData->m_mouseXpos, sData->m_mouseYpos);
//gDemoApplication->mouseFunc(2,1,xPos,yPos);
break;
}
case WM_RBUTTONDOWN:
{
int xPos = LOWORD(lParam);
int yPos = HIWORD(lParam);
sData->m_mouseRButton = 0;
if (sData && sData->m_mouseButtonCallback)
(*sData->m_mouseButtonCallback)(2, 1, sData->m_mouseXpos, sData->m_mouseYpos);
break;
}
case WM_QUIT:
{
return 0;
break;
}
case WM_SIZE: // Size Action Has Taken Place
RECT clientRect;
GetClientRect(hWnd, &clientRect);
switch (wParam) // Evaluate Size Action
{
case SIZE_MINIMIZED: // Was Window Minimized?
return 0; // Return
case SIZE_MAXIMIZED: // Was Window Maximized?
case SIZE_RESTORED: // Was Window Restored?
RECT wr;
GetWindowRect(hWnd, &wr);
sData->m_fullWindowWidth = wr.right - wr.left;
sData->m_fullWindowHeight = wr.bottom - wr.top; //LOWORD (lParam) HIWORD (lParam);
sData->m_openglViewportWidth = clientRect.right;
sData->m_openglViewportHeight = clientRect.bottom;
if (sData->m_resizeCallback)
{
glViewport(0, 0, sData->m_openglViewportWidth, sData->m_openglViewportHeight);
(*sData->m_resizeCallback)(sData->m_openglViewportWidth, sData->m_openglViewportHeight);
}
//if (sOpenGLInitialized)
//{
// //gDemoApplication->reshape(sWidth,sHeight);
//}
return 0; // Return
}
break;
default:
{
}
};
return DefWindowProc(hWnd, message, wParam, lParam);
}
void Win32Window::setWindowTitle(const char* titleChar)
{
#ifdef _WIN64
SetWindowTextA(m_data->m_hWnd, titleChar);
#else
#ifdef UNICODE
DWORD dwResult;
SendMessageTimeoutA(m_data->m_hWnd, WM_SETTEXT, 0,
reinterpret_cast<LPARAM>(titleChar),
SMTO_ABORTIFHUNG, 2000, &dwResult);
#else
DWORD dwResult;
SendMessageTimeout(m_data->m_hWnd, WM_SETTEXT, 0,
reinterpret_cast<LPARAM>(titleChar),
SMTO_ABORTIFHUNG, 2000, &dwResult);
#endif
#endif
}
void Win32Window::createWindow(const b3gWindowConstructionInfo& ci)
{
int oglViewportWidth = ci.m_width;
int oglViewportHeight = ci.m_height;
bool fullscreen = ci.m_fullscreen;
int colorBitsPerPixel = ci.m_colorBitsPerPixel;
void* windowHandle = ci.m_windowHandle;
// get handle to exe file
HINSTANCE hInstance = GetModuleHandle(0);
// create the window if we need to and we do not use the null device
if (!windowHandle)
{
#ifdef UNICODE
const wchar_t* ClassName = L"DeviceWin32";
const wchar_t* emptyString = L"";
#else
const char* ClassName = "DeviceWin32";
const char* emptyString = "";
#endif
// Register Class
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); //(HICON)LoadImage(hInstance, "bullet_ico.ico", IMAGE_ICON, 0,0, LR_LOADTRANSPARENT);//LR_LOADFROMFILE);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = 0;
wcex.lpszClassName = ClassName;
wcex.hIconSm = 0;
// if there is an icon, load it
// wcex.hIcon = (HICON)LoadImage(hInstance, "bullet.ico", IMAGE_ICON, 0,0, LR_LOADFROMFILE);
RegisterClassEx(&wcex);
// calculate client size
RECT clientSize;
clientSize.top = 0;
clientSize.left = 0;
clientSize.right = oglViewportWidth;
clientSize.bottom = oglViewportHeight;
DWORD style = WS_POPUP;
if (!fullscreen)
style = WS_SYSMENU | WS_BORDER | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SIZEBOX;
AdjustWindowRect(&clientSize, style, false);
m_data->m_fullWindowWidth = clientSize.right - clientSize.left;
m_data->m_fullWindowHeight = clientSize.bottom - clientSize.top;
int windowLeft = (GetSystemMetrics(SM_CXSCREEN) - m_data->m_fullWindowWidth) / 2;
int windowTop = (GetSystemMetrics(SM_CYSCREEN) - m_data->m_fullWindowHeight) / 2;
if (fullscreen)
{
windowLeft = 0;
windowTop = 0;
}
// create window
m_data->m_hWnd = CreateWindow(ClassName, emptyString, style, windowLeft, windowTop,
m_data->m_fullWindowWidth, m_data->m_fullWindowHeight, NULL, NULL, hInstance, NULL);
RECT clientRect;
GetClientRect(m_data->m_hWnd, &clientRect);
ShowWindow(m_data->m_hWnd, SW_SHOW);
UpdateWindow(m_data->m_hWnd);
MoveWindow(m_data->m_hWnd, windowLeft, windowTop, m_data->m_fullWindowWidth, m_data->m_fullWindowHeight, TRUE);
GetClientRect(m_data->m_hWnd, &clientRect);
int w = clientRect.right - clientRect.left;
int h = clientRect.bottom - clientRect.top;
// printf("actual client OpenGL viewport width / height = %d, %d\n",w,h);
m_data->m_openglViewportHeight = h;
m_data->m_openglViewportWidth = w;
}
else if (windowHandle)
{
// attach external window
m_data->m_hWnd = static_cast<HWND>(windowHandle);
RECT r;
GetWindowRect(m_data->m_hWnd, &r);
m_data->m_fullWindowWidth = r.right - r.left;
m_data->m_fullWindowHeight = r.bottom - r.top;
//sFullScreen = false;
//sExternalWindow = true;
}
if (fullscreen)
{
DEVMODE dm;
memset(&dm, 0, sizeof(dm));
dm.dmSize = sizeof(dm);
// use default values from current setting
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
m_data->m_oldScreenWidth = dm.dmPelsWidth;
m_data->m_oldHeight = dm.dmPelsHeight;
m_data->m_oldBitsPerPel = dm.dmBitsPerPel;
dm.dmPelsWidth = oglViewportWidth;
dm.dmPelsHeight = oglViewportHeight;
if (colorBitsPerPixel)
{
dm.dmBitsPerPel = colorBitsPerPixel;
}
dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY;
LONG res = ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
if (res != DISP_CHANGE_SUCCESSFUL)
{ // try again without forcing display frequency
dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
res = ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
}
}
}
void Win32Window::switchFullScreen(bool fullscreen, int width, int height, int colorBitsPerPixel)
{
LONG res;
DEVMODE dm;
memset(&dm, 0, sizeof(dm));
dm.dmSize = sizeof(dm);
// use default values from current setting
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY;
if (fullscreen && !m_data->m_oldScreenWidth)
{
m_data->m_oldScreenWidth = dm.dmPelsWidth;
m_data->m_oldHeight = dm.dmPelsHeight;
m_data->m_oldBitsPerPel = dm.dmBitsPerPel;
if (width && height)
{
dm.dmPelsWidth = width;
dm.dmPelsHeight = height;
}
else
{
dm.dmPelsWidth = m_data->m_fullWindowWidth;
dm.dmPelsHeight = m_data->m_fullWindowHeight;
}
if (colorBitsPerPixel)
{
dm.dmBitsPerPel = colorBitsPerPixel;
}
}
else
{
if (m_data->m_oldScreenWidth)
{
dm.dmPelsWidth = m_data->m_oldScreenWidth;
dm.dmPelsHeight = m_data->m_oldHeight;
dm.dmBitsPerPel = m_data->m_oldBitsPerPel;
}
}
if (fullscreen)
{
res = ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
if (!res)
{
dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
res = ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
}
DWORD style = WS_POPUP;
SetWindowLong(m_data->m_hWnd, GWL_STYLE, style);
MoveWindow(m_data->m_hWnd, 0, 0, m_data->m_fullWindowWidth, m_data->m_fullWindowHeight, TRUE);
SetWindowPos(m_data->m_hWnd, NULL, 0, 0, (int)width, (int)height,
SWP_FRAMECHANGED | SWP_SHOWWINDOW); //|SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOOWNERZORDER | SWP_NOREPOSITION | SWP_NOZORDER);
}
else
{
res = ChangeDisplaySettings(&dm, 0);
DWORD style = WS_SYSMENU | WS_BORDER | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SIZEBOX;
SetWindowLong(m_data->m_hWnd, GWL_STYLE, style);
SetWindowPos(m_data->m_hWnd, NULL, 0, 0, (int)width, (int)height,
SWP_FRAMECHANGED | SWP_SHOWWINDOW);
//|SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOOWNERZORDER | SWP_NOREPOSITION | SWP_NOZORDER);
}
}
Win32Window::Win32Window()
{
m_data = new InternalData2();
sData = m_data;
}
Win32Window::~Win32Window()
{
setKeyboardCallback(0);
setMouseMoveCallback(0);
setMouseButtonCallback(0);
setWheelCallback(0);
setResizeCallback(0);
sData = 0;
delete m_data;
}
void Win32Window::setRenderCallback(b3RenderCallback renderCallback)
{
}
void Win32Window::closeWindow()
{
setKeyboardCallback(0);
setMouseMoveCallback(0);
setMouseButtonCallback(0);
setWheelCallback(0);
setResizeCallback(0);
setRenderCallback(0);
DestroyWindow(this->m_data->m_hWnd);
}
void Win32Window::getMouseCoordinates(int& x, int& y)
{
x = m_data->m_mouseXpos;
y = m_data->m_mouseYpos;
}
void Win32Window::runMainLoop()
{
}
void Win32Window::startRendering()
{
pumpMessage();
}
void Win32Window::renderAllObjects()
{
}
void Win32Window::endRendering()
{
SwapBuffers(m_data->m_hDC);
}
float Win32Window::getTimeInSeconds()
{
return 0.f;
}
void Win32Window::setDebugMessage(int x, int y, const char* message)
{
}
void Win32Window::setRequestExit()
{
m_data->m_quit = true;
}
bool Win32Window::requestedExit() const
{
return m_data->m_quit;
}
void Win32Window::setWheelCallback(b3WheelCallback wheelCallback)
{
m_data->m_wheelCallback = wheelCallback;
}
void Win32Window::setMouseMoveCallback(b3MouseMoveCallback mouseCallback)
{
m_data->m_mouseMoveCallback = mouseCallback;
}
void Win32Window::setMouseButtonCallback(b3MouseButtonCallback mouseCallback)
{
m_data->m_mouseButtonCallback = mouseCallback;
}
void Win32Window::setResizeCallback(b3ResizeCallback resizeCallback)
{
m_data->m_resizeCallback = resizeCallback;
if (m_data->m_resizeCallback)
(*m_data->m_resizeCallback)(m_data->m_openglViewportWidth, m_data->m_openglViewportHeight);
}
void Win32Window::setKeyboardCallback(b3KeyboardCallback keyboardCallback)
{
m_data->m_keyboardCallback = keyboardCallback;
}
b3KeyboardCallback Win32Window::getKeyboardCallback()
{
return m_data->m_keyboardCallback;
}
b3MouseMoveCallback Win32Window::getMouseMoveCallback()
{
return m_data->m_mouseMoveCallback;
}
b3MouseButtonCallback Win32Window::getMouseButtonCallback()
{
return m_data->m_mouseButtonCallback;
}
b3ResizeCallback Win32Window::getResizeCallback()
{
return m_data->m_resizeCallback;
}
b3WheelCallback Win32Window::getWheelCallback()
{
return m_data->m_wheelCallback;
}
#endif

View file

@ -0,0 +1,78 @@
/*
Copyright (c) 2012 Advanced Micro Devices, Inc.
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
//Originally written by Erwin Coumans
#ifndef _WIN32_WINDOW_H
#define _WIN32_WINDOW_H
struct InternalData2;
#include "../CommonInterfaces/CommonWindowInterface.h"
class Win32Window : public CommonWindowInterface
{
protected:
struct InternalData2* m_data;
void pumpMessage();
public:
Win32Window();
virtual ~Win32Window();
virtual void createWindow(const b3gWindowConstructionInfo& ci);
virtual void switchFullScreen(bool fullscreen, int width = 0, int height = 0, int colorBitsPerPixel = 0);
virtual void closeWindow();
virtual void runMainLoop();
virtual void startRendering();
virtual void renderAllObjects();
virtual void endRendering();
virtual float getTimeInSeconds();
virtual void setDebugMessage(int x, int y, const char* message);
virtual bool requestedExit() const;
virtual void setRequestExit();
virtual void getMouseCoordinates(int& x, int& y);
virtual void setMouseMoveCallback(b3MouseMoveCallback mouseCallback);
virtual void setMouseButtonCallback(b3MouseButtonCallback mouseCallback);
virtual void setResizeCallback(b3ResizeCallback resizeCallback);
virtual void setWheelCallback(b3WheelCallback wheelCallback);
virtual void setKeyboardCallback(b3KeyboardCallback keyboardCallback);
virtual b3MouseMoveCallback getMouseMoveCallback();
virtual b3MouseButtonCallback getMouseButtonCallback();
virtual b3ResizeCallback getResizeCallback();
virtual b3WheelCallback getWheelCallback();
virtual b3KeyboardCallback getKeyboardCallback();
virtual void setRenderCallback(b3RenderCallback renderCallback);
virtual void setWindowTitle(const char* title);
virtual bool isModifierKeyPressed(int key);
};
#endif //_WIN32_WINDOW_H

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,72 @@
#ifndef X11_OPENGL_WINDOW_H
#define X11_OPENGL_WINDOW_H
#define b3gDefaultOpenGLWindow X11OpenGLWindow
#include "../CommonInterfaces/CommonWindowInterface.h"
class X11OpenGLWindow : public CommonWindowInterface
{
struct InternalData2* m_data;
bool m_OpenGLInitialized;
bool m_requestedExit;
protected:
void enableOpenGL();
void disableOpenGL();
void pumpMessage();
int getAsciiCodeFromVirtualKeycode(int orgCode);
public:
X11OpenGLWindow();
virtual ~X11OpenGLWindow();
virtual void createWindow(const b3gWindowConstructionInfo& ci);
virtual void closeWindow();
virtual void startRendering();
virtual void renderAllObjects();
virtual void endRendering();
virtual float getRetinaScale() const { return 1.f; }
virtual void setAllowRetina(bool /*allowRetina*/){};
virtual void runMainLoop();
virtual float getTimeInSeconds();
virtual bool requestedExit() const;
virtual void setRequestExit();
virtual bool isModifierKeyPressed(int key);
virtual void setMouseMoveCallback(b3MouseMoveCallback mouseCallback);
virtual void setMouseButtonCallback(b3MouseButtonCallback mouseCallback);
virtual void setResizeCallback(b3ResizeCallback resizeCallback);
virtual void setWheelCallback(b3WheelCallback wheelCallback);
virtual void setKeyboardCallback(b3KeyboardCallback keyboardCallback);
virtual b3MouseMoveCallback getMouseMoveCallback();
virtual b3MouseButtonCallback getMouseButtonCallback();
virtual b3ResizeCallback getResizeCallback();
virtual b3WheelCallback getWheelCallback();
virtual b3KeyboardCallback getKeyboardCallback();
virtual void setRenderCallback(b3RenderCallback renderCallback);
virtual void setWindowTitle(const char* title);
virtual int getWidth() const;
virtual int getHeight() const;
int fileOpenDialog(char* filename, int maxNameLength);
};
#endif

View file

@ -0,0 +1,889 @@
//
// Copyright (c) 2011 Andreas Krinke andreas.krinke@gmx.de
// Copyright (c) 2009 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#define STB_TRUETYPE_IMPLEMENTATION
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <windows.h>
#endif
#include "fontstash.h"
#define BORDER_X_LEFT 2
#define BORDER_X_RIGHT 2
#define BORDER_Y_TOP 2
#define BORDER_Y_BOTTOM 2
#define ADDITIONAL_HEIGHT 2
#define STB_TRUETYPE_IMPLEMENTATION
#define STBTT_malloc(x, u) malloc(x)
#define STBTT_free(x, u) free(x)
#include "stb_image/stb_truetype.h"
#define HASH_LUT_SIZE 256
#define TTFONT_FILE 1
#define TTFONT_MEM 2
#define BMFONT 3
static int idx = 1;
static float s_retinaScale = 1;
static unsigned int hashint(unsigned int a)
{
a += ~(a << 15);
a ^= (a >> 10);
a += (a << 3);
a ^= (a >> 6);
a += ~(a << 11);
a ^= (a >> 16);
return a;
}
struct sth_font
{
int idx;
int type;
stbtt_fontinfo font;
unsigned char* data;
struct sth_glyph* glyphs;
int lut[HASH_LUT_SIZE];
int nglyphs;
float ascender;
float descender;
float lineh;
struct sth_font* next;
};
struct sth_stash
{
int tw, th;
float itw, ith;
struct sth_texture* textures;
struct sth_font* fonts;
int drawing;
RenderCallbacks* m_renderCallbacks;
};
// Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
// See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
#define UTF8_ACCEPT 0
#define UTF8_REJECT 1
static const unsigned char utf8d[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1f
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3f
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5f
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7f
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9f
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // a0..bf
8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // c0..df
0xa, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // e0..ef
0xb, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // f0..ff
0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2
1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4
1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6
1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // s7..s8
};
static unsigned int decutf8(unsigned int* state, unsigned int* codep, unsigned int byte)
{
unsigned int type = utf8d[byte];
*codep = (*state != UTF8_ACCEPT) ? (byte & 0x3fu) | (*codep << 6) : (0xff >> type) & (byte);
*state = utf8d[256 + *state * 16 + type];
return *state;
}
struct sth_stash* sth_create(int cachew, int cacheh, RenderCallbacks* renderCallbacks)
{
struct sth_stash* stash = NULL;
struct sth_texture* texture = NULL;
// Allocate memory for the font stash.
stash = (struct sth_stash*)malloc(sizeof(struct sth_stash));
if (stash == NULL)
{
assert(0);
return NULL;
}
memset(stash, 0, sizeof(struct sth_stash));
stash->m_renderCallbacks = renderCallbacks;
// Allocate memory for the first texture
texture = (struct sth_texture*)malloc(sizeof(struct sth_texture));
if (texture == NULL)
{
assert(0);
free(stash);
}
memset(texture, 0, sizeof(struct sth_texture));
// Create first texture for the cache.
stash->tw = cachew;
stash->th = cacheh;
stash->itw = 1.0f / cachew;
stash->ith = 1.0f / cacheh;
stash->textures = texture;
stash->m_renderCallbacks->updateTexture(texture, 0, stash->tw, stash->th);
return stash;
}
int sth_add_font_from_memory(struct sth_stash* stash, unsigned char* buffer)
{
int i, ascent, descent, fh, lineGap;
struct sth_font* fnt = NULL;
fnt = (struct sth_font*)malloc(sizeof(struct sth_font));
if (fnt == NULL) goto error;
memset(fnt, 0, sizeof(struct sth_font));
// Init hash lookup.
for (i = 0; i < HASH_LUT_SIZE; ++i)
fnt->lut[i] = -1;
fnt->data = buffer;
// Init stb_truetype
if (!stbtt_InitFont(&fnt->font, fnt->data, 0))
goto error;
// Store normalized line height. The real line height is got
// by multiplying the lineh by font size.
stbtt_GetFontVMetrics(&fnt->font, &ascent, &descent, &lineGap);
fh = ascent - descent;
fnt->ascender = (float)ascent / (float)fh;
fnt->descender = (float)descent / (float)fh;
fnt->lineh = (float)(fh + lineGap) / (float)fh;
fnt->idx = idx;
fnt->type = TTFONT_MEM;
fnt->next = stash->fonts;
stash->fonts = fnt;
return idx++;
error:
if (fnt)
{
if (fnt->glyphs) free(fnt->glyphs);
free(fnt);
}
return 0;
}
int sth_add_font(struct sth_stash* stash, const char* path)
{
FILE* fp = 0;
int datasize;
unsigned char* data = NULL;
int idx = 0;
// Read in the font data.
fp = fopen(path, "rb");
if (!fp) goto error;
fseek(fp, 0, SEEK_END);
datasize = (int)ftell(fp);
fseek(fp, 0, SEEK_SET);
data = (unsigned char*)malloc(datasize);
if (data == NULL) goto error;
int bytesRead;
bytesRead = fread(data, 1, datasize, fp);
if (bytesRead)
{
idx = sth_add_font_from_memory(stash, data);
}
fclose(fp);
fp = 0;
// Modify type of the loaded font.
if (idx)
stash->fonts->type = TTFONT_FILE;
else
free(data);
return idx;
error:
if (data) free(data);
if (fp) fclose(fp);
return 0;
}
int sth_add_bitmap_font(struct sth_stash* stash, int ascent, int descent, int line_gap)
{
int i, fh;
struct sth_font* fnt = NULL;
fnt = (struct sth_font*)malloc(sizeof(struct sth_font));
if (fnt == NULL) goto error;
memset(fnt, 0, sizeof(struct sth_font));
// Init hash lookup.
for (i = 0; i < HASH_LUT_SIZE; ++i) fnt->lut[i] = -1;
// Store normalized line height. The real line height is got
// by multiplying the lineh by font size.
fh = ascent - descent;
fnt->ascender = (float)ascent / (float)fh;
fnt->descender = (float)descent / (float)fh;
fnt->lineh = (float)(fh + line_gap) / (float)fh;
fnt->idx = idx;
fnt->type = BMFONT;
fnt->next = stash->fonts;
stash->fonts = fnt;
return idx++;
error:
if (fnt) free(fnt);
return 0;
}
/*void sth_add_glyph(struct sth_stash* stash,
int idx,
unsigned int id1,
const char* s,
short size, short base,
int x, int y, int w, int h,
float xoffset, float yoffset, float xadvance)
{
struct sth_texture* texture = NULL;
struct sth_font* fnt = NULL;
struct sth_glyph* glyph = NULL;
unsigned int codepoint;
unsigned int state = 0;
if (stash == NULL) return;
texture = stash->textures;
while (texture != NULL && texture->id != id)
texture = texture->next;
if (texture == NULL)
{
// Create new texture
texture = (struct sth_texture*)malloc(sizeof(struct sth_texture));
if (texture == NULL) return;
memset(texture, 0, sizeof(struct sth_texture));
texture->id = id;
texture->next = stash->textures;
stash->textures = texture;
}
fnt = stash->fonts;
while (fnt != NULL && fnt->idx != idx) fnt = fnt->next;
if (fnt == NULL) return;
if (fnt->type != BMFONT) return;
for (; *s; ++s)
{
if (!decutf8(&state, &codepoint, *(unsigned char*)s)) break;
}
if (state != UTF8_ACCEPT) return;
// Alloc space for new glyph.
fnt->nglyphs++;
fnt->glyphs = (sth_glyph*)realloc(fnt->glyphs, fnt->nglyphs*sizeof(struct sth_glyph));
if (!fnt->glyphs) return;
// Init glyph.
glyph = &fnt->glyphs[fnt->nglyphs-1];
memset(glyph, 0, sizeof(struct sth_glyph));
glyph->codepoint = codepoint;
glyph->size = size;
glyph->texture = texture;
glyph->x0_ = x;
glyph->y0 = y;
glyph->x1 = glyph->x0_+w;
glyph->y1 = glyph->y0+h;
glyph->xoff = xoffset;
glyph->yoff = yoffset - base;
glyph->xadv = xadvance;
// Find code point and size.
h = hashint(codepoint) & (HASH_LUT_SIZE-1);
// Insert char to hash lookup.
glyph->next = fnt->lut[h];
fnt->lut[h] = fnt->nglyphs-1;
}
*/
static struct sth_glyph* get_glyph(struct sth_stash* stash, struct sth_font* fnt, unsigned int codepoint, short isize)
{
int i, g, advance, lsb, x0, y0, x1, y1, gw, gh;
float scale;
struct sth_texture* texture = NULL;
struct sth_glyph* glyph = NULL;
unsigned int h;
float size = isize / 10.0f;
int rh;
struct sth_row* br = NULL;
// Find code point and size.
h = hashint(codepoint) & (HASH_LUT_SIZE - 1);
i = fnt->lut[h];
while (i != -1)
{
if (fnt->glyphs[i].codepoint == codepoint && (fnt->type == BMFONT || fnt->glyphs[i].size == isize))
return &fnt->glyphs[i];
i = fnt->glyphs[i].next;
}
// Could not find glyph.
// For bitmap fonts: ignore this glyph.
if (fnt->type == BMFONT) return 0;
// For truetype fonts: create this glyph.
scale = stbtt_ScaleForPixelHeight(&fnt->font, size);
g = stbtt_FindGlyphIndex(&fnt->font, codepoint);
stbtt_GetGlyphHMetrics(&fnt->font, g, &advance, &lsb);
stbtt_GetGlyphBitmapBox(&fnt->font, g, scale, scale, &x0, &y0, &x1, &y1);
gw = x1 - x0;
gh = y1 - y0;
// Check if glyph is larger than maximum texture size
if (gw >= stash->tw || gh >= stash->th)
return 0;
// Find texture and row where the glyph can be fit.
br = NULL;
rh = (gh + 7) & ~7;
texture = stash->textures;
while (br == NULL)
{
for (i = 0; i < texture->nrows; ++i)
{
if (texture->rows[i].h >= rh && texture->rows[i].x + gw + 1 <= stash->tw)
br = &texture->rows[i];
}
// If no row is found, there are 3 possibilities:
// - add new row
// - try next texture
// - create new texture
if (br == NULL)
{
short py = BORDER_Y_TOP;
// Check that there is enough space.
if (texture->nrows)
{
py = texture->rows[texture->nrows - 1].y + texture->rows[texture->nrows - 1].h + 1;
if (py + rh > stash->th)
{
if (texture->next != NULL)
{
texture = texture->next;
}
else
{
// Create new texture
texture->next = (struct sth_texture*)malloc(sizeof(struct sth_texture));
texture = texture->next;
if (texture == NULL) goto error;
memset(texture, 0, sizeof(struct sth_texture));
stash->m_renderCallbacks->updateTexture(texture, 0, stash->tw, stash->th);
}
continue;
}
}
// Init and add row
br = &texture->rows[texture->nrows];
br->x = BORDER_X_LEFT;
br->y = py + BORDER_Y_BOTTOM;
br->h = rh + ADDITIONAL_HEIGHT;
texture->nrows++;
}
}
// Alloc space for new glyph.
fnt->nglyphs++;
fnt->glyphs = (sth_glyph*)realloc(fnt->glyphs, fnt->nglyphs * sizeof(struct sth_glyph));
if (!fnt->glyphs) return 0;
// Init glyph.
glyph = &fnt->glyphs[fnt->nglyphs - 1];
memset(glyph, 0, sizeof(struct sth_glyph));
glyph->codepoint = codepoint;
glyph->size = isize;
glyph->texture = texture;
glyph->x0_ = br->x;
glyph->y0 = br->y;
glyph->x1 = glyph->x0_ + gw;
glyph->y1 = glyph->y0 + gh;
glyph->xadv = scale * advance;
glyph->xoff = (float)x0;
glyph->yoff = (float)y0;
glyph->next = 0;
// Advance row location.
br->x += gw + BORDER_X_RIGHT;
// Insert char to hash lookup.
glyph->next = fnt->lut[h];
fnt->lut[h] = fnt->nglyphs - 1;
// Rasterize
{
unsigned char* ptr = texture->m_texels + glyph->x0_ + glyph->y0 * stash->tw;
stbtt_MakeGlyphBitmap(&fnt->font, ptr, gw, gh, stash->tw, scale, scale, g);
stash->m_renderCallbacks->updateTexture(texture, glyph, stash->tw, stash->th);
}
return glyph;
error:
if (texture)
free(texture);
return 0;
}
static int get_quad(struct sth_stash* stash, struct sth_font* fnt, struct sth_glyph* glyph, short isize, float* x, float* y, struct sth_quad* q)
{
float rx, ry;
float scale = 1.f / s_retinaScale; //1.0f;
if (fnt->type == BMFONT)
scale = isize / (glyph->size * 10.0f);
rx = (*x + scale * float(glyph->xoff));
ry = (*y + scale * float(glyph->yoff));
q->x0 = rx;
q->y0 = ry + 1.5f * 0.5f * float(isize) / 10.f;
q->x1 = rx + scale * float(glyph->x1 - glyph->x0_);
q->y1 = ry + scale * float(glyph->y1 - glyph->y0) + 1.5f * 0.5f * float(isize) / 10.f;
q->s0 = float(glyph->x0_) * stash->itw;
q->t0 = float(glyph->y0) * stash->ith;
q->s1 = float(glyph->x1) * stash->itw;
q->t1 = float(glyph->y1) * stash->ith;
*x += scale * glyph->xadv;
return 1;
}
static int get_quad3D(struct sth_stash* stash, struct sth_font* fnt, struct sth_glyph* glyph, short isize2, float* x, float* y, struct sth_quad* q, float fontSize, float textScale)
{
short isize = 1;
float rx, ry;
float scale = textScale / fontSize; //0.1;//1.0f;
if (fnt->type == BMFONT)
scale = isize / (glyph->size);
rx = (*x + scale * float(glyph->xoff));
ry = (scale * float(glyph->yoff));
q->x0 = rx;
q->y0 = *y - (ry);
q->x1 = rx + scale * float(glyph->x1 - glyph->x0_);
q->y1 = *y - (ry + scale * float(glyph->y1 - glyph->y0));
q->s0 = float(glyph->x0_) * stash->itw;
q->t0 = float(glyph->y0) * stash->ith;
q->s1 = float(glyph->x1) * stash->itw;
q->t1 = float(glyph->y1) * stash->ith;
*x += scale * glyph->xadv;
return 1;
}
static Vertex* setv(Vertex* v, float x, float y, float s, float t, float width, float height, float colorRGBA[4])
{
bool scale = true;
if (scale)
{
v->position.p[0] = (x * 2 - width) / (width);
v->position.p[1] = 1 - (y) / (height / 2);
}
else
{
v->position.p[0] = (x - width) / (width);
v->position.p[1] = (height - y) / (height);
}
v->position.p[2] = 0.f;
v->position.p[3] = 1.f;
v->uv.p[0] = s;
v->uv.p[1] = t;
v->colour.p[0] = 0.1; //colorRGBA[0];
v->colour.p[1] = 0.1; //colorRGBA[1];
v->colour.p[2] = 0.1; //colorRGBA[2];
v->colour.p[3] = 1.0; //colorRGBA[3];
return v + 1;
}
static Vertex* setv3D(Vertex* v, float x, float y, float z, float s, float t, float colorRGBA[4])
{
v->position.p[0] = x;
v->position.p[1] = y;
v->position.p[2] = z;
v->position.p[3] = 1.f;
v->uv.p[0] = s;
v->uv.p[1] = t;
v->colour.p[0] = colorRGBA[0];
v->colour.p[1] = colorRGBA[1];
v->colour.p[2] = colorRGBA[2];
v->colour.p[3] = colorRGBA[3];
return v + 1;
}
static void flush_draw(struct sth_stash* stash)
{
struct sth_texture* texture = stash->textures;
while (texture)
{
if (texture->nverts > 0)
{
stash->m_renderCallbacks->render(texture);
texture->nverts = 0;
}
texture = texture->next;
}
}
void sth_begin_draw(struct sth_stash* stash)
{
if (stash == NULL) return;
if (stash->drawing)
flush_draw(stash);
stash->drawing = 1;
}
void sth_end_draw(struct sth_stash* stash)
{
if (stash == NULL) return;
if (!stash->drawing) return;
/*
// Debug dump.
if (stash->nverts+6 < VERT_COUNT)
{
float x = 500, y = 100;
float* v = &stash->verts[stash->nverts*4];
v = setv(v, x, y, 0, 0);
v = setv(v, x+stash->tw, y, 1, 0);
v = setv(v, x+stash->tw, y+stash->th, 1, 1);
v = setv(v, x, y, 0, 0);
v = setv(v, x+stash->tw, y+stash->th, 1, 1);
v = setv(v, x, y+stash->th, 0, 1);
stash->nverts += 6;
}
*/
flush_draw(stash);
stash->drawing = 0;
}
void sth_draw_texture(struct sth_stash* stash,
int idx, float size,
float x, float y,
int screenwidth, int screenheight,
const char* s, float* dx, float colorRGBA[4])
{
int width = stash->tw;
int height = stash->th;
unsigned int codepoint;
struct sth_glyph* glyph = NULL;
struct sth_texture* texture = NULL;
unsigned int state = 0;
struct sth_quad q;
short isize = (short)(size * 10.0f);
Vertex* v;
struct sth_font* fnt = NULL;
if (stash == NULL) return;
if (!stash->textures) return;
fnt = stash->fonts;
while (fnt != NULL && fnt->idx != idx) fnt = fnt->next;
if (fnt == NULL) return;
if (fnt->type != BMFONT && !fnt->data) return;
int once = true;
for (; once; ++s)
{
once = false;
if (decutf8(&state, &codepoint, *(unsigned char*)s))
continue;
glyph = get_glyph(stash, fnt, codepoint, isize);
if (!glyph)
continue;
texture = glyph->texture;
if (texture->nverts + 6 >= VERT_COUNT)
flush_draw(stash);
if (!get_quad(stash, fnt, glyph, isize, &x, &y, &q))
continue;
v = &texture->newverts[texture->nverts];
q.x0 = 0;
q.y0 = 0;
q.x1 = q.x0 + width;
q.y1 = q.y0 + height;
v = setv(v, q.x0, q.y0, 0, 0, (float)screenwidth, (float)screenheight, colorRGBA);
v = setv(v, q.x1, q.y0, 1, 0, (float)screenwidth, (float)screenheight, colorRGBA);
v = setv(v, q.x1, q.y1, 1, 1, (float)screenwidth, (float)screenheight, colorRGBA);
v = setv(v, q.x0, q.y0, 0, 0, (float)screenwidth, (float)screenheight, colorRGBA);
v = setv(v, q.x1, q.y1, 1, 1, (float)screenwidth, (float)screenheight, colorRGBA);
v = setv(v, q.x0, q.y1, 0, 1, (float)screenwidth, (float)screenheight, colorRGBA);
texture->nverts += 6;
}
flush_draw(stash);
if (dx) *dx = x;
}
void sth_flush_draw(struct sth_stash* stash)
{
flush_draw(stash);
}
void sth_draw_text(struct sth_stash* stash,
int idx, float size,
float x, float y,
const char* s, float* dx, int screenwidth, int screenheight, int measureOnly, float retinaScale, float colorRGBA[4])
{
unsigned int codepoint;
struct sth_glyph* glyph = NULL;
struct sth_texture* texture = NULL;
unsigned int state = 0;
struct sth_quad q;
short isize = (short)(size * 10.0f);
Vertex* v;
struct sth_font* fnt = NULL;
s_retinaScale = retinaScale;
if (stash == NULL) return;
if (!stash->textures) return;
fnt = stash->fonts;
while (fnt != NULL && fnt->idx != idx) fnt = fnt->next;
if (fnt == NULL) return;
if (fnt->type != BMFONT && !fnt->data) return;
for (; *s; ++s)
{
if (decutf8(&state, &codepoint, *(unsigned char*)s))
continue;
glyph = get_glyph(stash, fnt, codepoint, isize);
if (!glyph) continue;
texture = glyph->texture;
if (!measureOnly)
{
if (texture->nverts + 6 >= VERT_COUNT)
flush_draw(stash);
}
if (!get_quad(stash, fnt, glyph, isize, &x, &y, &q)) continue;
if (!measureOnly)
{
v = &texture->newverts[texture->nverts];
v = setv(v, q.x0, q.y0, q.s0, q.t0, (float)screenwidth, (float)screenheight, colorRGBA);
v = setv(v, q.x1, q.y0, q.s1, q.t0, (float)screenwidth, (float)screenheight, colorRGBA);
v = setv(v, q.x1, q.y1, q.s1, q.t1, (float)screenwidth, (float)screenheight, colorRGBA);
v = setv(v, q.x0, q.y0, q.s0, q.t0, (float)screenwidth, (float)screenheight, colorRGBA);
v = setv(v, q.x1, q.y1, q.s1, q.t1, (float)screenwidth, (float)screenheight, colorRGBA);
v = setv(v, q.x0, q.y1, q.s0, q.t1, (float)screenwidth, (float)screenheight, colorRGBA);
texture->nverts += 6;
}
}
if (dx) *dx = x;
}
void sth_draw_text3D(struct sth_stash* stash,
int idx, float fontSize,
float x, float y, float z,
const char* s, float* dx, float textScale, float colorRGBA[4], int unused)
{
unsigned int codepoint;
struct sth_glyph* glyph = NULL;
struct sth_texture* texture = NULL;
unsigned int state = 0;
struct sth_quad q;
short isize = (short)(fontSize * 10.0f);
Vertex* v;
struct sth_font* fnt = NULL;
s_retinaScale = 1;
if (stash == NULL) return;
if (!stash->textures) return;
fnt = stash->fonts;
while (fnt != NULL && fnt->idx != idx) fnt = fnt->next;
if (fnt == NULL) return;
if (fnt->type != BMFONT && !fnt->data) return;
for (; *s; ++s)
{
if (decutf8(&state, &codepoint, *(unsigned char*)s))
continue;
glyph = get_glyph(stash, fnt, codepoint, isize);
if (!glyph) continue;
texture = glyph->texture;
if (texture->nverts + 6 >= VERT_COUNT)
flush_draw(stash);
if (!get_quad3D(stash, fnt, glyph, isize, &x, &y, &q, fontSize, textScale)) continue;
{
v = &texture->newverts[texture->nverts];
v = setv3D(v, q.x0, q.y0, z, q.s0, q.t0, colorRGBA);
v = setv3D(v, q.x1, q.y0, z, q.s1, q.t0, colorRGBA);
v = setv3D(v, q.x1, q.y1, z, q.s1, q.t1, colorRGBA);
v = setv3D(v, q.x0, q.y0, z, q.s0, q.t0, colorRGBA);
v = setv3D(v, q.x1, q.y1, z, q.s1, q.t1, colorRGBA);
v = setv3D(v, q.x0, q.y1, z, q.s0, q.t1, colorRGBA);
texture->nverts += 6;
}
}
if (dx) *dx = x;
}
void sth_dim_text(struct sth_stash* stash,
int idx, float size,
const char* s,
float* minx, float* miny, float* maxx, float* maxy)
{
unsigned int codepoint;
struct sth_glyph* glyph = NULL;
unsigned int state = 0;
struct sth_quad q;
short isize = (short)(size * 10.0f);
struct sth_font* fnt = NULL;
float x = 0, y = 0;
if (stash == NULL)
return;
if (!stash->textures)
return;
fnt = stash->fonts;
while (fnt != NULL && fnt->idx != idx) fnt = fnt->next;
if (fnt == NULL) return;
if (fnt->type != BMFONT && !fnt->data) return;
*minx = *maxx = x;
*miny = *maxy = y;
for (; *s; ++s)
{
if (decutf8(&state, &codepoint, *(unsigned char*)s)) continue;
glyph = get_glyph(stash, fnt, codepoint, isize);
if (!glyph) continue;
if (!get_quad(stash, fnt, glyph, isize, &x, &y, &q)) continue;
if (q.x0 < *minx) *minx = q.x0;
if (q.x1 > *maxx) *maxx = q.x1;
if (q.y1 < *miny) *miny = q.y1;
if (q.y0 > *maxy) *maxy = q.y0;
}
}
void sth_vmetrics(struct sth_stash* stash,
int idx, float size,
float* ascender, float* descender, float* lineh)
{
struct sth_font* fnt = NULL;
if (stash == NULL) return;
if (!stash->textures) return;
fnt = stash->fonts;
while (fnt != NULL && fnt->idx != idx) fnt = fnt->next;
if (fnt == NULL) return;
if (fnt->type != BMFONT && !fnt->data) return;
if (ascender)
*ascender = fnt->ascender * size;
if (descender)
*descender = fnt->descender * size;
if (lineh)
*lineh = fnt->lineh * size;
}
void sth_delete(struct sth_stash* stash)
{
struct sth_texture* tex = NULL;
struct sth_texture* curtex = NULL;
struct sth_font* fnt = NULL;
struct sth_font* curfnt = NULL;
if (!stash) return;
tex = stash->textures;
while (tex != NULL)
{
curtex = tex;
free(tex->m_texels);
tex->m_texels = 0;
tex = tex->next;
stash->m_renderCallbacks->updateTexture(curtex, 0, 0, 0);
free(curtex);
}
fnt = stash->fonts;
while (fnt != NULL)
{
curfnt = fnt;
fnt = fnt->next;
if (curfnt->glyphs)
{
free(curfnt->glyphs);
}
if (curfnt->type == TTFONT_FILE && curfnt->data)
{
free(curfnt->data);
}
free(curfnt);
}
free(stash);
}

View file

@ -0,0 +1,154 @@
//
// Copyright (c) 2011 Andreas Krinke andreas.krinke@gmx.de
// Copyright (c) 2009 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef FONTSTASH_H
#define FONTSTASH_H
#define MAX_ROWS 128
#define VERT_COUNT (16 * 128)
#define INDEX_COUNT (VERT_COUNT * 2)
struct vec2
{
vec2(float x, float y)
{
p[0] = x;
p[1] = y;
}
float p[2];
};
struct vec4
{
vec4(float x, float y, float z, float w)
{
p[0] = x;
p[1] = y;
p[2] = z;
p[3] = w;
}
float p[4];
};
typedef struct
{
vec4 position;
vec4 colour;
vec2 uv;
} Vertex;
struct sth_quad
{
float x0, y0, s0, t0;
float x1, y1, s1, t1;
};
struct sth_row
{
short x, y, h;
};
struct sth_glyph
{
unsigned int codepoint;
short size;
struct sth_texture* texture;
int x0_, y0, x1, y1;
float xadv, xoff, yoff;
int next;
};
struct sth_texture
{
union {
void* m_userData;
int m_userId;
};
unsigned char* m_texels;
// TODO: replace rows with pointer
struct sth_row rows[MAX_ROWS];
int nrows;
int nverts;
Vertex newverts[VERT_COUNT];
struct sth_texture* next;
};
struct RenderCallbacks
{
virtual ~RenderCallbacks() {}
virtual void setColorRGBA(float color[4]) = 0;
virtual void setWorldPosition(float pos[3]) = 0;
virtual void setWorldOrientation(float orn[4]) = 0;
virtual void updateTexture(sth_texture* texture, sth_glyph* glyph, int textureWidth, int textureHeight) = 0;
virtual void render(sth_texture* texture) = 0;
};
struct sth_stash* sth_create(int cachew, int cacheh, RenderCallbacks* callbacks);
int sth_add_font(struct sth_stash* stash, const char* path);
int sth_add_font_from_memory(struct sth_stash* stash, unsigned char* buffer);
int sth_add_bitmap_font(struct sth_stash* stash, int ascent, int descent, int line_gap);
/*void sth_add_glyph(struct sth_stash* stash, int idx, unsigned int uid, const char* s,
short size, short base, int x, int y, int w, int h,
float xoffset, float yoffset, float xadvance);
*/
void sth_begin_draw(struct sth_stash* stash);
void sth_end_draw(struct sth_stash* stash);
void sth_draw_texture(struct sth_stash* stash,
int idx, float size,
float x, float y,
int screenwidth, int screenheight,
const char* s, float* dx, float colorRGBA[4]);
void sth_flush_draw(struct sth_stash* stash);
void sth_draw_text3D(struct sth_stash* stash,
int idx, float fontSize,
float x, float y, float z,
const char* s, float* dx, float textScale, float colorRGBA[4], int bla);
void sth_draw_text(struct sth_stash* stash,
int idx, float size,
float x, float y, const char* string, float* dx, int screenwidth, int screenheight, int measureOnly, float retinaScale, float colorRGBA[4]);
inline void sth_draw_text(struct sth_stash* stash,
int idx, float size,
float x, float y, const char* string, float* dx, int screenwidth, int screenheight, int measureOnly = false, float retinaScale = 1.)
{
float colorRGBA[4] = {1, 1, 1, 1};
sth_draw_text(stash, idx, size, x, y, string, dx, screenwidth, screenheight, measureOnly, retinaScale, colorRGBA);
}
void sth_dim_text(struct sth_stash* stash, int idx, float size, const char* string,
float* minx, float* miny, float* maxx, float* maxy);
void sth_vmetrics(struct sth_stash* stash,
int idx, float size,
float* ascender, float* descender, float* lineh);
void sth_delete(struct sth_stash* stash);
#endif // FONTSTASH_H

View file

@ -0,0 +1,242 @@
#ifndef NO_OPENGL3
#include "opengl_fontstashcallbacks.h"
#include "../OpenGLWindow/GLPrimitiveRenderer.h"
#include "../OpenGLWindow/GLPrimInternalData.h"
#include "fontstash.h"
#include "../OpenGLWindow/OpenGLInclude.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stb_image/stb_image_write.h"
static unsigned int s_indexData[INDEX_COUNT];
static GLuint s_indexArrayObject, s_indexBuffer;
static GLuint s_vertexArrayObject, s_vertexBuffer;
OpenGL2RenderCallbacks::OpenGL2RenderCallbacks(GLPrimitiveRenderer* primRender)
: m_primRender2(primRender)
{
}
OpenGL2RenderCallbacks::~OpenGL2RenderCallbacks()
{
}
PrimInternalData* OpenGL2RenderCallbacks::getData()
{
return m_primRender2->getData();
}
InternalOpenGL2RenderCallbacks::~InternalOpenGL2RenderCallbacks()
{
}
void InternalOpenGL2RenderCallbacks::display2()
{
assert(glGetError() == GL_NO_ERROR);
// glViewport(0,0,10,10);
//const float timeScale = 0.008f;
PrimInternalData* data = getData();
glUseProgram(data->m_shaderProg);
glBindBuffer(GL_ARRAY_BUFFER, s_vertexBuffer);
glBindVertexArray(s_vertexArrayObject);
assert(glGetError() == GL_NO_ERROR);
// glBindTexture(GL_TEXTURE_2D,m_texturehandle);
assert(glGetError() == GL_NO_ERROR);
float identity[16] = {1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1};
glUniformMatrix4fv(data->m_viewmatUniform, 1, false, identity);
glUniformMatrix4fv(data->m_projMatUniform, 1, false, identity);
vec2 p(0.f, 0.f); //?b?0.5f * sinf(timeValue), 0.5f * cosf(timeValue) );
glUniform2fv(data->m_positionUniform, 1, (const GLfloat*)&p);
assert(glGetError() == GL_NO_ERROR);
glEnableVertexAttribArray(data->m_positionAttribute);
assert(glGetError() == GL_NO_ERROR);
glEnableVertexAttribArray(data->m_colourAttribute);
assert(glGetError() == GL_NO_ERROR);
glEnableVertexAttribArray(data->m_textureAttribute);
glVertexAttribPointer(data->m_positionAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)0);
glVertexAttribPointer(data->m_colourAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)sizeof(vec4));
glVertexAttribPointer(data->m_textureAttribute, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)(sizeof(vec4) + sizeof(vec4)));
assert(glGetError() == GL_NO_ERROR);
/*
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer);
//glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
int indexCount = 6;
err = glGetError();
assert(err==GL_NO_ERROR);
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
err = glGetError();
assert(err==GL_NO_ERROR);
*/
// glutSwapBuffers();
}
void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_glyph* glyph, int textureWidth, int textureHeight)
{
assert(glGetError() == GL_NO_ERROR);
if (glyph)
{
// Update texture (entire texture, could use glyph to update partial texture using glTexSubImage2D)
GLuint* gltexture = (GLuint*)texture->m_userData;
glBindTexture(GL_TEXTURE_2D, *gltexture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
assert(glGetError() == GL_NO_ERROR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, textureWidth, textureHeight, 0, GL_RED, GL_UNSIGNED_BYTE, texture->m_texels);
assert(glGetError() == GL_NO_ERROR);
}
else
{
if (textureWidth && textureHeight)
{
GLuint* texId = new GLuint;
texture->m_userData = texId;
//create new texture
glGenTextures(1, texId);
assert(glGetError() == GL_NO_ERROR);
glBindTexture(GL_TEXTURE_2D, *texId);
texture->m_texels = (unsigned char*)malloc(textureWidth * textureHeight);
memset(texture->m_texels, 0, textureWidth * textureHeight);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, textureWidth, textureHeight, 0, GL_RED, GL_UNSIGNED_BYTE, texture->m_texels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
assert(glGetError() == GL_NO_ERROR);
////////////////////////////
//create the other data
{
glGenVertexArrays(1, &s_vertexArrayObject);
glBindVertexArray(s_vertexArrayObject);
glGenBuffers(1, &s_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, s_vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, VERT_COUNT * sizeof(Vertex), texture->newverts, GL_DYNAMIC_DRAW);
assert(glGetError() == GL_NO_ERROR);
for (int i = 0; i < INDEX_COUNT; i++)
{
s_indexData[i] = i;
}
glGenBuffers(1, &s_indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s_indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, INDEX_COUNT * sizeof(int), s_indexData, GL_STATIC_DRAW);
assert(glGetError() == GL_NO_ERROR);
}
}
else
{
//delete texture
if (texture->m_userData)
{
GLuint* id = (GLuint*)texture->m_userData;
glDeleteTextures(1, id);
//delete id;
delete id; //texture->m_userData;
texture->m_userData = 0;
}
}
}
}
void InternalOpenGL2RenderCallbacks::render(sth_texture* texture)
{
display2();
GLuint* texId = (GLuint*)texture->m_userData;
assert(glGetError() == GL_NO_ERROR);
glActiveTexture(GL_TEXTURE0);
assert(glGetError() == GL_NO_ERROR);
glBindTexture(GL_TEXTURE_2D, *texId);
bool useFiltering = false;
if (useFiltering)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
assert(glGetError() == GL_NO_ERROR);
glBindBuffer(GL_ARRAY_BUFFER, s_vertexBuffer);
glBindVertexArray(s_vertexArrayObject);
glBufferData(GL_ARRAY_BUFFER, texture->nverts * sizeof(Vertex), &texture->newverts[0].position.p[0], GL_DYNAMIC_DRAW);
assert(glGetError() == GL_NO_ERROR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s_indexBuffer);
//glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
int indexCount = texture->nverts;
assert(glGetError() == GL_NO_ERROR);
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
assert(glGetError() == GL_NO_ERROR);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
// glDisableVertexAttribArray(m_textureAttribute);
glUseProgram(0);
}
void dumpTextureToPng(int textureWidth, int textureHeight, const char* fileName)
{
glPixelStorei(GL_PACK_ALIGNMENT, 1);
unsigned char* pixels = (unsigned char*)malloc(textureWidth * textureHeight);
glReadPixels(0, 0, textureWidth, textureHeight, GL_RED, GL_UNSIGNED_BYTE, pixels);
//swap the pixels
unsigned char* tmp = (unsigned char*)malloc(textureWidth);
for (int j = 0; j < textureHeight; j++)
{
pixels[j * textureWidth + j] = 255;
}
if (0)
{
for (int j = 0; j < textureHeight / 2; j++)
{
for (int i = 0; i < textureWidth; i++)
{
tmp[i] = pixels[j * textureWidth + i];
pixels[j * textureWidth + i] = pixels[(textureHeight - j - 1) * textureWidth + i];
pixels[(textureHeight - j - 1) * textureWidth + i] = tmp[i];
}
}
}
int comp = 1; //1=Y
stbi_write_png(fileName, textureWidth, textureHeight, comp, pixels, textureWidth);
free(pixels);
}
#endif

View file

@ -0,0 +1,51 @@
#ifndef _OPENGL_FONTSTASH_CALLBACKS_H
#define _OPENGL_FONTSTASH_CALLBACKS_H
#include "fontstash.h"
struct PrimInternalData;
class GLPrimitiveRenderer;
struct InternalOpenGL2RenderCallbacks : public RenderCallbacks
{
virtual PrimInternalData* getData() = 0;
virtual ~InternalOpenGL2RenderCallbacks();
virtual void updateTexture(sth_texture* texture, sth_glyph* glyph, int textureWidth, int textureHeight);
virtual void render(sth_texture* texture);
void display2();
};
void dumpTextureToPng(int screenWidth, int screenHeight, const char* fileName);
struct SimpleOpenGL2RenderCallbacks : public InternalOpenGL2RenderCallbacks
{
PrimInternalData* m_data;
virtual PrimInternalData* getData()
{
return m_data;
}
SimpleOpenGL2RenderCallbacks(PrimInternalData* data)
: m_data(data)
{
}
virtual ~SimpleOpenGL2RenderCallbacks()
{
}
};
struct OpenGL2RenderCallbacks : public InternalOpenGL2RenderCallbacks
{
GLPrimitiveRenderer* m_primRender2;
virtual PrimInternalData* getData();
virtual void setWorldPosition(float pos[3]) {}
virtual void setWorldOrientation(float orn[4]) {}
virtual void setColorRGBA(float color[4]) {}
OpenGL2RenderCallbacks(GLPrimitiveRenderer* primRender);
virtual ~OpenGL2RenderCallbacks();
};
#endif //_OPENGL_FONTSTASH_CALLBACKS_H

View file

@ -0,0 +1,64 @@
project "OpenGL_Window"
language "C++"
kind "StaticLib"
initOpenGL()
initGlew()
includedirs {
"../ThirdPartyLibs",
"../../src",
}
if os.is("Linux") then
buildoptions{"-fPIC"}
end
--links {
--}
files {
"*.cpp",
"*.h",
"OpenGLWindow/*.c",
"OpenGLWindow/*.h",
"OpenGLWindow/GL/*.h",
"../ThirdPartyLibs/stb_image/stb_image_write.cpp",
}
if not os.is("Windows") then
excludes {
"Win32OpenGLWindow.cpp",
"Win32OpenGLWindow.h",
"Win32Window.cpp",
"Win32Window.h",
}
end
if os.is("Linux") then
initX11()
end
if not os.is("Linux") then
excludes {
"X11OpenGLWindow.cpp",
"X11OpenGLWindows.h"
}
end
if not os.is("MacoSX") then
excludes {
"MacOpenGLWindow.cpp"
}
end
if os.is("MacOSX") then
files
{
"MacOpenGLWindow.h",
"MacOpenGLWindow.cpp",
"MacOpenGLWindowObjC.m",
"MacOpenGLWindowObjC.h",
}
end