update bullet so it actually works

Moved the addSourceDirectory for physics/Bullet into the Engine/Source/CMakeLists.txt file that way it can actually appear where we expect it to in the solution explorer.
This commit is contained in:
marauder2k7 2026-06-03 15:08:51 +01:00
parent c7be48130a
commit 13fa178cf6
5986 changed files with 1811270 additions and 453803 deletions

View file

@ -1,12 +1,15 @@
INCLUDE_DIRECTORIES(
..
../ThirdPartyLibs
../../src
../ThirdPartyLibs/glad
)
FILE(GLOB OpenGLWindow_HDRS "*.h" )
FILE(GLOB OpenGLWindowMac_CPP "Mac*.mm")
FILE(GLOB OpenGLWindowMac_CPP "Mac*.cpp")
FILE(GLOB OpenGLWindowMacObjC_CPP "Mac*.m")
FILE(GLOB OpenGLWindowWin32_CPP "Win32*.cpp")
FILE(GLOB OpenGLWindowLinux_CPP "X11*.cpp")
@ -16,38 +19,44 @@ 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/Glew/glew.c ${OpenGLWindowWin32_CPP} ${OpenGLWindowCommon_CPP})
SET(OpenGLWindow_SRCS ${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/glad/gl.c ${OpenGLWindowWin32_CPP} ${OpenGLWindowCommon_CPP})
INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/Glew
${BULLET_PHYSICS_SOURCE_DIR}/examples/ThirdPartyLibs/glad
)
ADD_DEFINITIONS(-DGLEW_STATIC)
ENDIF(WIN32)
IF (APPLE)
SET(OpenGLWindow_SRCS ${OpenGLWindowMac_CPP} ${OpenGLWindowCommon_CPP} )
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/Glew
${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/Glew/glew.c ${OpenGLWindowCommon_CPP} )
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 )
target_link_libraries(OpenGLWindow ${DL})
elseif (APPLE)
target_link_libraries(OpenGLWindow ${COCOA_LIBRARY})
endif ()
@ -59,8 +68,13 @@ if (BUILD_SHARED_LIBS)
else()
set (CMAKE_THREAD_PREFER_PTHREAD TRUE)
FIND_PACKAGE(Threads)
target_link_libraries(OpenGLWindow dl ${CMAKE_THREAD_LIBS_INIT})
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,399 @@
// 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);
}
EGLint egl_context_attribs[] = {
EGL_CONTEXT_MAJOR_VERSION,
3,
EGL_CONTEXT_MINOR_VERSION,
3,
EGL_CONTEXT_OPENGL_PROFILE_MASK,
EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE,
EGL_TRUE,
EGL_NONE,
};
m_data->egl_context = eglCreateContext(
m_data->egl_display, m_data->egl_config, EGL_NO_CONTEXT, egl_context_attribs);
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

@ -11,25 +11,23 @@ struct GLInstanceVertex
};
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;
}
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
#endif //GL_INSTANCE_GRAPHICS_SHAPE_H

View file

@ -6,18 +6,16 @@
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;
int m_vboSize;
GLuint m_vbo;
int m_totalNumInstances;
int m_maxNumObjectCapacity;
int m_maxShapeCapacityInBytes;
};
#endif //GL_INSTANCE_RENDERER_INTERNAL_DATA_H
#endif //GL_INSTANCE_RENDERER_INTERNAL_DATA_H

View file

@ -20,16 +20,10 @@ subject to the following restrictions:
#include "../CommonInterfaces/CommonRenderInterface.h"
#include "SimpleCamera.h"
class GLInstancingRenderer : public CommonRenderInterface
{
b3AlignedObjectArray<struct b3GraphicsInstance*> m_graphicsInstances;
struct InternalDataRenderer* m_data;
bool m_textureenabled;
@ -37,36 +31,39 @@ class GLInstancingRenderer : public CommonRenderInterface
int m_screenWidth;
int m_screenHeight;
int m_upAxis;
bool m_enableBlend;
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);
GLInstancingRenderer(int m_maxObjectCapacity, int maxShapeCapacityInBytes = 56 * 1024 * 1024);
virtual ~GLInstancingRenderer();
virtual void init();
virtual void renderScene();
virtual void renderSceneInternal(int renderMode=B3_DEFAULT_RENDERMODE);
virtual void renderSceneInternal(int orgRenderMode = B3_DEFAULT_RENDERMODE);
void InitShaders();
void CleanupShaders();
virtual void removeAllInstances();
virtual void updateShape(int shapeIndex, const float* vertices);
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);
virtual void updateTexture(int textureIndex, const unsigned char* texels);
virtual void activateTexture(int textureIndex);
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);
@ -74,52 +71,65 @@ public:
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);
}
{
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(float* color, int srcIndex);
virtual void writeSingleInstanceColorToCPU(double* color, 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 writeSingleInstanceScaleToCPU(float* scale, int srcIndex);
virtual void writeSingleInstanceScaleToCPU(double* scale, int srcIndex);
virtual void writeSingleInstanceSpecularColorToCPU(const double* specular, int srcIndex2);
virtual void writeSingleInstanceSpecularColorToCPU(const float* specular, int srcIndex2);
virtual struct GLInstanceRendererInternalData* getInternalData();
virtual void writeSingleInstanceScaleToCPU(const float* scale, int srcIndex);
virtual void writeSingleInstanceScaleToCPU(const double* scale, int srcIndex);
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 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 updateCamera(int upAxis=1);
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 resize(int width, int height);
virtual int getScreenWidth()
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;
}
@ -129,19 +139,18 @@ public:
}
virtual int getMaxShapeCapacity() const;
virtual int getInstanceCapacity() const;
virtual int getTotalNumInstances() const;
virtual void enableShadowMap();
virtual void enableBlend(bool blend)
{
m_enableBlend = blend;
}
virtual void setPlaneReflectionShapeIndex(int index);
virtual void clearZBuffer();
virtual void setRenderFrameBuffer(unsigned int renderFrameBuffer);
};
#endif //GL_INSTANCING_RENDERER_H
#endif //GL_INSTANCING_RENDERER_H

View file

@ -8,14 +8,19 @@ 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_vertexArrayObject;
GLuint m_indexBuffer;
GLuint m_texturehandle;
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
#endif //PRIM_INTERNAL_DATA

View file

@ -1,325 +1,487 @@
#ifndef NO_OPENGL3
#include "GLPrimitiveRenderer.h"
#include "GLPrimInternalData.h"
//#include "Bullet3Common/b3Logging.h"
#include "Bullet3Common/b3Scalar.h"
#include "LoadShader.h"
#include <assert.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* 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};
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_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) {
assert(0);
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) {
assert(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) {
assert(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) {
assert(0);
}
if (m_data->m_colourAttribute < 0)
{
b3Assert(0);
}
m_data->m_positionAttribute = glGetAttribLocation(m_data->m_shaderProg, "position");
if (m_data->m_positionAttribute < 0) {
assert(0);
}
m_data->m_textureAttribute = glGetAttribLocation(m_data->m_shaderProg,"texuv");
if (m_data->m_textureAttribute < 0) {
assert(0);
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();
loadBufferData();
}
void GLPrimitiveRenderer::loadBufferData()
{
PrimVertex vertexData[4] = {
{ PrimVec4(-1, -1, 0.0, 1.0 ), PrimVec4( 1.0, 0.0, 0.0, 1.0 ) ,PrimVec2(0,0)},
{ PrimVec4(-1, 1, 0.0, 1.0 ), PrimVec4( 0.0, 1.0, 0.0, 1.0 ) ,PrimVec2(0,1)},
{ PrimVec4( 1, 1, 0.0, 1.0 ), PrimVec4( 0.0, 0.0, 1.0, 1.0 ) ,PrimVec2(1,1)},
{ 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);
assert(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);
glEnableVertexAttribArray(m_data->m_positionAttribute);
glEnableVertexAttribArray(m_data->m_colourAttribute);
assert(glGetError()==GL_NO_ERROR);
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)));
assert(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);
assert(glGetError()==GL_NO_ERROR);
delete[] image;
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);
glBindTexture(GL_TEXTURE_2D, 0);
glUseProgram(0);
glBindTexture(GL_TEXTURE_2D,0);
glDeleteProgram(m_data->m_shaderProg);
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])
{
assert(glGetError()==GL_NO_ERROR);
b3Assert(glGetError() == GL_NO_ERROR);
glActiveTexture(GL_TEXTURE0);
assert(glGetError()==GL_NO_ERROR);
glBindTexture(GL_TEXTURE_2D,m_data->m_texturehandle);
assert(glGetError()==GL_NO_ERROR);
drawTexturedRect(x0,y0,x1,y1,color,0,0,1,1);
assert(glGetError()==GL_NO_ERROR);
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)
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");
assert(glGetError()==GL_NO_ERROR);
glUseProgram(m_data->m_shaderProg);
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);
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ARRAY_BUFFER, m_data->m_vertexBuffer);
glBindVertexArray(m_data->m_vertexArrayObject);
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
}
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);
PrimVertex vertexData[4] = {
v0, v1, v2, v3};
glBufferSubData(GL_ARRAY_BUFFER, 0, 4 * sizeof(PrimVertex), vertexData);
b3Assert(glGetError() == GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
PrimVec2 p( 0.f,0.f);//?b?0.5f * sinf(timeValue), 0.5f * cosf(timeValue) );
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);
glUniform2fv(m_data->m_positionUniform, 1, (const GLfloat *)&p);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_positionAttribute);
assert(glGetError()==GL_NO_ERROR);
glEnableVertexAttribArray(m_data->m_colourAttribute);
assert(glGetError()==GL_NO_ERROR);
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)));
assert(glGetError()==GL_NO_ERROR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_data->m_indexBuffer);
//glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
int indexCount = 6;
assert(glGetError()==GL_NO_ERROR);
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
assert(glGetError()==GL_NO_ERROR);
glBindVertexArray(0);
assert(glGetError()==GL_NO_ERROR);
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);
assert(glGetError()==GL_NO_ERROR);
b3Assert(glGetError() == GL_NO_ERROR);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
assert(glGetError()==GL_NO_ERROR);
b3Assert(glGetError() == GL_NO_ERROR);
//glDisableVertexAttribArray(m_data->m_textureAttribute);
assert(glGetError()==GL_NO_ERROR);
b3Assert(glGetError() == GL_NO_ERROR);
glUseProgram(0);
assert(glGetError()==GL_NO_ERROR);
b3Assert(glGetError() == GL_NO_ERROR);
}
void GLPrimitiveRenderer::drawTexturedRect(float x0, float y0, float x1, float y1, float color[4], float u0,float v0, float u1, float v1, int useRGBA)
void GLPrimitiveRenderer::drawTexturedRect3D2Text(bool useRGBA)
{
float identity[16]={1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1};
PrimVertex vertexData[4] = {
{ 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)},
{ 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)},
{ 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)},
{ 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);
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

@ -5,6 +5,9 @@
struct PrimVec2
{
PrimVec2()
{
}
PrimVec2(float x, float y)
{
p[0] = x;
@ -16,52 +19,64 @@ struct PrimVec2
struct PrimVec4
{
PrimVec4() {}
PrimVec4(float x,float y, float z, float w)
PrimVec4(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
struct PrimVertex
{
PrimVec4 position;
PrimVec4 colour;
PrimVec2 uv;
} 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;
int m_screenWidth;
int m_screenHeight;
struct PrimInternalData* m_data;
struct PrimInternalData2* m_data2;
void loadBufferData();
struct PrimInternalData* m_data;
void loadBufferData();
public:
GLPrimitiveRenderer(int screenWidth, int screenHeight);
virtual ~GLPrimitiveRenderer();
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);
PrimInternalData* getData()
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
#endif //_GL_PRIMITIVE_RENDERER_H

View file

@ -2,28 +2,26 @@
///See http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-14-render-to-texture/
#include "GLRenderToTexture.h"
#include "Bullet3Common/b3Scalar.h" // for b3Assert
#include "Bullet3Common/b3Scalar.h" // for b3Assert
#include <string.h>
#include <stdio.h>
bool gIntelLinuxglDrawBufferWorkaround=false;
bool gIntelLinuxglDrawBufferWorkaround = false;
GLRenderToTexture::GLRenderToTexture()
:m_framebufferName(0)
: 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__)
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)
@ -33,18 +31,16 @@ void GLRenderToTexture::init(int width, int height, GLuint textureId, int render
glGenFramebuffers(1, &m_framebufferName);
glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferName);
// The depth buffer
// glGenRenderbuffers(1, &m_depthrenderbuffer);
// 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);
// 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)
switch (m_renderTextureType)
{
case RENDERTEXTURE_COLOR:
case RENDERTEXTURE_COLOR:
{
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureId, 0);
break;
@ -55,15 +51,12 @@ void GLRenderToTexture::init(int width, int height, GLuint textureId, int render
break;
}
default:
{
{
b3Assert(0);
}
}
};
glBindFramebuffer( GL_FRAMEBUFFER, 0 );
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
bool GLRenderToTexture::enable()
@ -72,13 +65,12 @@ bool GLRenderToTexture::enable()
glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferName);
switch (m_renderTextureType)
{
case RENDERTEXTURE_COLOR:
case RENDERTEXTURE_COLOR:
{
// Set the list of draw buffers.
GLenum drawBuffers[2] = {GL_COLOR_ATTACHMENT0,0};
GLenum drawBuffers[2] = {GL_COLOR_ATTACHMENT0, 0};
glDrawBuffers(1, drawBuffers);
break;
}
@ -87,51 +79,47 @@ bool GLRenderToTexture::enable()
//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
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)
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
{
status = true;
}
return status;
}
void GLRenderToTexture::disable()
{
glBindFramebuffer( GL_FRAMEBUFFER, 0 );
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
GLRenderToTexture::~GLRenderToTexture()
{
glBindFramebuffer( GL_FRAMEBUFFER, 0 );
glBindFramebuffer(GL_FRAMEBUFFER, 0);
if (m_depthrenderbuffer)
{
glDeleteRenderbuffers(1,&m_depthrenderbuffer);
glDeleteRenderbuffers(1, &m_depthrenderbuffer);
}
if( m_framebufferName)
if (m_framebufferName)
{
glDeleteFramebuffers(1, &m_framebufferName);
}
}
#endif

View file

@ -5,28 +5,26 @@
///See http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-14-render-to-texture/
#include "OpenGLInclude.h"
enum
enum
{
RENDERTEXTURE_COLOR=1,
RENDERTEXTURE_COLOR = 1,
RENDERTEXTURE_DEPTH,
};
struct GLRenderToTexture
{
GLuint m_framebufferName;
GLuint m_depthrenderbuffer;
bool m_initialized;
int m_renderTextureType;
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();
void init(int width, int height, GLuint textureId, int renderTextureType = RENDERTEXTURE_COLOR);
bool enable();
void disable();
virtual ~GLRenderToTexture();
};
#endif //GL_RENDER_TO_TEXTURE_H
#endif //GL_RENDER_TO_TEXTURE_H

View file

@ -12,43 +12,42 @@ struct sth_stash;
#include "Gwen/Texture.h"
#include "TwFonts.h"
static float extraSpacing = 0.;//6f;
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)
inline void MyClamp(T& a, const T& lb, const T& ub)
{
if (a < lb)
if (a < lb)
{
a = lb;
a = lb;
}
else if (ub < a)
else if (ub < a)
{
a = ub;
}
}
static GLuint BindFont(const CTexFont *_Font)
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);
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;
return TexID;
}
struct MyTextureLoader
@ -56,8 +55,8 @@ struct MyTextureLoader
virtual ~MyTextureLoader()
{
}
virtual void LoadTexture( Gwen::Texture* pTexture ) = 0;
virtual void FreeTexture( Gwen::Texture* pTexture )=0;
virtual void LoadTexture(Gwen::Texture* pTexture) = 0;
virtual void FreeTexture(Gwen::Texture* pTexture) = 0;
};
class GwenOpenGL3CoreRenderer : public Gwen::Renderer::Base
@ -65,28 +64,29 @@ 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;
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;
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)
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)
if (retinaScale == 2.0f)
{
m_useTrueTypeFont = true;
}
@ -94,9 +94,9 @@ public:
m_currentColor[1] = 1;
m_currentColor[2] = 1;
m_currentColor[3] = 1;
m_fontScaling = 16.f*m_retinaScale;
m_fontScaling = 16.f * m_retinaScale;
TwGenerateDefaultFonts();
m_currentFont = g_DefaultNormalFont;
@ -104,7 +104,6 @@ public:
//m_currentFont = g_DefaultLargeFont;
m_fontTextureId = BindFont(m_currentFont);
}
virtual ~GwenOpenGL3CoreRenderer()
@ -116,47 +115,41 @@ public:
m_screenWidth = width;
m_screenHeight = height;
}
virtual void Begin()
{
m_yOffset=0;
m_yOffset = 0;
glEnable(GL_BLEND);
assert(glGetError()==GL_NO_ERROR);
assert(glGetError() == GL_NO_ERROR);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
assert(glGetError()==GL_NO_ERROR);
assert(glGetError()==GL_NO_ERROR);
assert(glGetError() == GL_NO_ERROR);
assert(glGetError() == GL_NO_ERROR);
glDisable(GL_DEPTH_TEST);
assert(glGetError()==GL_NO_ERROR);
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);
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);
assert(glGetError() == GL_NO_ERROR);
glEnable(GL_BLEND);
assert(glGetError()==GL_NO_ERROR);
assert(glGetError() == GL_NO_ERROR);
}
virtual void End()
{
glDisable(GL_BLEND);
}
virtual void StartClip()
@ -169,196 +162,189 @@ public:
// 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);
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 );
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 );
glDisable(GL_SCISSOR_TEST);
};
virtual void SetDrawColor( Gwen::Color color )
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;
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 )
virtual void DrawFilledRect(Gwen::Rect rect)
{
Translate( 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_yOffset+=rect.h+10;
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 )
{
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;
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)
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
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;
int pos = 0;
//float color[]={0.2f,0.2,0.2f,1.f};
glBindTexture(GL_TEXTURE_2D,m_fontTextureId);
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;
r.w = m_currentFont->m_CharWidth[c] + extraSpacing;
Gwen::Rect rect = r;
Translate( rect );
Translate(rect);
m_primitiveRenderer->drawTexturedRect(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]);
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]);
//DrawTexturedRect(0,r,m_currentFont->m_CharU0[c],m_currentFont->m_CharV0[c],m_currentFont->m_CharU1[c],m_currentFont->m_CharV1[c]);
// DrawFilledRect(r);
width += r.w;
r.x = width;
pos++;
}
glBindTexture(GL_TEXTURE_2D,0);
{
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();
}
Gwen::Point MeasureText( Gwen::Font* pFont, const Gwen::UnicodeString& text )
{
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;
// 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);
1, m_fontScaling,
xpos, ypos,
unicodeText, &dx, m_screenWidth, m_screenHeight, measureOnly);
Gwen::Point pt;
if (m_retinaScale==2.0f)
if (m_retinaScale == 2.0f)
{
pt.x = dx*Scale()/2.f;
pt.y = m_fontScaling/2*Scale()+1;
pt.x = dx * Scale() / 2.f;
pt.y = m_fontScaling / 2 * Scale() + 1;
}
else
{
pt.x = dx*Scale();
pt.y = m_fontScaling*Scale()+1;
pt.x = dx * Scale();
pt.y = m_fontScaling * Scale() + 1;
}
return pt;
}
else
{
float width = 0.f;
int pos=0;
int pos = 0;
while (unicodeText[pos])
{
width += m_currentFont->m_CharWidth[(int)unicodeText[pos]]+extraSpacing;
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();
pt.x = width * Scale();
pt.y = (fontHeight + 2) * Scale();
return pt;
}
return Gwen::Renderer::Base::MeasureText(pFont,text);
}
return Gwen::Renderer::Base::MeasureText(pFont, text);
}
virtual void LoadTexture( Gwen::Texture* pTexture )
virtual void LoadTexture(Gwen::Texture* pTexture)
{
if (m_textureLoader)
m_textureLoader->LoadTexture(pTexture);
}
virtual void FreeTexture( Gwen::Texture* 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 )
{
Translate( rect );
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;
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;
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);
@ -370,24 +356,17 @@ public:
}
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);
//glEnable(GL_TEXTURE_2D);
assert(glGetError()==GL_NO_ERROR);
// 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
#endif //__GWEN_OPENGL3_CORE_RENDERER_H

View file

@ -4,7 +4,6 @@
#include <stdio.h>
#include <stdlib.h>
// Load the shader from the source text
void gltLoadShaderSrc(const char *szShaderSrc, GLuint shader)
{
@ -14,11 +13,9 @@ void gltLoadShaderSrc(const char *szShaderSrc, GLuint shader)
glShaderSource(shader, 1, (const GLchar **)fsStringPtr, NULL);
}
GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg)
{
assert(glGetError()==GL_NO_ERROR);
assert(glGetError() == GL_NO_ERROR);
// Temporary Shader objects
GLuint hVertexShader;
@ -35,46 +32,43 @@ GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg)
// Compile them
glCompileShader(hVertexShader);
assert(glGetError()==GL_NO_ERROR);
assert(glGetError() == GL_NO_ERROR);
glGetShaderiv(hVertexShader, GL_COMPILE_STATUS, &testVal);
if(testVal == GL_FALSE)
if (testVal == GL_FALSE)
{
char temp[256] = "";
glGetShaderInfoLog( hVertexShader, 256, NULL, temp);
fprintf( stderr, "Compile failed:\n%s\n", temp);
assert(0);
return 0;
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)NULL;
return (GLuint)0;
}
assert(glGetError()==GL_NO_ERROR);
assert(glGetError() == GL_NO_ERROR);
glCompileShader(hFragmentShader);
assert(glGetError()==GL_NO_ERROR);
glCompileShader(hFragmentShader);
assert(glGetError() == GL_NO_ERROR);
glGetShaderiv(hFragmentShader, GL_COMPILE_STATUS, &testVal);
if(testVal == GL_FALSE)
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(0);
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)NULL;
return (GLuint)0;
}
assert(glGetError()==GL_NO_ERROR);
assert(glGetError() == GL_NO_ERROR);
// Check for errors
// Link them - assuming it works...
hReturn = glCreateProgram();
glAttachShader(hReturn, hVertexShader);
@ -88,24 +82,22 @@ GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg)
// Make sure link worked too
glGetProgramiv(hReturn, GL_LINK_STATUS, &testVal);
if(testVal == GL_FALSE)
if (testVal == GL_FALSE)
{
GLsizei maxLen = 4096;
GLchar infoLog[4096];
GLsizei actualLen;
glGetProgramInfoLog( hReturn,
maxLen,
&actualLen,
infoLog);
glGetProgramInfoLog(hReturn,
maxLen,
&actualLen,
infoLog);
printf("Warning/Error in GLSL shader:\n");
printf("%s\n",infoLog);
printf("%s\n", infoLog);
glDeleteProgram(hReturn);
return (GLuint)NULL;
return (GLuint)0;
}
return hReturn;
}

View file

@ -4,15 +4,14 @@
#include "OpenGLInclude.h"
#ifdef __cplusplus
extern "C" {
#endif//__cplusplus
extern "C"
{
#endif //__cplusplus
GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg);
GLuint gltLoadShaderPair(const char *szVertexProg, const char *szFragmentProg);
#ifdef __cplusplus
}
#endif//__cplusplus
#endif//_LOAD_SHADER_H
#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

@ -7,112 +7,66 @@
class MacOpenGLWindow : public CommonWindowInterface
{
struct MacOpenGLWindowInternalData* m_internalData;
float m_mouseX;
float m_mouseY;
int m_modifierFlags;
b3MouseButtonCallback m_mouseButtonCallback;
b3MouseMoveCallback m_mouseMoveCallback;
b3WheelCallback m_wheelCallback;
b3KeyboardCallback m_keyboardCallback;
b3RenderCallback m_renderCallback;
float m_retinaScaleFactor;
bool m_allowRetina;
struct MacOpenGLWindowInternalData* m_internalData;
public:
MacOpenGLWindow();
virtual ~MacOpenGLWindow();
void init(int width, int height, const char* windowTitle);
MacOpenGLWindow();
virtual ~MacOpenGLWindow();
void closeWindow();
void startRendering();
void endRendering();//swap buffers
virtual bool requestedExit() const;
void init(int width, int height, const char* windowTitle);
virtual void setRequestExit();
void getMouseCoordinates(int& x, int& y);
void runMainLoop();
void closeWindow();
virtual bool isModifierKeyPressed(int key);
void setMouseButtonCallback(b3MouseButtonCallback mouseCallback)
{
m_mouseButtonCallback = mouseCallback;
}
void startRendering();
void setMouseMoveCallback(b3MouseMoveCallback mouseCallback)
{
m_mouseMoveCallback = mouseCallback;
}
void setResizeCallback(b3ResizeCallback resizeCallback);
void setKeyboardCallback( b3KeyboardCallback keyboardCallback)
{
m_keyboardCallback = keyboardCallback;
}
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 b3MouseMoveCallback getMouseMoveCallback()
{
return m_mouseMoveCallback;
}
virtual b3MouseButtonCallback getMouseButtonCallback()
{
return m_mouseButtonCallback;
}
virtual b3ResizeCallback getResizeCallback();
virtual b3WheelCallback getWheelCallback()
{
return m_wheelCallback;
}
virtual b3WheelCallback getWheelCallback();
b3KeyboardCallback getKeyboardCallback()
{
return m_keyboardCallback;
}
void setWheelCallback (b3WheelCallback wheelCallback)
{
m_wheelCallback = wheelCallback;
}
b3KeyboardCallback getKeyboardCallback();
float getRetinaScale() const
{
return m_retinaScaleFactor;
}
virtual void setAllowRetina(bool allow)
{
m_allowRetina = allow;
}
virtual void createWindow(const b3gWindowConstructionInfo& ci);
virtual float getTimeInSeconds();
void setWheelCallback(b3WheelCallback wheelCallback);
virtual int getWidth() const;
virtual int getHeight() const;
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 setRenderCallback( b3RenderCallback renderCallback);
virtual void setWindowTitle(const char* title);
int fileOpenDialog(char* filename, int maxNameLength);
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

View file

@ -13,32 +13,22 @@ subject to the following restrictions:
*/
//Originally written by Erwin Coumans
#ifndef __OPENGL_INCLUDE_H
#define __OPENGL_INCLUDE_H
//think different
#if defined(__APPLE__) && !defined (VMDMESA)
#include <OpenGL/OpenGL.h>
#include <OpenGL/gl.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 GLEW_STATIC
#include "CustomGL/glew.h"
#ifdef B3_USE_GLFW
#include "glad/gl.h"
#include <GLFW/glfw3.h>
#else
#include <GL/glew.h>
#endif//GLEW_STATIC
#ifdef _WINDOWS
#include <windows.h>
//#include <GL/gl.h>
//#include <GL/glu.h>
#else
//#include <GL/gl.h>
//#include <GL/glu.h>
#endif //_WINDOWS
#endif //APPLE
#include "glad/gl.h"
#endif //B3_USE_GLFW
#endif //BT_NO_GLAD
//disable glGetError
//#undef glGetError
@ -55,5 +45,4 @@ subject to the following restrictions:
//
//#endif //__linux
#endif //__OPENGL_INCLUDE_H
#endif //__OPENGL_INCLUDE_H

View file

@ -13,54 +13,19 @@ subject to the following restrictions:
*/
//Originally written by Erwin Coumans
#ifndef __OPENGL_INCLUDE_H
#define __OPENGL_INCLUDE_H
//think different
#if defined(__APPLE__) && !defined (VMDMESA)
#include <OpenGL/OpenGL.h>
//#include <OpenGL/gl.h>
//#include <OpenGL/glu.h>
//#import <Cocoa/Cocoa.h>
#if defined (USE_OPENGL2) || defined (NO_OPENGL3)
#include <OpenGL/gl.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
#include <OpenGL/gl3.h>
#endif
#ifdef B3_USE_GLFW
#include <glad/gl.h>
#include <GLFW/glfw3.h>
#else
#ifdef GLEW_STATIC
#include "CustomGL/glew.h"
#else
#include <GL/glew.h>
#endif //GLEW_STATIC
#ifdef _WINDOWS
#include <windows.h>
//#include <GL/gl.h>
//#include <GL/glu.h>
#else
//#include <GL/gl.h>
//#include <GL/glu.h>
#endif //_WINDOWS
#endif //APPLE
//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
#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

View file

@ -8,7 +8,7 @@ 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 vec3 instance_scale;
layout (location = 6) in vec4 instance_scale_obUid;
uniform mat4 depthMVP;
@ -48,7 +48,7 @@ vec4 quatRotate ( in vec4 p, in vec4 q )
void main(void)
{
vec4 q = instance_quaternion;
vec4 localcoord = quatRotate3( position.xyz*instance_scale,q);
vec4 localcoord = quatRotate3( position.xyz*instance_scale_obUid.xyz,q);
vec4 vertexPos = depthMVP * vec4( (instance_position+localcoord).xyz,1);
gl_Position = vertexPos;
}

View file

@ -8,7 +8,7 @@ static const char* createShadowMapInstancingVertexShader= \
"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 vec3 instance_scale;\n"
"layout (location = 6) in vec4 instance_scale_obUid;\n"
"uniform mat4 depthMVP;\n"
"vec4 quatMul ( in vec4 q1, in vec4 q2 )\n"
"{\n"
@ -41,7 +41,7 @@ static const char* createShadowMapInstancingVertexShader= \
"void main(void)\n"
"{\n"
" vec4 q = instance_quaternion;\n"
" vec4 localcoord = quatRotate3( position.xyz*instance_scale,q);\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

@ -8,7 +8,7 @@ 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 vec3 instance_scale;
layout (location = 6) in vec4 instance_scale_obUid;
uniform mat4 ModelViewMatrix;
@ -68,7 +68,7 @@ void main(void)
lightDir = lightDirIn;
vec4 localcoord = quatRotate3( position.xyz*instance_scale,q);
vec4 localcoord = quatRotate3( position.xyz*instance_scale_obUid.xyz,q);
vec4 vertexPos = ProjectionMatrix * ModelViewMatrix *(instance_position+localcoord);
gl_Position = vertexPos;

View file

@ -8,7 +8,7 @@ static const char* instancingVertexShader= \
"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 vec3 instance_scale;\n"
"layout (location = 6) in vec4 instance_scale_obUid;\n"
"uniform mat4 ModelViewMatrix;\n"
"uniform mat4 ProjectionMatrix;\n"
"uniform vec3 lightDirIn;\n"
@ -59,7 +59,7 @@ static const char* instancingVertexShader= \
" \n"
" lightDir = lightDirIn;\n"
" \n"
" vec4 localcoord = quatRotate3( position.xyz*instance_scale,q);\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"

View file

@ -11,7 +11,7 @@ out vec4 colourV;
void main (void)
{
colourV = colour;
colourV = colour;
gl_Position = ProjectionMatrix * ModelViewMatrix * position;
}

View file

@ -8,7 +8,7 @@ static const char* linesVertexShader= \
"out vec4 colourV;\n"
"void main (void)\n"
"{\n"
" colourV = colour;\n"
" colourV = colour;\n"
" gl_Position = ProjectionMatrix * ModelViewMatrix * position;\n"
" \n"
"}\n"

View file

@ -8,7 +8,7 @@ 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 vec3 instance_scale;
layout (location = 6) in vec4 instance_scale_obUid;
uniform float screenWidth = 700.f;
@ -38,7 +38,7 @@ void main(void)
vec3 posEye = vec3(ModelViewMatrix * vec4(instance_position.xyz, 1.0));
float dist = length(posEye);
float pointRadius = 1.f;
gl_PointSize = instance_scale.x * pointRadius * (screenWidth / dist);
gl_PointSize = instance_scale_obUid.x * pointRadius * (screenWidth / dist);
gl_Position = vertexPos;

View file

@ -7,7 +7,7 @@ static const char* pointSpriteVertexShader= \
"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 vec3 instance_scale;\n"
"layout (location = 6) in vec4 instance_scale_obUid;\n"
"uniform float screenWidth = 700.f;\n"
"uniform mat4 ModelViewMatrix;\n"
"uniform mat4 ProjectionMatrix;\n"
@ -29,7 +29,7 @@ static const char* pointSpriteVertexShader= \
" 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.x * pointRadius * (screenWidth / dist);\n"
" gl_PointSize = instance_scale_obUid.x * pointRadius * (screenWidth / dist);\n"
" gl_Position = vertexPos;\n"
" \n"
" fragment.color = instance_color;\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

@ -13,9 +13,15 @@ in Vert
uniform sampler2D Diffuse;
uniform sampler2DShadow shadowMap;
uniform mat4 ViewMatrixInverse;
in vec3 lightDir,normal,ambient;
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;
@ -23,11 +29,16 @@ out vec4 color;
void main(void)
{
vec4 texel = fragment.color*texture(Diffuse,vert.texcoord);
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);
intensity = 0.5+0.5*clamp( dot( normalize(normal),lightDir ), -1,1 );
vec3 normalDir = normalize(normal);
intensity = 0.5+0.5*clamp( dot( normalDir,lightDir ), -1,1 );
af = 1.0;
@ -36,13 +47,31 @@ void main(void)
//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;
intensity = 0.7*intensity + 0.3*intensity*visibility;
cf = intensity*(vec3(1.0,1.0,1.0)-ambient)+ambient;
cf = intensity*(vec3(1.0,1.0,1.0)-ambient)+ambient+specularReflection*visibility;
color = vec4(ct * cf, fragment.color.w);
}

View file

@ -12,16 +12,27 @@ static const char* useShadowMapInstancingFragmentShader= \
"} vert;\n"
"uniform sampler2D Diffuse;\n"
"uniform sampler2DShadow shadowMap;\n"
"in vec3 lightDir,normal,ambient;\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"
" 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"
" intensity = 0.5+0.5*clamp( dot( normalize(normal),lightDir ), -1,1 );\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"
@ -30,13 +41,30 @@ static const char* useShadowMapInstancingFragmentShader= \
" \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"
" intensity = 0.7*intensity + 0.3*intensity*visibility;\n"
" \n"
" cf = intensity*(vec3(1.0,1.0,1.0)-ambient)+ambient;\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

@ -8,14 +8,20 @@ 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 vec3 instance_scale;
layout (location = 6) in vec4 instance_scale_obUid;
uniform mat4 ModelViewMatrix;
uniform mat4 ProjectionMatrix;
uniform mat4 DepthBiasModelViewProjectionMatrix;
uniform mat4 MVP;
uniform vec3 lightDirIn;
uniform vec3 lightPosIn;
uniform vec3 cameraPositionIn;
uniform mat4 ViewMatrixInverse;
uniform float materialShininessIn;
uniform float shadowmapIntensityIn;
uniform vec3 lightSpecularIntensityIn;
uniform vec3 materialSpecularColorIn;
out vec4 ShadowCoord;
@ -60,7 +66,14 @@ vec4 quatRotate ( in vec4 p, in vec4 q )
return quatMul ( temp, vec4 ( -q.x, -q.y, -q.z, q.w ) );
}
out vec3 lightDir,normal,ambient;
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)
{
@ -69,15 +82,21 @@ void main(void)
vec4 worldNormal = (quatRotate3( vertexnormal,q));
normal = normalize(worldNormal).xyz;
normal = worldNormal.xyz;
lightDir = lightDirIn;
lightPos = lightPosIn;
cameraPosition = cameraPositionIn;
materialShininess = materialShininessIn;
vec4 localcoord = quatRotate3( position.xyz*instance_scale,q);
vec4 vertexPos = MVP* vec4((instance_position+localcoord).xyz,1);
gl_Position = vertexPos;
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;

View file

@ -8,12 +8,18 @@ static const char* useShadowMapInstancingVertexShader= \
"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 vec3 instance_scale;\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 lightDirIn;\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"
@ -51,7 +57,13 @@ static const char* useShadowMapInstancingVertexShader= \
" 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"
"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"
@ -59,13 +71,20 @@ static const char* useShadowMapInstancingVertexShader= \
" \n"
" vec4 worldNormal = (quatRotate3( vertexnormal,q));\n"
" \n"
" normal = normalize(worldNormal).xyz;\n"
" lightDir = lightDirIn;\n"
" \n"
" normal = worldNormal.xyz;\n"
" lightPos = lightPosIn;\n"
" cameraPosition = cameraPositionIn;\n"
" materialShininess = materialShininessIn;\n"
" \n"
" vec4 localcoord = quatRotate3( position.xyz*instance_scale,q);\n"
" vec4 vertexPos = MVP* vec4((instance_position+localcoord).xyz,1);\n"
" gl_Position = vertexPos;\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"

File diff suppressed because it is too large Load diff

View file

@ -5,31 +5,32 @@
#include "Bullet3Common/b3Matrix3x3.h"
#include "Bullet3Common/b3Transform.h"
B3_ATTRIBUTE_ALIGNED16(struct) SimpleCameraInternalData
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)
: 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;
B3_DECLARE_ALIGNED_ALLOCATOR();
B3_ATTRIBUTE_ALIGNED16(float)
m_offsetTransformVR[16];
b3Vector3 m_cameraTargetPosition;
float m_cameraDistance;
b3Vector3 m_cameraUp;
b3Vector3 m_cameraForward;
@ -37,21 +38,17 @@ B3_ATTRIBUTE_ALIGNED16(struct) SimpleCameraInternalData
//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;
float m_frustumZFar;
bool m_enableVR;
float m_viewMatrixVR[16];
float m_projectionMatrixVR[16];
};
SimpleCamera::SimpleCamera()
{
m_data = new SimpleCameraInternalData;
@ -61,16 +58,44 @@ SimpleCamera::~SimpleCamera()
delete m_data;
}
void SimpleCamera::setVRCamera(const float viewMat[16], const float projectionMatrix[16])
void SimpleCamera::setVRCamera(const float viewMat[16], const float projectionMatrix[16])
{
m_data->m_enableVR = true;
for (int i=0;i<16;i++)
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;
@ -78,44 +103,39 @@ void SimpleCamera::disableVRCamera()
bool SimpleCamera::isVRCamera() const
{
return m_data->m_enableVR ;
return m_data->m_enableVR;
}
static void b3CreateFrustum(
float left,
float right,
float bottom,
float top,
float nearVal,
float farVal,
float frustum[16])
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[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[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);
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])
{
@ -145,33 +165,33 @@ static void b3CreateOrtho(float left, float right, float bottom, float top, floa
result[3][2] = - (zFar + zNear) / (zFar - zNear);
}
#endif
static void b3CreateLookAt(const b3Vector3& eye, const b3Vector3& center,const b3Vector3& up, float result[16])
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);
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 + 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 + 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 + 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[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;
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)
@ -181,190 +201,233 @@ void SimpleCamera::setCameraUpAxis(int upAxis)
update();
}
int SimpleCamera::getCameraUpAxis() const
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);
break;
case 2:
forwardAxis = 1;
m_data->m_cameraUp = b3MakeVector3(0,0,1);
//gLightPos = b3MakeVector3(-50.f,30,100);
break;
default:
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);
b3Vector3 eyePos = b3MakeVector3(0, 0, 0);
eyePos[forwardAxis] = -m_data->m_cameraDistance;
eyePos = b3Matrix3x3(eyeRot) * eyePos;
m_data->m_cameraForward = b3MakeVector3(eyePos[0],eyePos[1],eyePos[2]);
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.setValue(1.f, 0.f, 0.f);
}
else
{
m_data->m_cameraForward.normalize();
}
// m_azi=m_azi+0.01;
b3Scalar rele = m_data->m_yaw * b3Scalar(0.01745329251994329547);// rads per deg
b3Scalar razi = m_data->m_pitch * b3Scalar(0.01745329251994329547);// rads per deg
b3Quaternion rot(m_data->m_cameraUp,razi);
b3Vector3 right = m_data->m_cameraUp.cross(m_data->m_cameraForward);
b3Quaternion roll(right,-rele);
eyePos = b3Matrix3x3(rot) * b3Matrix3x3(roll) * eyePos;
m_data->m_cameraPosition = eyePos;
m_data->m_cameraPosition+= m_data->m_cameraTargetPosition;
}
void SimpleCamera::getCameraProjectionMatrix(float projectionMatrix[16]) const
{
if (m_data->m_enableVR)
{
for (int i=0;i<16;i++)
for (int i = 0; i < 16; i++)
{
projectionMatrix[i] = m_data->m_projectionMatrixVR[i];
}
} else
}
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);
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])
void SimpleCamera::setVRCameraOffsetTransform(const float offset[16])
{
for (int i=0;i<16;i++)
for (int i = 0; i < 16; i++)
{
m_data->m_offsetTransformVR[i] = offset[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++)
for (int i = 0; i < 16; i++)
{
b3Transform tr;
tr.setFromOpenGLMatrix(m_data->m_viewMatrixVR);
b3Transform shift=b3Transform::getIdentity();
b3Transform shift = b3Transform::getIdentity();
shift.setFromOpenGLMatrix(m_data->m_offsetTransformVR);
tr = tr*shift;
tr = tr * shift;
tr.getOpenGLMatrix(viewMatrix);
//viewMatrix[i] = m_data->m_viewMatrixVR[i];
}
} else
}
else
{
b3CreateLookAt(m_data->m_cameraPosition,m_data->m_cameraTargetPosition,m_data->m_cameraUp,viewMatrix);
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];
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];
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];
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];
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)
void SimpleCamera::setCameraTargetPosition(float x, float y, float z)
{
m_data->m_cameraTargetPosition.setValue(x,y,z);
m_data->m_cameraTargetPosition.setValue(x, y, z);
update();
}
float SimpleCamera::getCameraDistance() const
float SimpleCamera::getCameraDistance() const
{
return m_data->m_cameraDistance;
}
void SimpleCamera::setCameraDistance(float dist)
void SimpleCamera::setCameraDistance(float dist)
{
m_data->m_cameraDistance = dist;
update();
}
void SimpleCamera::setCameraUpVector(float x,float y ,float z)
void SimpleCamera::setCameraUpVector(float x, float y, float z)
{
m_data->m_cameraUp.setValue(x,y,z);
m_data->m_cameraUp.setValue(x, y, z);
update();
}
void SimpleCamera::getCameraUpVector(float up[3]) const
void SimpleCamera::getCameraUpVector(float up[3]) const
{
up[0] = float(m_data->m_cameraUp[0]);
up[1] = float(m_data->m_cameraUp[1]);
up[2] = float(m_data->m_cameraUp[2]);
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)
void SimpleCamera::setCameraYaw(float yaw)
{
m_data->m_yaw = yaw;
update();
}
float SimpleCamera::getCameraYaw() const
float SimpleCamera::getCameraYaw() const
{
return m_data->m_yaw;
}
void SimpleCamera::setCameraPitch(float pitch)
void SimpleCamera::setCameraPitch(float pitch)
{
m_data->m_pitch = pitch;
update();
}
void SimpleCamera::setAspectRatio(float ratio)
void SimpleCamera::setAspectRatio(float ratio)
{
m_data->m_aspect = ratio;
update();
}
float SimpleCamera::getCameraPitch() const
float SimpleCamera::getCameraPitch() const
{
return m_data->m_pitch;
}
float SimpleCamera::getAspectRatio() const
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

@ -13,9 +13,11 @@ struct SimpleCamera : public CommonCameraInterface
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 void setVRCameraOffsetTransform(const float offset[16]);
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;
@ -26,25 +28,33 @@ struct SimpleCamera : public CommonCameraInterface
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 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;
virtual void setCameraUpVector(float x,float y, float z);
void getCameraUpVector(float up[3]) const;
///the setCameraUpAxis will call the 'setCameraUpVector' and 'setCameraForwardVector'
virtual void setCameraUpAxis(int axis);
virtual int getCameraUpAxis() const;
virtual void setCameraUpAxis(int axis);
virtual int getCameraUpAxis() const;
virtual void setCameraYaw(float yaw);
virtual float getCameraYaw() const;
virtual void setCameraYaw(float yaw);
virtual float getCameraYaw() const;
virtual void setCameraPitch(float pitch);
virtual float getCameraPitch() const;
virtual void setCameraPitch(float pitch);
virtual float getCameraPitch() const;
virtual void setAspectRatio(float ratio);
virtual float getAspectRatio() 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
#endif //SIMPLE_CAMERA_H

View file

@ -1,99 +1,117 @@
#include "SimpleOpenGL2App.h"
#define USE_OPENGL2
#include "OpenGLInclude.h"
#include "Bullet3Common/b3Logging.h"//b3Assert?
#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"
#endif //_WIN32
#endif//__APPLE__
#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 SimpleOpenGL2App* gApp2 = 0;
static void Simple2ResizeCallback( float widthf, float heightf)
static void Simple2ResizeCallback(float widthf, float heightf)
{
int width = (int)widthf;
int height = (int)heightf;
if (gApp2->m_renderer)
gApp2->m_renderer->resize(width,height);
//gApp2->m_renderer->setScreenSize(width,height);
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);
}
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)
void Simple2MouseButtonCallback(int button, int state, float x, float y)
{
gApp2->defaultMouseButtonCallback(button,state,x,y);
if (gApp2 && gApp2->m_window)
{
gApp2->defaultMouseButtonCallback(button, state, x, y);
}
}
void Simple2MouseMoveCallback( float x, float y)
void Simple2MouseMoveCallback(float x, float y)
{
gApp2->defaultMouseMoveCallback(x,y);
if (gApp2 && gApp2->m_window)
{
gApp2->defaultMouseMoveCallback(x, y);
}
}
void Simple2WheelCallback( float deltax, float deltay)
void Simple2WheelCallback(float deltax, float deltay)
{
gApp2->defaultWheelCallback(deltax,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)
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);
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;
return TexID;
}
SimpleOpenGL2App::SimpleOpenGL2App(const char* title, int width, int height)
{
gApp2 = this;
@ -109,61 +127,65 @@ SimpleOpenGL2App::SimpleOpenGL2App(const char* title, int width, int height)
m_window->setWindowTitle(title);
#ifndef NO_GLEW
#ifndef __APPLE__
#ifndef _WIN32
//some Linux implementations need the 'glewExperimental' to be true
glewExperimental = GL_TRUE;
#endif
#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 (glewInit() != GLEW_OK)
{
#if 0
if (glewInit() != GLEW_OK)
{
b3Error("glewInit failed");
exit(1);
}
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
}
{
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);
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);
b3Assert(glGetError() == GL_NO_ERROR);
//m_primRenderer = new GLPrimitiveRenderer(width,height);
m_parameterInterface = 0;
b3Assert(glGetError() ==GL_NO_ERROR);
b3Assert(glGetError() == GL_NO_ERROR);
//m_instancingRenderer = new GLInstancingRenderer(128*1024,32*1024*1024);
//m_instancingRenderer->init();
//m_instancingRenderer->resize(width,height);
//m_renderer = new GLInstancingRenderer(128*1024,32*1024*1024);
//m_renderer->init();
//m_renderer->resize(width,height);
b3Assert(glGetError() ==GL_NO_ERROR);
b3Assert(glGetError() == GL_NO_ERROR);
//m_instancingRenderer->InitShaders();
//m_renderer->InitShaders();
m_window->setMouseMoveCallback(Simple2MouseMoveCallback);
m_window->setMouseButtonCallback(Simple2MouseButtonCallback);
m_window->setKeyboardCallback(Simple2KeyboardCallback);
m_window->setWheelCallback(Simple2WheelCallback);
m_window->setKeyboardCallback(Simple2KeyboardCallback);
m_window->setWheelCallback(Simple2WheelCallback);
m_window->setResizeCallback(Simple2ResizeCallback);
m_renderer = new SimpleOpenGL2Renderer(width, height);
}
SimpleOpenGL2App::~SimpleOpenGL2App()
@ -174,51 +196,52 @@ SimpleOpenGL2App::~SimpleOpenGL2App()
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);
CommonGraphicsApp::setBackgroundColor(red, green, blue);
glClearColor(m_backgroundColorRGB[0], m_backgroundColorRGB[1], m_backgroundColorRGB[2], 1.f);
}
void SimpleOpenGL2App::drawGrid(DrawGridData data)
{
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];
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;
int sideAxis = -1;
int forwardAxis = -1;
switch (upAxis)
{
case 1:
forwardAxis=2;
sideAxis=0;
forwardAxis = 2;
sideAxis = 0;
break;
case 2:
forwardAxis=1;
sideAxis=0;
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++)
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);
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);
b3Vector3 to = b3MakeVector3(0, 0, 0);
to[sideAxis] = float(i);
to[upAxis] = upOffset;
to[forwardAxis] = float(gridSize);
@ -226,18 +249,17 @@ void SimpleOpenGL2App::drawGrid(DrawGridData data)
indices.push_back(lineIndex++);
vertices.push_back(to);
indices.push_back(lineIndex++);
// m_renderer->drawLine(from,to,gridColor);
// m_renderer->drawLine(from,to,gridColor);
}
b3Assert(glGetError() ==GL_NO_ERROR);
b3Assert(glGetError() == GL_NO_ERROR);
{
b3Assert(glGetError() ==GL_NO_ERROR);
b3Vector3 from=b3MakeVector3(0,0,0);
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);
b3Vector3 to = b3MakeVector3(0, 0, 0);
to[sideAxis] = float(gridSize);
to[upAxis] = upOffset;
to[forwardAxis] = float(i);
@ -245,86 +267,78 @@ void SimpleOpenGL2App::drawGrid(DrawGridData data)
indices.push_back(lineIndex++);
vertices.push_back(to);
indices.push_back(lineIndex++);
// m_renderer->drawLine(from,to,gridColor);
// m_renderer->drawLine(from,to,gridColor);
}
}
m_renderer->drawLines(&vertices[0].x,
gridColor,
vertices.size(),sizeof(b3Vector3),&indices[0],indices.size(),1);
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);
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)
// 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_instancingRenderer->drawPoints(&points[0].x, b3MakeVector3(1, 0, 0), 3, sizeof(b3Vector3), 6);
// 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 1;
return this->m_data->m_upAxis;
}
void SimpleOpenGL2App::swapBuffer()
{
m_window->endRendering();
m_window->startRendering();
}
void SimpleOpenGL2App::drawText( const char* txt, int posX, int posY)
{
}
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 worldPosX, float worldPosY, float worldPosZ, float size1)
void SimpleOpenGL2App::drawText(const char* txt, int posXi, int posYi, float size, float colorRGBA[4])
{
saveOpenGLState(gApp2->m_renderer->getScreenWidth(),gApp2->m_renderer->getScreenHeight());
}
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();
@ -332,37 +346,33 @@ void SimpleOpenGL2App::drawText3D( const char* txt, float worldPosX, float world
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);
// 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 );
glAlphaFunc(GL_GREATER, 1.0f);
int viewport[4]={0,0,gApp2->m_renderer->getScreenWidth(),gApp2->m_renderer->getScreenHeight()};
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;
float winx, winy, winz;
if (!projectWorldCoordToScreen(worldPosX, worldPosY, worldPosZ,viewMat,projMat,viewport,&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;
posY = gApp2->m_renderer->getScreenHeight() / 2 + (gApp2->m_renderer->getScreenHeight() / 2) - winy;
{
//float width = 0.f;
int pos=0;
int pos = 0;
//float color[]={0.2f,0.2,0.2f,1.f};
glActiveTexture(GL_TEXTURE0);
glMatrixMode(GL_TEXTURE);
@ -371,91 +381,184 @@ void SimpleOpenGL2App::drawText3D( const char* txt, float worldPosX, float world
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glBindTexture(GL_TEXTURE_2D,m_data->m_largeFontTextureId);
glEnable(GL_TEXTURE_2D);//BindTexture
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;
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 endX = startX + g_DefaultLargeFont->m_CharWidth[c] * size1;
float endY = posY;
float currentColor[]={1.f,0.2,0.2f,1.f};
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 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,
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] = {
{ 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)},
{ 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)},
{ 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)},
{ 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();
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);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
restoreOpenGLState();
}
void SimpleOpenGL2App::registerGrid(int xres, int yres, float color0[4], float color1[4])
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

@ -6,31 +6,27 @@
class SimpleOpenGL2App : public CommonGraphicsApp
{
protected:
struct SimpleOpenGL2AppInternalData* m_data;
struct SimpleOpenGL2AppInternalData* m_data;
public:
SimpleOpenGL2App(const char* title, int width, int height);
virtual ~SimpleOpenGL2App();
virtual void drawGrid(DrawGridData data=DrawGridData());
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);
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)
{
return 0;
}
virtual int registerGraphicsUnitSphereShape(EnumSphereLevelOfDetail lod, int textureId=-1)
{
return 0;
}
virtual void drawText3D( const char* txt, float posX, float posZY, float posZ, float size);
virtual void registerGrid(int xres, int yres, float color0[4], float color1[4]);
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
#endif //SIMPLE_OPENGL2_APP_H

View file

@ -2,13 +2,71 @@
#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_width(width),
m_height(height)
{
m_data = new SimpleOpenGL2RendererInternalData;
m_data->m_width = width;
m_data->m_height = height;
}
SimpleOpenGL2Renderer::~SimpleOpenGL2Renderer()
{
delete m_data;
}
void SimpleOpenGL2Renderer::init()
@ -17,148 +75,560 @@ void SimpleOpenGL2Renderer::init()
const CommonCameraInterface* SimpleOpenGL2Renderer::getActiveCamera() const
{
return &m_camera;
return &m_data->m_camera;
}
CommonCameraInterface* SimpleOpenGL2Renderer::getActiveCamera()
{
return &m_camera;
return &m_data->m_camera;
}
void SimpleOpenGL2Renderer::setActiveCamera(CommonCameraInterface* cam)
{
b3Assert(0);//not supported yet
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];
m_camera.setAspectRatio((float)m_width/(float)m_height);
m_camera.update();
m_camera.getCameraProjectionMatrix(projection);
m_camera.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);
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::writeSingleInstanceColorToCPU(float* color, int srcIndex)
void SimpleOpenGL2Renderer::removeGraphicsInstance(int instanceUid)
{
}
void SimpleOpenGL2Renderer::writeSingleInstanceColorToCPU(double* color, int srcIndex)
{
m_data->m_graphicsInstancesPool.freeHandle(instanceUid);
}
void SimpleOpenGL2Renderer::writeSingleInstanceScaleToCPU(float* scale, int srcIndex)
bool SimpleOpenGL2Renderer::readSingleInstanceTransformToCPU(float* position, float* orientation, int srcIndex)
{
return false;
}
void SimpleOpenGL2Renderer::writeSingleInstanceColorToCPU(const float* color, int srcIndex)
{
}
void SimpleOpenGL2Renderer::writeSingleInstanceScaleToCPU(double* scale, 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 0;
return m_data->m_graphicsInstancesPool.getNumHandles();
}
void SimpleOpenGL2Renderer::getCameraViewMatrix(float viewMat[16]) const
void SimpleOpenGL2Renderer::getCameraViewMatrix(float viewMat[16]) const
{
b3Assert(0);
b3Assert(0);
}
void SimpleOpenGL2Renderer::getCameraProjectionMatrix(float projMat[16]) const
void SimpleOpenGL2Renderer::getCameraProjectionMatrix(float projMat[16]) const
{
b3Assert(0);
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)
{
return 0;
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)
{
return 0;
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();
}
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();
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)
int SimpleOpenGL2Renderer::registerShape(const float* vertices, int numvertices, const int* indices, int numIndices, int primitiveType, int textureIndex)
{
return 0;
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)
{
@ -166,13 +636,32 @@ void SimpleOpenGL2Renderer::drawPoint(const float* position, const float color[4
void SimpleOpenGL2Renderer::drawPoint(const double* position, const double color[4], double pointDrawSize)
{
}
void SimpleOpenGL2Renderer::updateShape(int shapeIndex, const float* vertices)
void SimpleOpenGL2Renderer::drawPoints(const float* positions, const float* colors, int numPoints, int pointStrideInBytes, float pointDrawSize)
{
}
void SimpleOpenGL2Renderer::enableBlend(bool blend)
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()

View file

@ -5,92 +5,92 @@
#include "../CommonInterfaces/CommonRenderInterface.h"
#include "SimpleCamera.h"
struct SimpleOpenGL2Renderer : public CommonRenderInterface
class SimpleOpenGL2Renderer : public CommonRenderInterface
{
int m_width;
int m_height;
SimpleCamera m_camera;
SimpleOpenGL2Renderer(int width, int height);
virtual void init();
virtual void updateCamera(int upAxis);
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 resize(int width, int height)
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)
{
m_width = width;
m_height = height;
}
virtual void removeAllInstances();
virtual void writeSingleInstanceColorToCPU(float* color, int srcIndex);
virtual void writeSingleInstanceColorToCPU(double* color, int srcIndex);
virtual void writeSingleInstanceScaleToCPU(float* scale, int srcIndex);
virtual void writeSingleInstanceScaleToCPU(double* scale, int srcIndex);
virtual void getCameraViewMatrix(float viewMat[16]) const;
virtual void getCameraProjectionMatrix(float projMat[16]) const;
virtual void renderScene();
virtual void renderScene();
virtual int getScreenWidth()
{
return m_width;
}
virtual int getScreenHeight()
{
return m_height;
}
virtual int registerTexture(const unsigned char* texels, int width, int height)
{
return -1;
}
virtual void updateTexture(int textureIndex, const unsigned char* texels) {}
virtual void activateTexture(int textureIndex) {}
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 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 updateShape(int shapeIndex, const float* vertices);
virtual void enableBlend(bool blend);
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()
virtual struct GLInstanceRendererInternalData* getInternalData()
{
return 0;
}
};
#endif //SIMPLE_OPENGL2_RENDERER_H
#endif //SIMPLE_OPENGL2_RENDERER_H

File diff suppressed because it is too large Load diff

View file

@ -7,36 +7,38 @@
#include "../CommonInterfaces/CommonGraphicsAppInterface.h"
struct SimpleOpenGL3App : public CommonGraphicsApp
{
struct SimpleInternalData* m_data;
class GLPrimitiveRenderer* m_primRenderer;
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);
SimpleOpenGL3App(const char* title, int width,int height, bool allowRetina);
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 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);
void getScreenPixels(unsigned char* rgbaBuffer, int bufferSizeInBytes, float* depthBuffer, int depthBufferSizeInBytes);
void drawGrid(DrawGridData data=DrawGridData());
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);
virtual void drawText3D( const char* txt, float posX, float posZY, float posZ, float size);
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 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
#endif //SIMPLE_OPENGL3_APP_H

File diff suppressed because it is too large Load diff

View file

@ -10,7 +10,6 @@
//
// ---------------------------------------------------------------------------
#if !defined ANT_TW_FONTS_INCLUDED
#define ANT_TW_FONTS_INCLUDED
@ -32,36 +31,32 @@ Last row of a line of characters is a delimiter with color=zero at the last pixe
*/
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;
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();
~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_DefaultNormalFontAA;
extern CTexFont *g_DefaultLargeFont;
extern CTexFont *g_DefaultFixed1Font;
void TwGenerateDefaultFonts();
void TwDeleteDefaultFonts();
#endif // !defined ANT_TW_FONTS_INCLUDED

View file

@ -4,14 +4,14 @@
#include <windows.h>
struct InternalData2
{
HWND m_hWnd;;
int m_fullWindowWidth;//includes borders etc
HWND m_hWnd;
;
int m_fullWindowWidth; //includes borders etc
int m_fullWindowHeight;
int m_openglViewportWidth;//just the 3d viewport/client area
int m_openglViewportWidth; //just the 3d viewport/client area
int m_openglViewportHeight;
HDC m_hDC;
@ -30,24 +30,22 @@ struct InternalData2
int m_internalKeyModifierFlags;
b3WheelCallback m_wheelCallback;
b3MouseMoveCallback m_mouseMoveCallback;
b3MouseButtonCallback m_mouseButtonCallback;
b3ResizeCallback m_resizeCallback;
b3KeyboardCallback m_keyboardCallback;
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_mouseLButton = 0;
m_mouseRButton = 0;
m_mouseMButton = 0;
m_internalKeyModifierFlags = 0;
m_fullWindowWidth = 0;
m_fullWindowHeight= 0;
m_openglViewportHeight=0;
m_openglViewportWidth=0;
m_fullWindowHeight = 0;
m_openglViewportHeight = 0;
m_openglViewportWidth = 0;
m_hDC = 0;
m_hRC = 0;
m_OpenGLInitialized = false;
@ -61,8 +59,7 @@ struct InternalData2
m_mouseButtonCallback = 0;
m_resizeCallback = 0;
m_wheelCallback = 0;
}
};
#endif //WIN32_INTERNAL_WINDOW_DATA_H
#endif //WIN32_INTERNAL_WINDOW_DATA_H

View file

@ -1,3 +1,4 @@
#ifndef B3_USE_GLFW
#ifdef _WIN32
/*
Copyright (c) 2012 Advanced Micro Devices, Inc.
@ -14,7 +15,6 @@ subject to the following restrictions:
*/
//Originally written by Erwin Coumans
#include "Win32OpenGLWindow.h"
#include "OpenGLInclude.h"
@ -23,129 +23,100 @@ subject to the following restrictions:
#include "Win32InternalWindowData.h"
#include <stdio.h>
static void printGLString(const char *name, GLenum s) {
const char *v = (const char *) glGetString(s);
printf("%s = %s\n",name, v);
}
bool sOpenGLVerbose = true;
#include <stdlib.h>
void Win32OpenGLWindow::enableOpenGL()
{
PIXELFORMATDESCRIPTOR pfd;
int format;
// get the device context (DC)
m_data->m_hDC = GetDC( m_data->m_hWnd );
m_data->m_hDC = GetDC(m_data->m_hWnd);
// set the pixel format for the DC
ZeroMemory( &pfd, sizeof( pfd ) );
pfd.nSize = sizeof( pfd );
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.cGreenBits = 8;
pfd.cBlueBits = 8;
pfd.cAlphaBits = 8;
pfd.cDepthBits = 24;
pfd.cStencilBits = 8;//1;
pfd.cStencilBits = 8; //1;
pfd.iLayerType = PFD_MAIN_PLANE;
format = ChoosePixelFormat( m_data->m_hDC, &pfd );
SetPixelFormat( m_data->m_hDC, format, &pfd );
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 );
if (sOpenGLVerbose)
{
printGLString("Version", GL_VERSION);
printGLString("Vendor", GL_VENDOR);
printGLString("Renderer", GL_RENDERER);
}
//printGLString("Extensions", GL_EXTENSIONS);
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 );
wglMakeCurrent(NULL, NULL);
wglDeleteContext(m_data->m_hRC);
// ReleaseDC( m_data->m_hWnd, m_data->m_hDC );
}
void Win32OpenGLWindow::createWindow(const b3gWindowConstructionInfo& ci)
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()
void Win32OpenGLWindow::closeWindow()
{
disableOpenGL();
Win32Window::closeWindow();
}
void Win32OpenGLWindow::startRendering()
void Win32OpenGLWindow::startRendering()
{
pumpMessage();
//don't clear all 3 buffers because some AMD drivers are buggy
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
pumpMessage();
//glCullFace(GL_BACK);
//glFrontFace(GL_CCW);
glEnable(GL_DEPTH_TEST);
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::renderAllObjects()
{
}
void Win32OpenGLWindow::endRendering()
{
SwapBuffers( m_data->m_hDC );
void Win32OpenGLWindow::endRendering()
{
SwapBuffers(m_data->m_hDC);
}
int Win32OpenGLWindow::fileOpenDialog(char* fileName, int maxFileNameLength)
{
#if 0
//wchar_t wideChars[1024];
OPENFILENAME ofn ;
@ -165,7 +136,7 @@ int Win32OpenGLWindow::fileOpenDialog(char* fileName, int maxFileNameLength)
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;
@ -175,9 +146,9 @@ int Win32OpenGLWindow::fileOpenDialog(char* fileName, int maxFileNameLength)
ofn.Flags = OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST ;
GetOpenFileName( &ofn );
return strlen(fileName);
//return 0;
#else
return 0;
#endif
}
int Win32OpenGLWindow::getWidth() const
@ -191,10 +162,9 @@ int Win32OpenGLWindow::getHeight() const
{
if (m_data)
return m_data->m_openglViewportHeight;
return 0;
return 0;
}
#endif
#endif //B3_USE_GLFW

View file

@ -13,12 +13,9 @@ subject to the following restrictions:
*/
//Originally written by Erwin Coumans
#ifndef _WIN32_OPENGL_RENDER_MANAGER_H
#define _WIN32_OPENGL_RENDER_MANAGER_H
#include "Win32Window.h"
#define b3gDefaultOpenGLWindow Win32OpenGLWindow
@ -27,38 +24,33 @@ class Win32OpenGLWindow : public Win32Window
{
bool m_OpenGLInitialized;
protected:
protected:
void enableOpenGL();
void disableOpenGL();
public:
Win32OpenGLWindow();
virtual ~Win32OpenGLWindow();
virtual void createWindow(const b3gWindowConstructionInfo& ci);
virtual void closeWindow();
virtual void createWindow(const b3gWindowConstructionInfo& ci);
virtual void startRendering();
virtual void closeWindow();
virtual void renderAllObjects();
virtual void startRendering();
virtual void endRendering();
virtual void renderAllObjects();
virtual float getRetinaScale() const {return 1.f;}
virtual void setAllowRetina(bool /*allowRetina*/) {};
virtual void endRendering();
virtual int getWidth() const;
virtual int getHeight() const;
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
#endif //_WIN32_OPENGL_RENDER_MANAGER_H

File diff suppressed because it is too large Load diff

View file

@ -13,74 +13,66 @@ subject to the following restrictions:
*/
//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;
protected:
struct InternalData2* m_data;
void pumpMessage();
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 createWindow(const b3gWindowConstructionInfo& ci);
virtual void closeWindow();
virtual void switchFullScreen(bool fullscreen, int width = 0, int height = 0, int colorBitsPerPixel = 0);
virtual void runMainLoop();
virtual void closeWindow();
virtual void startRendering();
virtual void runMainLoop();
virtual void renderAllObjects();
virtual void startRendering();
virtual void endRendering();
virtual void renderAllObjects();
virtual float getTimeInSeconds();
virtual void endRendering();
virtual void setDebugMessage(int x,int y,const char* message);
virtual bool requestedExit() const;
virtual void setRequestExit();
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 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 b3KeyboardCallback getKeyboardCallback();
virtual void setRenderCallback( b3RenderCallback renderCallback);
virtual void setRenderCallback(b3RenderCallback renderCallback);
virtual void setWindowTitle(const char* title);
virtual void setWindowTitle(const char* title);
virtual bool isModifierKeyPressed(int key);
virtual bool isModifierKeyPressed(int key);
};
#endif //_WIN32_WINDOW_H
#endif //_WIN32_WINDOW_H

File diff suppressed because it is too large Load diff

View file

@ -7,72 +7,66 @@
class X11OpenGLWindow : public CommonWindowInterface
{
struct InternalData2* m_data;
bool m_OpenGLInitialized;
struct InternalData2* m_data;
bool m_OpenGLInitialized;
bool m_requestedExit;
protected:
void enableOpenGL();
void enableOpenGL();
void disableOpenGL();
void disableOpenGL();
void pumpMessage();
void pumpMessage();
int getAsciiCodeFromVirtualKeycode(int orgCode);
int getAsciiCodeFromVirtualKeycode(int orgCode);
public:
X11OpenGLWindow();
X11OpenGLWindow();
virtual ~X11OpenGLWindow();
virtual ~X11OpenGLWindow();
virtual void createWindow(const b3gWindowConstructionInfo& ci);
virtual void createWindow(const b3gWindowConstructionInfo& ci);
virtual void closeWindow();
virtual void closeWindow();
virtual void startRendering();
virtual void startRendering();
virtual void renderAllObjects();
virtual void renderAllObjects();
virtual void endRendering();
virtual void endRendering();
virtual float getRetinaScale() const { return 1.f; }
virtual void setAllowRetina(bool /*allowRetina*/){};
virtual float getRetinaScale() const {return 1.f;}
virtual void setAllowRetina(bool /*allowRetina*/) {};
virtual void runMainLoop();
virtual float getTimeInSeconds();
virtual void runMainLoop();
virtual float getTimeInSeconds();
virtual bool requestedExit() const;
virtual void setRequestExit() ;
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 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 b3MouseMoveCallback getMouseMoveCallback();
virtual b3MouseButtonCallback getMouseButtonCallback();
virtual b3ResizeCallback getResizeCallback();
virtual b3WheelCallback getWheelCallback();
virtual b3KeyboardCallback getKeyboardCallback();
virtual void setRenderCallback( b3RenderCallback renderCallback);
virtual void setRenderCallback(b3RenderCallback renderCallback);
virtual void setWindowTitle(const char* title);
virtual void setWindowTitle(const char* title);
virtual int getWidth() const;
virtual int getWidth() const;
virtual int getHeight() const;
virtual int getHeight() const;
int fileOpenDialog(char* filename, int maxNameLength);
};
#endif

View file

@ -26,8 +26,6 @@
#endif
#include "fontstash.h"
#define BORDER_X_LEFT 2
#define BORDER_X_RIGHT 2
#define BORDER_Y_TOP 2
@ -35,34 +33,30 @@
#define ADDITIONAL_HEIGHT 2
#define STB_TRUETYPE_IMPLEMENTATION
#define STBTT_malloc(x,u) malloc(x)
#define STBTT_free(x,u) free(x)
#include "stb_truetype.h"
#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
#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);
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;
@ -78,23 +72,17 @@ struct sth_font
struct sth_font* next;
};
struct sth_stash
{
int tw,th;
float itw,ith;
int tw, th;
float itw, ith;
struct sth_texture* textures;
struct sth_font* fonts;
int drawing;
RenderCallbacks* m_renderCallbacks;
RenderCallbacks* m_renderCallbacks;
};
// Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
// See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
@ -102,34 +90,30 @@ struct sth_stash
#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
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];
*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;
@ -138,34 +122,33 @@ struct sth_stash* sth_create(int cachew, int cacheh, RenderCallbacks* renderCall
// 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));
{
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));
{
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->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)
@ -175,19 +158,17 @@ int sth_add_font_from_memory(struct sth_stash* stash, unsigned char* buffer)
fnt = (struct sth_font*)malloc(sizeof(struct sth_font));
if (fnt == NULL) goto error;
memset(fnt,0,sizeof(struct sth_font));
memset(fnt, 0, sizeof(struct sth_font));
// Init hash lookup.
for (i = 0; i < HASH_LUT_SIZE; ++i)
fnt->lut[i] = -1;
fnt->lut[i] = -1;
fnt->data = buffer;
// Init stb_truetype
if (!stbtt_InitFont(&fnt->font, fnt->data, 0))
goto error;
goto error;
// Store normalized line height. The real line height is got
// by multiplying the lineh by font size.
@ -203,11 +184,11 @@ int sth_add_font_from_memory(struct sth_stash* stash, unsigned char* buffer)
fnt->next = stash->fonts;
stash->fonts = fnt;
return idx++;
error:
if (fnt) {
if (fnt)
{
if (fnt->glyphs) free(fnt->glyphs);
free(fnt);
}
@ -219,14 +200,14 @@ int sth_add_font(struct sth_stash* stash, const char* path)
FILE* fp = 0;
int datasize;
unsigned char* data = NULL;
int idx=0;
int idx = 0;
// Read in the font data.
fp = fopen(path, "rb");
if (!fp) goto error;
fseek(fp,0,SEEK_END);
fseek(fp, 0, SEEK_END);
datasize = (int)ftell(fp);
fseek(fp,0,SEEK_SET);
fseek(fp, 0, SEEK_SET);
data = (unsigned char*)malloc(datasize);
if (data == NULL) goto error;
int bytesRead;
@ -238,7 +219,6 @@ int sth_add_font(struct sth_stash* stash, const char* path)
fclose(fp);
fp = 0;
// Modify type of the loaded font.
if (idx)
stash->fonts->type = TTFONT_FILE;
@ -260,7 +240,7 @@ int sth_add_bitmap_font(struct sth_stash* stash, int ascent, int descent, int li
fnt = (struct sth_font*)malloc(sizeof(struct sth_font));
if (fnt == NULL) goto error;
memset(fnt,0,sizeof(struct sth_font));
memset(fnt, 0, sizeof(struct sth_font));
// Init hash lookup.
for (i = 0; i < HASH_LUT_SIZE; ++i) fnt->lut[i] = -1;
@ -354,18 +334,18 @@ error:
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;
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;
float size = isize / 10.0f;
int rh;
struct sth_row* br = NULL;
// Find code point and size.
h = hashint(codepoint) & (HASH_LUT_SIZE-1);
h = hashint(codepoint) & (HASH_LUT_SIZE - 1);
i = fnt->lut[h];
while (i != -1)
{
@ -382,23 +362,23 @@ static struct sth_glyph* get_glyph(struct sth_stash* stash, struct sth_font* fnt
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;
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
// 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;
rh = (gh + 7) & ~7;
texture = stash->textures;
while(br == NULL)
while (br == NULL)
{
for (i = 0; i < texture->nrows; ++i)
{
if (texture->rows[i].h >= rh && texture->rows[i].x+gw+1 <= stash->tw)
if (texture->rows[i].h >= rh && texture->rows[i].x + gw + 1 <= stash->tw)
br = &texture->rows[i];
}
@ -412,8 +392,8 @@ static struct sth_glyph* get_glyph(struct sth_stash* stash, struct sth_font* fnt
// 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)
py = texture->rows[texture->nrows - 1].y + texture->rows[texture->nrows - 1].h + 1;
if (py + rh > stash->th)
{
if (texture->next != NULL)
{
@ -425,11 +405,9 @@ static struct sth_glyph* get_glyph(struct sth_stash* stash, struct sth_font* fnt
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);
memset(texture, 0, sizeof(struct sth_texture));
stash->m_renderCallbacks->updateTexture(texture, 0, stash->tw, stash->th);
}
continue;
}
@ -437,46 +415,45 @@ static struct sth_glyph* get_glyph(struct sth_stash* stash, struct sth_font* fnt
// 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;
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));
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];
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->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;
br->x += gw + BORDER_X_RIGHT;
// Insert char to hash lookup.
glyph->next = fnt->lut[h];
fnt->lut[h] = fnt->nglyphs-1;
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);
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;
@ -489,20 +466,20 @@ error:
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;
float rx, ry;
float scale = 1.f / s_retinaScale; //1.0f;
if (fnt->type == BMFONT)
scale = isize/(glyph->size*10.0f);
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->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->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;
@ -514,34 +491,77 @@ static int get_quad(struct sth_stash* stash, struct sth_font* fnt, struct sth_gl
return 1;
}
static Vertex* setv(Vertex* v, float x, float y, float s, float t, float width, float height)
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)
{
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;
short isize = 1;
float rx, ry;
float scale = textScale / fontSize; //0.1;//1.0f;
v->uv.p[0] = s;
v->uv.p[1] = t;
if (fnt->type == BMFONT)
scale = isize / (glyph->size);
v->colour.p[0] = 0.1f;//1.f;
v->colour.p[1] = 0.1f;
v->colour.p[2] = 0.1f;
v->colour.p[3] = 1.f;
rx = (*x + scale * float(glyph->xoff));
ry = (scale * float(glyph->yoff));
return v+1;
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)
{
@ -557,7 +577,6 @@ static void flush_draw(struct sth_stash* stash)
}
}
void sth_begin_draw(struct sth_stash* stash)
{
if (stash == NULL) return;
@ -571,7 +590,7 @@ void sth_end_draw(struct sth_stash* stash)
if (stash == NULL) return;
if (!stash->drawing) return;
/*
/*
// Debug dump.
if (stash->nverts+6 < VERT_COUNT)
{
@ -595,20 +614,20 @@ 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)
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;
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);
short isize = (short)(size * 10.0f);
Vertex* v;
struct sth_font* fnt = NULL;
@ -616,21 +635,21 @@ void sth_draw_texture(struct sth_stash* stash,
if (!stash->textures) return;
fnt = stash->fonts;
while(fnt != NULL && fnt->idx != idx) fnt = fnt->next;
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;
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)
if (texture->nverts + 6 >= VERT_COUNT)
flush_draw(stash);
if (!get_quad(stash, fnt, glyph, isize, &x, &y, &q))
@ -639,24 +658,21 @@ void sth_draw_texture(struct sth_stash* stash,
v = &texture->newverts[texture->nverts];
q.x0 = 0;
q.y0 = 0;
q.x1 = q.x0+width;
q.y1 = q.y0+height;
q.x1 = q.x0 + width;
q.y1 = q.y0 + height;
v = setv(v, q.x0, q.y0, 0,0,(float)screenwidth,(float)screenheight);
v = setv(v, q.x1, q.y0, 1,0,(float)screenwidth,(float)screenheight);
v = setv(v, q.x1, q.y1, 1,1,(float)screenwidth,(float)screenheight);
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);
v = setv(v, q.x1, q.y1, 1,1,(float)screenwidth,(float)screenheight);
v = setv(v, q.x0, q.y1, 0,1,(float)screenwidth,(float)screenheight);
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;
}
@ -667,24 +683,23 @@ void sth_flush_draw(struct sth_stash* 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)
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);
short isize = (short)(size * 10.0f);
Vertex* v;
struct sth_font* fnt = NULL;
s_retinaScale = retinaScale;
s_retinaScale = retinaScale;
if (stash == NULL) return;
if (!stash->textures) return;
fnt = stash->fonts;
while(fnt != NULL && fnt->idx != idx) fnt = fnt->next;
while (fnt != NULL && fnt->idx != idx) fnt = fnt->next;
if (fnt == NULL) return;
if (fnt->type != BMFONT && !fnt->data) return;
@ -696,28 +711,82 @@ void sth_draw_text(struct sth_stash* stash,
if (!glyph) continue;
texture = glyph->texture;
if (!measureOnly)
{
if (texture->nverts+6 >= VERT_COUNT)
flush_draw(stash);
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];
if (!measureOnly)
{
v = &texture->newverts[texture->nverts];
v = setv(v, q.x0, q.y0, q.s0, q.t0,(float)screenwidth,(float)screenheight);
v = setv(v, q.x1, q.y0, q.s1, q.t0,(float)screenwidth,(float)screenheight);
v = setv(v, q.x1, q.y1, q.s1, q.t1,(float)screenwidth,(float)screenheight);
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);
v = setv(v, q.x1, q.y1, q.s1, q.t1,(float)screenwidth,(float)screenheight);
v = setv(v, q.x0, q.y1, q.s0, q.t1,(float)screenwidth,(float)screenheight);
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;
}
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;
@ -732,7 +801,7 @@ void sth_dim_text(struct sth_stash* stash,
struct sth_glyph* glyph = NULL;
unsigned int state = 0;
struct sth_quad q;
short isize = (short)(size*10.0f);
short isize = (short)(size * 10.0f);
struct sth_font* fnt = NULL;
float x = 0, y = 0;
@ -741,7 +810,7 @@ void sth_dim_text(struct sth_stash* stash,
if (!stash->textures)
return;
fnt = stash->fonts;
while(fnt != NULL && fnt->idx != idx) fnt = fnt->next;
while (fnt != NULL && fnt->idx != idx) fnt = fnt->next;
if (fnt == NULL) return;
if (fnt->type != BMFONT && !fnt->data) return;
@ -770,15 +839,15 @@ void sth_vmetrics(struct sth_stash* stash,
if (stash == NULL) return;
if (!stash->textures) return;
fnt = stash->fonts;
while(fnt != NULL && fnt->idx != idx) fnt = fnt->next;
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;
*ascender = fnt->ascender * size;
if (descender)
*descender = fnt->descender*size;
*descender = fnt->descender * size;
if (lineh)
*lineh = fnt->lineh*size;
*lineh = fnt->lineh * size;
}
void sth_delete(struct sth_stash* stash)
@ -791,17 +860,19 @@ void sth_delete(struct sth_stash* stash)
if (!stash) return;
tex = stash->textures;
while(tex != NULL) {
while (tex != NULL)
{
curtex = tex;
delete tex->m_texels;
tex->m_texels=0;
free(tex->m_texels);
tex->m_texels = 0;
tex = tex->next;
stash->m_renderCallbacks->updateTexture(curtex,0,0,0);
stash->m_renderCallbacks->updateTexture(curtex, 0, 0, 0);
free(curtex);
}
fnt = stash->fonts;
while(fnt != NULL) {
while (fnt != NULL)
{
curfnt = fnt;
fnt = fnt->next;
if (curfnt->glyphs)

View file

@ -20,11 +20,9 @@
#ifndef FONTSTASH_H
#define FONTSTASH_H
#define MAX_ROWS 128
#define VERT_COUNT (6*128)
#define INDEX_COUNT (VERT_COUNT*2)
#define VERT_COUNT (16 * 128)
#define INDEX_COUNT (VERT_COUNT * 2)
struct vec2
{
@ -38,34 +36,33 @@ struct vec2
struct vec4
{
vec4(float x,float y, float z, float w)
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;
vec4 position;
vec4 colour;
vec2 uv;
} Vertex;
struct sth_quad
{
float x0,y0,s0,t0;
float x1,y1,s1,t1;
float x0, y0, s0, t0;
float x1, y1, s1, t1;
};
struct sth_row
{
short x,y,h;
short x, y, h;
};
struct sth_glyph
@ -73,37 +70,37 @@ struct sth_glyph
unsigned int codepoint;
short size;
struct sth_texture* texture;
int x0_,y0,x1,y1;
float xadv,xoff,yoff;
int x0_, y0, x1, y1;
float xadv, xoff, yoff;
int next;
};
struct sth_texture
{
union
{
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;
Vertex newverts[VERT_COUNT];
struct sth_texture* next;
};
struct RenderCallbacks
struct RenderCallbacks
{
virtual ~RenderCallbacks() {}
virtual void updateTexture(sth_texture* texture, sth_glyph* glyph, int textureWidth, int textureHeight)=0;
virtual void render(sth_texture* texture)=0;
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);
@ -121,26 +118,37 @@ 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);
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=0, float retinaScale=1);
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);
float* ascender, float* descender, float* lineh);
void sth_delete(struct sth_stash* stash);
#endif // FONTSTASH_H
#endif // FONTSTASH_H

View file

@ -9,18 +9,15 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#include "stb_image/stb_image_write.h"
static unsigned int s_indexData[INDEX_COUNT];
GLuint s_indexArrayObject, s_indexBuffer;
GLuint s_vertexArrayObject,s_vertexBuffer;
static GLuint s_indexArrayObject, s_indexBuffer;
static GLuint s_vertexArrayObject, s_vertexBuffer;
OpenGL2RenderCallbacks::OpenGL2RenderCallbacks(GLPrimitiveRenderer* primRender)
:m_primRender2(primRender)
: m_primRender2(primRender)
{
}
OpenGL2RenderCallbacks::~OpenGL2RenderCallbacks()
{
@ -32,47 +29,50 @@ PrimInternalData* OpenGL2RenderCallbacks::getData()
}
InternalOpenGL2RenderCallbacks::~InternalOpenGL2RenderCallbacks()
{
}
void InternalOpenGL2RenderCallbacks::display2()
void InternalOpenGL2RenderCallbacks::display2()
{
assert(glGetError()==GL_NO_ERROR);
// glViewport(0,0,10,10);
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);
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);
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);
/*
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);
@ -85,103 +85,94 @@ void InternalOpenGL2RenderCallbacks::display2()
assert(err==GL_NO_ERROR);
*/
// glutSwapBuffers();
// glutSwapBuffers();
}
void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_glyph* glyph, int textureWidth, int textureHeight)
{
assert(glGetError()==GL_NO_ERROR);
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;
GLuint* gltexture = (GLuint*)texture->m_userData;
glBindTexture(GL_TEXTURE_2D, *gltexture);
glPixelStorei(GL_UNPACK_ALIGNMENT,1);
assert(glGetError()==GL_NO_ERROR);
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
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);
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);
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);
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++)
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
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;
delete id; //texture->m_userData;
texture->m_userData = 0;
}
}
}
}
void InternalOpenGL2RenderCallbacks::render(sth_texture* texture)
{
display2();
GLuint* texId = (GLuint*) texture->m_userData;
GLuint* texId = (GLuint*)texture->m_userData;
assert(glGetError()==GL_NO_ERROR);
glActiveTexture(GL_TEXTURE0);
assert(glGetError()==GL_NO_ERROR);
assert(glGetError() == GL_NO_ERROR);
glActiveTexture(GL_TEXTURE0);
assert(glGetError() == GL_NO_ERROR);
glBindTexture(GL_TEXTURE_2D, *texId);
bool useFiltering = false;
@ -189,66 +180,63 @@ void InternalOpenGL2RenderCallbacks::render(sth_texture* texture)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
} else
}
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_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);
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);
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);
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++)
for (int j = 0; j < textureHeight; j++)
{
pixels[j*textureWidth+j]=255;
pixels[j * textureWidth + j] = 255;
}
if (0)
{
for (int j=0;j<textureHeight/2;j++)
for (int j = 0; j < textureHeight / 2; j++)
{
for (int i=0;i<textureWidth;i++)
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];
}
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);
int comp = 1; //1=Y
stbi_write_png(fileName, textureWidth, textureHeight, comp, pixels, textureWidth);
free(pixels);
}
#endif

View file

@ -5,21 +5,19 @@
struct PrimInternalData;
class GLPrimitiveRenderer;
struct InternalOpenGL2RenderCallbacks : public RenderCallbacks
struct InternalOpenGL2RenderCallbacks : public RenderCallbacks
{
virtual PrimInternalData* getData()=0;
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);
void dumpTextureToPng(int screenWidth, int screenHeight, const char* fileName);
struct SimpleOpenGL2RenderCallbacks : public InternalOpenGL2RenderCallbacks
{
@ -29,7 +27,7 @@ struct SimpleOpenGL2RenderCallbacks : public InternalOpenGL2RenderCallbacks
return m_data;
}
SimpleOpenGL2RenderCallbacks(PrimInternalData* data)
:m_data(data)
: m_data(data)
{
}
virtual ~SimpleOpenGL2RenderCallbacks()
@ -37,19 +35,17 @@ struct SimpleOpenGL2RenderCallbacks : public InternalOpenGL2RenderCallbacks
}
};
struct OpenGL2RenderCallbacks : public InternalOpenGL2RenderCallbacks
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
#endif //_OPENGL_FONTSTASH_CALLBACKS_H

View file

@ -9,10 +9,14 @@
initGlew()
includedirs {
"../ThirdPartyLibs",
"../../src",
}
if os.is("Linux") then
buildoptions{"-fPIC"}
end
--links {
--}
@ -21,9 +25,12 @@
"*.h",
"OpenGLWindow/*.c",
"OpenGLWindow/*.h",
"OpenGLWindow/GL/*.h"
"OpenGLWindow/GL/*.h",
"../ThirdPartyLibs/stb_image/stb_image_write.cpp",
}
if not os.is("Windows") then
excludes {
"Win32OpenGLWindow.cpp",
@ -41,10 +48,17 @@
"X11OpenGLWindows.h"
}
end
if not os.is("MacoSX") then
excludes {
"MacOpenGLWindow.cpp"
}
end
if os.is("MacOSX") then
files
{
"../OpenGLWindow/MacOpenGLWindow.h",
"../OpenGLWindow/MacOpenGLWindow.mm",
"MacOpenGLWindow.h",
"MacOpenGLWindow.cpp",
"MacOpenGLWindowObjC.m",
"MacOpenGLWindowObjC.h",
}
end

View file

@ -1,514 +0,0 @@
/* stbiw-0.92 - public domain - http://nothings.org/stb/stb_image_write.h
writes out PNG/BMP/TGA images to C stdio - Sean Barrett 2010
no warranty implied; use at your own risk
Before including,
#define STB_IMAGE_WRITE_IMPLEMENTATION
in the file that you want to have the implementation.
ABOUT:
This header file is a library for writing images to C stdio. It could be
adapted to write to memory or a general streaming interface; let me know.
The PNG output is not optimal; it is 20-50% larger than the file
written by a decent optimizing implementation. This library is designed
for source code compactness and simplicitly, not optimal image file size
or run-time performance.
USAGE:
There are three functions, one for each image file format:
int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes);
int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data);
int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data);
Each function returns 0 on failure and non-0 on success.
The functions create an image file defined by the parameters. The image
is a rectangle of pixels stored from left-to-right, top-to-bottom.
Each pixel contains 'comp' channels of data stored interleaved with 8-bits
per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is
monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall.
The *data pointer points to the first byte of the top-left-most pixel.
For PNG, "stride_in_bytes" is the distance in bytes from the first byte of
a row of pixels to the first byte of the next row of pixels.
PNG creates output files with the same number of components as the input.
The BMP and TGA formats expand Y to RGB in the file format. BMP does not
output alpha.
PNG supports writing rectangles of data even when the bytes storing rows of
data are not consecutive in memory (e.g. sub-rectangles of a larger image),
by supplying the stride between the beginning of adjacent rows. The other
formats do not. (Thus you cannot write a native-format BMP through the BMP
writer, both because it is in BGR order and because it may have padding
at the end of the line.)
*/
#ifndef INCLUDE_STB_IMAGE_WRITE_H
#define INCLUDE_STB_IMAGE_WRITE_H
#ifdef __cplusplus
extern "C" {
#endif
extern int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes);
extern int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data);
extern int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data);
#ifdef __cplusplus
}
#endif
#endif//INCLUDE_STB_IMAGE_WRITE_H
#ifdef STB_IMAGE_WRITE_IMPLEMENTATION
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
typedef unsigned int stbiw_uint32;
typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1];
static void writefv(FILE *f, const char *fmt, va_list v)
{
while (*fmt) {
switch (*fmt++) {
case ' ': break;
case '1': { unsigned char x = (unsigned char) va_arg(v, int); fputc(x,f); break; }
case '2': { int x = va_arg(v,int); unsigned char b[2];
b[0] = (unsigned char) x; b[1] = (unsigned char) (x>>8);
fwrite(b,2,1,f); break; }
case '4': { stbiw_uint32 x = va_arg(v,int); unsigned char b[4];
b[0]=(unsigned char)x; b[1]=(unsigned char)(x>>8);
b[2]=(unsigned char)(x>>16); b[3]=(unsigned char)(x>>24);
fwrite(b,4,1,f); break; }
default:
assert(0);
return;
}
}
}
static void write3(FILE *f, unsigned char a, unsigned char b, unsigned char c)
{
unsigned char arr[3];
arr[0] = a, arr[1] = b, arr[2] = c;
fwrite(arr, 3, 1, f);
}
static void write_pixels(FILE *f, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad)
{
unsigned char bg[3] = { 255, 0, 255}, px[3];
stbiw_uint32 zero = 0;
int i,j,k, j_end;
if (y <= 0)
return;
if (vdir < 0)
j_end = -1, j = y-1;
else
j_end = y, j = 0;
for (; j != j_end; j += vdir) {
for (i=0; i < x; ++i) {
unsigned char *d = (unsigned char *) data + (j*x+i)*comp;
if (write_alpha < 0)
fwrite(&d[comp-1], 1, 1, f);
switch (comp) {
case 1:
case 2: write3(f, d[0],d[0],d[0]);
break;
case 4:
if (!write_alpha) {
// composite against pink background
for (k=0; k < 3; ++k)
px[k] = bg[k] + ((d[k] - bg[k]) * d[3])/255;
write3(f, px[1-rgb_dir],px[1],px[1+rgb_dir]);
break;
}
/* FALLTHROUGH */
case 3:
write3(f, d[1-rgb_dir],d[1],d[1+rgb_dir]);
break;
}
if (write_alpha > 0)
fwrite(&d[comp-1], 1, 1, f);
}
fwrite(&zero,scanline_pad,1,f);
}
}
static int outfile(char const *filename, int rgb_dir, int vdir, int x, int y, int comp, void *data, int alpha, int pad, const char *fmt, ...)
{
FILE *f;
if (y < 0 || x < 0) return 0;
f = fopen(filename, "wb");
if (f) {
va_list v;
va_start(v, fmt);
writefv(f, fmt, v);
va_end(v);
write_pixels(f,rgb_dir,vdir,x,y,comp,data,alpha,pad);
fclose(f);
}
return f != NULL;
}
int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data)
{
int pad = (-x*3) & 3;
return outfile(filename,-1,-1,x,y,comp,(void *) data,0,pad,
"11 4 22 4" "4 44 22 444444",
'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header
40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header
}
int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data)
{
int has_alpha = !(comp & 1);
return outfile(filename, -1,-1, x, y, comp, (void *) data, has_alpha, 0,
"111 221 2222 11", 0,0,2, 0,0,0, 0,0,x,y, 24+8*has_alpha, 8*has_alpha);
}
// stretchy buffer; stbi__sbpush() == vector<>::push_back() -- stbi__sbcount() == vector<>::size()
#define stbi__sbraw(a) ((int *) (a) - 2)
#define stbi__sbm(a) stbi__sbraw(a)[0]
#define stbi__sbn(a) stbi__sbraw(a)[1]
#define stbi__sbneedgrow(a,n) ((a)==0 || stbi__sbn(a)+n >= stbi__sbm(a))
#define stbi__sbmaybegrow(a,n) (stbi__sbneedgrow(a,(n)) ? stbi__sbgrow(a,n) : 0)
#define stbi__sbgrow(a,n) stbi__sbgrowf((void **) &(a), (n), sizeof(*(a)))
#define stbi__sbpush(a, v) (stbi__sbmaybegrow(a,1), (a)[stbi__sbn(a)++] = (v))
#define stbi__sbcount(a) ((a) ? stbi__sbn(a) : 0)
#define stbi__sbfree(a) ((a) ? free(stbi__sbraw(a)),0 : 0)
static void *stbi__sbgrowf(void **arr, int increment, int itemsize)
{
int m = *arr ? 2*stbi__sbm(*arr)+increment : increment+1;
void *p = realloc(*arr ? stbi__sbraw(*arr) : 0, itemsize * m + sizeof(int)*2);
assert(p);
if (p) {
if (!*arr) ((int *) p)[1] = 0;
*arr = (void *) ((int *) p + 2);
stbi__sbm(*arr) = m;
}
return *arr;
}
static unsigned char *stbi__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount)
{
while (*bitcount >= 8) {
stbi__sbpush(data, (unsigned char) *bitbuffer);
*bitbuffer >>= 8;
*bitcount -= 8;
}
return data;
}
static int stbi__zlib_bitrev(int code, int codebits)
{
int res=0;
while (codebits--) {
res = (res << 1) | (code & 1);
code >>= 1;
}
return res;
}
static unsigned int stbi__zlib_countm(unsigned char *a, unsigned char *b, int limit)
{
int i;
for (i=0; i < limit && i < 258; ++i)
if (a[i] != b[i]) break;
return i;
}
static unsigned int stbi__zhash(unsigned char *data)
{
stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16);
hash ^= hash << 3;
hash += hash >> 5;
hash ^= hash << 4;
hash += hash >> 17;
hash ^= hash << 25;
hash += hash >> 6;
return hash;
}
#define stbi__zlib_flush() (out = stbi__zlib_flushf(out, &bitbuf, &bitcount))
#define stbi__zlib_add(code,codebits) \
(bitbuf |= (code) << bitcount, bitcount += (codebits), stbi__zlib_flush())
#define stbi__zlib_huffa(b,c) stbi__zlib_add(stbi__zlib_bitrev(b,c),c)
// default huffman tables
#define stbi__zlib_huff1(n) stbi__zlib_huffa(0x30 + (n), 8)
#define stbi__zlib_huff2(n) stbi__zlib_huffa(0x190 + (n)-144, 9)
#define stbi__zlib_huff3(n) stbi__zlib_huffa(0 + (n)-256,7)
#define stbi__zlib_huff4(n) stbi__zlib_huffa(0xc0 + (n)-280,8)
#define stbi__zlib_huff(n) ((n) <= 143 ? stbi__zlib_huff1(n) : (n) <= 255 ? stbi__zlib_huff2(n) : (n) <= 279 ? stbi__zlib_huff3(n) : stbi__zlib_huff4(n))
#define stbi__zlib_huffb(n) ((n) <= 143 ? stbi__zlib_huff1(n) : stbi__zlib_huff2(n))
#define stbi__ZHASH 16384
unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality)
{
static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 };
static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 };
static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 };
static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 };
unsigned int bitbuf=0;
int i,j, bitcount=0;
unsigned char *out = NULL;
unsigned char **hash_table[stbi__ZHASH]; // 64KB on the stack!
if (quality < 5) quality = 5;
stbi__sbpush(out, 0x78); // DEFLATE 32K window
stbi__sbpush(out, 0x5e); // FLEVEL = 1
stbi__zlib_add(1,1); // BFINAL = 1
stbi__zlib_add(1,2); // B3YPE = 1 -- fixed huffman
for (i=0; i < stbi__ZHASH; ++i)
hash_table[i] = NULL;
i=0;
while (i < data_len-3) {
// hash next 3 bytes of data to be compressed
int h = stbi__zhash(data+i)&(stbi__ZHASH-1), best=3;
unsigned char *bestloc = 0;
unsigned char **hlist = hash_table[h];
int n = stbi__sbcount(hlist);
for (j=0; j < n; ++j) {
if (hlist[j]-data > i-32768) { // if entry lies within window
int d = stbi__zlib_countm(hlist[j], data+i, data_len-i);
if (d >= best) best=d,bestloc=hlist[j];
}
}
// when hash table entry is too long, delete half the entries
if (hash_table[h] && stbi__sbn(hash_table[h]) == 2*quality) {
memcpy(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality);
stbi__sbn(hash_table[h]) = quality;
}
stbi__sbpush(hash_table[h],data+i);
if (bestloc) {
// "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal
h = stbi__zhash(data+i+1)&(stbi__ZHASH-1);
hlist = hash_table[h];
n = stbi__sbcount(hlist);
for (j=0; j < n; ++j) {
if (hlist[j]-data > i-32767) {
int e = stbi__zlib_countm(hlist[j], data+i+1, data_len-i-1);
if (e > best) { // if next match is better, bail on current match
bestloc = NULL;
break;
}
}
}
}
if (bestloc) {
int d = data+i - bestloc; // distance back
assert(d <= 32767 && best <= 258);
for (j=0; best > lengthc[j+1]-1; ++j);
stbi__zlib_huff(j+257);
if (lengtheb[j]) stbi__zlib_add(best - lengthc[j], lengtheb[j]);
for (j=0; d > distc[j+1]-1; ++j);
stbi__zlib_add(stbi__zlib_bitrev(j,5),5);
if (disteb[j]) stbi__zlib_add(d - distc[j], disteb[j]);
i += best;
} else {
stbi__zlib_huffb(data[i]);
++i;
}
}
// write out final bytes
for (;i < data_len; ++i)
stbi__zlib_huffb(data[i]);
stbi__zlib_huff(256); // end of block
// pad with 0 bits to byte boundary
while (bitcount)
stbi__zlib_add(0,1);
for (i=0; i < stbi__ZHASH; ++i)
(void) stbi__sbfree(hash_table[i]);
{
// compute adler32 on input
unsigned int i=0, s1=1, s2=0, blocklen = data_len % 5552;
int j=0;
while (j < data_len) {
for (i=0; i < blocklen; ++i) s1 += data[j+i], s2 += s1;
s1 %= 65521, s2 %= 65521;
j += blocklen;
blocklen = 5552;
}
stbi__sbpush(out, (unsigned char) (s2 >> 8));
stbi__sbpush(out, (unsigned char) s2);
stbi__sbpush(out, (unsigned char) (s1 >> 8));
stbi__sbpush(out, (unsigned char) s1);
}
*out_len = stbi__sbn(out);
// make returned pointer freeable
memmove(stbi__sbraw(out), out, *out_len);
return (unsigned char *) stbi__sbraw(out);
}
unsigned int stbi__crc32(unsigned char *buffer, int len)
{
static unsigned int crc_table[256];
unsigned int crc = ~0u;
int i,j;
if (crc_table[1] == 0)
for(i=0; i < 256; i++)
for (crc_table[i]=i, j=0; j < 8; ++j)
crc_table[i] = (crc_table[i] >> 1) ^ (crc_table[i] & 1 ? 0xedb88320 : 0);
for (i=0; i < len; ++i)
crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];
return ~crc;
}
#define stbi__wpng4(o,a,b,c,d) ((o)[0]=(unsigned char)(a),(o)[1]=(unsigned char)(b),(o)[2]=(unsigned char)(c),(o)[3]=(unsigned char)(d),(o)+=4)
#define stbi__wp32(data,v) stbi__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v));
#define stbi__wptag(data,s) stbi__wpng4(data, s[0],s[1],s[2],s[3])
static void stbi__wpcrc(unsigned char **data, int len)
{
unsigned int crc = stbi__crc32(*data - len - 4, len+4);
stbi__wp32(*data, crc);
}
static unsigned char stbi__paeth(int a, int b, int c)
{
int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c);
if (pa <= pb && pa <= pc) return (unsigned char) a;
if (pb <= pc) return (unsigned char) b;
return (unsigned char) c;
}
unsigned char *stbi_write_png_to_mem(unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len)
{
int ctype[5] = { -1, 0, 4, 2, 6 };
unsigned char sig[8] = { 137,80,78,71,13,10,26,10 };
unsigned char *out,*o, *filt, *zlib;
signed char *line_buffer;
int i,j,k,p,zlen;
if (stride_bytes == 0)
stride_bytes = x * n;
filt = (unsigned char *) malloc((x*n+1) * y); if (!filt) return 0;
line_buffer = (signed char *) malloc(x * n); if (!line_buffer) { free(filt); return 0; }
for (j=0; j < y; ++j) {
static int mapping[] = { 0,1,2,3,4 };
static int firstmap[] = { 0,1,0,5,6 };
int *mymap = j ? mapping : firstmap;
int best = 0, bestval = 0x7fffffff;
for (p=0; p < 2; ++p) {
for (k= p?best:0; k < 5; ++k) {
int type = mymap[k],est=0;
unsigned char *z = pixels + stride_bytes*j;
for (i=0; i < n; ++i)
switch (type) {
case 0: line_buffer[i] = z[i]; break;
case 1: line_buffer[i] = z[i]; break;
case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break;
case 3: line_buffer[i] = z[i] - (z[i-stride_bytes]>>1); break;
case 4: line_buffer[i] = (signed char) (z[i] - stbi__paeth(0,z[i-stride_bytes],0)); break;
case 5: line_buffer[i] = z[i]; break;
case 6: line_buffer[i] = z[i]; break;
}
for (i=n; i < x*n; ++i) {
switch (type) {
case 0: line_buffer[i] = z[i]; break;
case 1: line_buffer[i] = z[i] - z[i-n]; break;
case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break;
case 3: line_buffer[i] = z[i] - ((z[i-n] + z[i-stride_bytes])>>1); break;
case 4: line_buffer[i] = z[i] - stbi__paeth(z[i-n], z[i-stride_bytes], z[i-stride_bytes-n]); break;
case 5: line_buffer[i] = z[i] - (z[i-n]>>1); break;
case 6: line_buffer[i] = z[i] - stbi__paeth(z[i-n], 0,0); break;
}
}
if (p) break;
for (i=0; i < x*n; ++i)
est += abs((signed char) line_buffer[i]);
if (est < bestval) { bestval = est; best = k; }
}
}
// when we get here, best contains the filter type, and line_buffer contains the data
filt[j*(x*n+1)] = (unsigned char) best;
memcpy(filt+j*(x*n+1)+1, line_buffer, x*n);
}
free(line_buffer);
zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, 8); // increase 8 to get smaller but use more memory
free(filt);
if (!zlib) return 0;
// each tag requires 12 bytes of overhead
out = (unsigned char *) malloc(8 + 12+13 + 12+zlen + 12);
if (!out) return 0;
*out_len = 8 + 12+13 + 12+zlen + 12;
o=out;
memcpy(o,sig,8); o+= 8;
stbi__wp32(o, 13); // header length
stbi__wptag(o, "IHDR");
stbi__wp32(o, x);
stbi__wp32(o, y);
*o++ = 8;
*o++ = (unsigned char) ctype[n];
*o++ = 0;
*o++ = 0;
*o++ = 0;
stbi__wpcrc(&o,13);
stbi__wp32(o, zlen);
stbi__wptag(o, "IDAT");
memcpy(o, zlib, zlen); o += zlen; free(zlib);
stbi__wpcrc(&o, zlen);
stbi__wp32(o,0);
stbi__wptag(o, "IEND");
stbi__wpcrc(&o,0);
assert(o == out + *out_len);
return out;
}
int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes)
{
FILE *f;
int len;
unsigned char *png = stbi_write_png_to_mem((unsigned char *) data, stride_bytes, x, y, comp, &len);
if (!png) return 0;
f = fopen(filename, "wb");
if (!f) {
free(png);
return 0;
}
fwrite(png, 1, len, f);
fclose(f);
free(png);
return 1;
}
#endif // STB_IMAGE_WRITE_IMPLEMENTATION
/* Revision history
0.92 (2010-08-01)
casts to unsigned char to fix warnings
0.91 (2010-07-17)
first public release
0.90 first internal release
*/

File diff suppressed because it is too large Load diff