-
-
Save realazthat/54c84cbe72fda63e6b85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
----------------------------------------------------------------------------- | |
Filename: BaseApplication.cpp | |
----------------------------------------------------------------------------- | |
This source file is part of the | |
___ __ __ _ _ _ | |
/___\__ _ _ __ ___ / / /\ \ (_) | _(_) | |
// // _` | '__/ _ \ \ \/ \/ / | |/ / | | |
/ \_// (_| | | | __/ \ /\ /| | <| | | |
\___/ \__, |_| \___| \/ \/ |_|_|\_\_| | |
|___/ | |
Tutorial Framework | |
http://www.ogre3d.org/tikiwiki/ | |
----------------------------------------------------------------------------- | |
*/ | |
#include "BaseApplication.h" | |
//------------------------------------------------------------------------------------- | |
BaseApplication::BaseApplication(void) | |
: mRoot(0), | |
mViewport(0), | |
mCamera(0), | |
mSceneMgr(0), | |
mWindow(0), | |
mResourcesCfg(Ogre::StringUtil::BLANK), | |
mPluginsCfg(Ogre::StringUtil::BLANK), | |
mTrayMgr(0), | |
mCameraMan(0), | |
mDetailsPanel(0), | |
mCursorWasVisible(false), | |
mShutDown(false), | |
mInputManager(0), | |
mMouse(0), | |
mKeyboard(0) | |
{ | |
} | |
//------------------------------------------------------------------------------------- | |
BaseApplication::~BaseApplication(void) | |
{ | |
if (mTrayMgr) delete mTrayMgr; | |
if (mCameraMan) delete mCameraMan; | |
//Remove ourself as a Window listener | |
Ogre::WindowEventUtilities::removeWindowEventListener(mWindow, this); | |
windowClosed(mWindow); | |
delete mRoot; | |
} | |
bool BaseApplication::configure_plugins() | |
{ | |
return true; | |
} | |
//------------------------------------------------------------------------------------- | |
bool BaseApplication::configure(void) | |
{ | |
// Show the configuration dialog and initialise the system | |
// You can skip this and use root.restoreConfig() to load configuration | |
// settings if you were sure there are valid ones saved in ogre.cfg | |
if(mRoot->showConfigDialog()) | |
{ | |
// If returned true, user clicked OK so initialise | |
// Here we choose to let the system create a default rendering window by passing 'true' | |
mWindow = mRoot->initialise(true, "TutorialApplication Render Window"); | |
return true; | |
} | |
else | |
{ | |
return false; | |
} | |
} | |
//------------------------------------------------------------------------------------- | |
void BaseApplication::chooseSceneManager(void) | |
{ | |
// Get the SceneManager, in this case a generic one | |
mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC); | |
if (!mSceneMgr) | |
throw std::runtime_error("Unable to create scene manager"); | |
} | |
//------------------------------------------------------------------------------------- | |
void BaseApplication::createCamera(void) | |
{ | |
// Create the camera | |
mCamera = mSceneMgr->createCamera("PlayerCam"); | |
// Position it at 500 in Z direction | |
mCamera->setPosition(Ogre::Vector3(0,0,80)); | |
// Look back along -Z | |
mCamera->lookAt(Ogre::Vector3(0,0,-300)); | |
mCamera->setNearClipDistance(.1); | |
mCameraMan = new OgreBites::SdkCameraMan(mCamera); // create a default camera controller | |
} | |
//------------------------------------------------------------------------------------- | |
void BaseApplication::createInputDevices() | |
{ | |
Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***"); | |
OIS::ParamList pl; | |
size_t windowHnd = 0; | |
std::ostringstream windowHndStr; | |
mWindow->getCustomAttribute("WINDOW", &windowHnd); | |
windowHndStr << windowHnd; | |
pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str())); | |
#if defined OIS_WIN32_PLATFORM | |
pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND" ))); | |
pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE"))); | |
pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_FOREGROUND"))); | |
pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_NONEXCLUSIVE"))); | |
#elif defined OIS_LINUX_PLATFORM | |
pl.insert(std::make_pair(std::string("x11_mouse_grab"), std::string("false"))); | |
pl.insert(std::make_pair(std::string("x11_mouse_hide"), std::string("false"))); | |
//pl.insert(std::make_pair(std::string("x11_keyboard_grab"), std::string("false"))); | |
pl.insert(std::make_pair(std::string("XAutoRepeatOn"), std::string("true"))); | |
#endif | |
mInputManager = OIS::InputManager::createInputSystem( pl ); | |
mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true )); | |
mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true )); | |
mMouse->setEventCallback(this); | |
mKeyboard->setEventCallback(this); | |
} | |
//------------------------------------------------------------------------------------- | |
void BaseApplication::createFrameListener(void) | |
{ | |
//Set initial mouse clipping size | |
windowResized(mWindow); | |
//Register as a Window listener | |
Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this); | |
#ifndef __native_client__ | |
mTrayMgr = new OgreBites::SdkTrayManager("InterfaceName", mWindow, mMouse, this); | |
mTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT); | |
mTrayMgr->showLogo(OgreBites::TL_BOTTOMRIGHT); | |
mTrayMgr->hideCursor(); | |
// create a params panel for displaying sample details | |
Ogre::StringVector items; | |
items.push_back("cam.pX"); | |
items.push_back("cam.pY"); | |
items.push_back("cam.pZ"); | |
items.push_back(""); | |
items.push_back("cam.oW"); | |
items.push_back("cam.oX"); | |
items.push_back("cam.oY"); | |
items.push_back("cam.oZ"); | |
items.push_back(""); | |
items.push_back("Filtering"); | |
items.push_back("Poly Mode"); | |
mDetailsPanel = mTrayMgr->createParamsPanel(OgreBites::TL_NONE, "DetailsPanel", 200, items); | |
mDetailsPanel->setParamValue(9, "Bilinear"); | |
mDetailsPanel->setParamValue(10, "Solid"); | |
mDetailsPanel->hide(); | |
#endif | |
mRoot->addFrameListener(this); | |
} | |
//------------------------------------------------------------------------------------- | |
void BaseApplication::destroyScene(void) | |
{ | |
} | |
//------------------------------------------------------------------------------------- | |
void BaseApplication::createViewports(void) | |
{ | |
// Create one viewport, entire window | |
mViewport = mWindow->addViewport(mCamera); | |
mViewport->setBackgroundColour(Ogre::ColourValue(0,0,0)); | |
mViewport->setClearEveryFrame(true); | |
// Alter the camera aspect ratio to match the viewport | |
mCamera->setAspectRatio( | |
Ogre::Real(mViewport->getActualWidth()) / Ogre::Real(mViewport->getActualHeight())); | |
} | |
//------------------------------------------------------------------------------------- | |
void BaseApplication::setupResources(void) | |
{ | |
if (mResourcesCfg.empty()) | |
return; | |
// Load resource paths from config file | |
Ogre::ConfigFile cf; | |
cf.load(mResourcesCfg); | |
// Go through all sections & settings in the file | |
Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); | |
Ogre::String secName, typeName, archName; | |
while (seci.hasMoreElements()) | |
{ | |
secName = seci.peekNextKey(); | |
Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext(); | |
Ogre::ConfigFile::SettingsMultiMap::iterator i; | |
for (i = settings->begin(); i != settings->end(); ++i) | |
{ | |
typeName = i->first; | |
archName = i->second; | |
Ogre::ResourceGroupManager::getSingleton().addResourceLocation( | |
archName, typeName, secName); | |
} | |
} | |
} | |
//------------------------------------------------------------------------------------- | |
void BaseApplication::createResourceListener(void) | |
{ | |
} | |
//------------------------------------------------------------------------------------- | |
void BaseApplication::loadResources(void) | |
{ | |
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); | |
} | |
//------------------------------------------------------------------------------------- | |
#ifndef __native_client__ | |
void BaseApplication::go(void) | |
{ | |
mResourcesCfg = "resources.cfg"; | |
mPluginsCfg = "plugins.cfg"; | |
if (!setup()) | |
return; | |
mRoot->startRendering(); | |
// clean up | |
destroyScene(); | |
} | |
#else // #ifndef __native_client__ | |
bool BaseApplication::load_nacl() | |
{ | |
mResourcesCfg = ""; | |
mPluginsCfg = ""; | |
return setup(); | |
} | |
#endif // #ifndef __native_client__ | |
//------------------------------------------------------------------------------------- | |
bool BaseApplication::setup(void) | |
{ | |
mRoot = new Ogre::Root(mPluginsCfg); | |
if (!configure_plugins()) | |
return false; | |
//mRoot->getRenderSystem()->_initRenderTargets(); | |
setupResources(); | |
if (!configure()) | |
return false; | |
chooseSceneManager(); | |
createCamera(); | |
createViewports(); | |
// Set default mipmap level (NB some APIs ignore this) | |
Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5); | |
// Create any resource listeners (for loading screens) | |
createResourceListener(); | |
// Load resources | |
loadResources(); | |
createInputDevices(); | |
// Create the scene | |
createScene(); | |
createFrameListener(); | |
return true; | |
} | |
//------------------------------------------------------------------------------------- | |
bool BaseApplication::frameRenderingQueued(const Ogre::FrameEvent& evt) | |
{ | |
if(mWindow->isClosed()) | |
return false; | |
if(mShutDown) | |
return false; | |
//Need to capture/update each device | |
mKeyboard->capture(); | |
mMouse->capture(); | |
#ifndef __native_client__ | |
mTrayMgr->frameRenderingQueued(evt); | |
if (!mTrayMgr->isDialogVisible()) | |
{ | |
mCameraMan->frameRenderingQueued(evt); // if dialog isn't up, then update the camera | |
if (mDetailsPanel->isVisible()) // if details panel is visible, then update its contents | |
{ | |
mDetailsPanel->setParamValue(0, Ogre::StringConverter::toString(mCamera->getDerivedPosition().x)); | |
mDetailsPanel->setParamValue(1, Ogre::StringConverter::toString(mCamera->getDerivedPosition().y)); | |
mDetailsPanel->setParamValue(2, Ogre::StringConverter::toString(mCamera->getDerivedPosition().z)); | |
mDetailsPanel->setParamValue(4, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().w)); | |
mDetailsPanel->setParamValue(5, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().x)); | |
mDetailsPanel->setParamValue(6, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().y)); | |
mDetailsPanel->setParamValue(7, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().z)); | |
} | |
} | |
#endif | |
return true; | |
} | |
//------------------------------------------------------------------------------------- | |
bool BaseApplication::keyPressed( const OIS::KeyEvent &arg ) | |
{ | |
#ifndef __native_client__ | |
if (mTrayMgr->isDialogVisible()) return true; // don't process any more keys if dialog is up | |
if (arg.key == OIS::KC_F) // toggle visibility of advanced frame stats | |
{ | |
mTrayMgr->toggleAdvancedFrameStats(); | |
} | |
else if (arg.key == OIS::KC_G) // toggle visibility of even rarer debugging details | |
{ | |
if (mDetailsPanel->getTrayLocation() == OgreBites::TL_NONE) | |
{ | |
mTrayMgr->moveWidgetToTray(mDetailsPanel, OgreBites::TL_TOPRIGHT, 0); | |
mDetailsPanel->show(); | |
} | |
else | |
{ | |
mTrayMgr->removeWidgetFromTray(mDetailsPanel); | |
mDetailsPanel->hide(); | |
} | |
} else if (arg.key == OIS::KC_T) // cycle polygon rendering mode | |
{ | |
Ogre::String newVal; | |
Ogre::TextureFilterOptions tfo; | |
unsigned int aniso; | |
switch (mDetailsPanel->getParamValue(9).asUTF8()[0]) | |
{ | |
case 'B': | |
newVal = "Trilinear"; | |
tfo = Ogre::TFO_TRILINEAR; | |
aniso = 1; | |
break; | |
case 'T': | |
newVal = "Anisotropic"; | |
tfo = Ogre::TFO_ANISOTROPIC; | |
aniso = 8; | |
break; | |
case 'A': | |
newVal = "None"; | |
tfo = Ogre::TFO_NONE; | |
aniso = 1; | |
break; | |
default: | |
newVal = "Bilinear"; | |
tfo = Ogre::TFO_BILINEAR; | |
aniso = 1; | |
} | |
Ogre::MaterialManager::getSingleton().setDefaultTextureFiltering(tfo); | |
Ogre::MaterialManager::getSingleton().setDefaultAnisotropy(aniso); | |
mDetailsPanel->setParamValue(9, newVal); | |
} | |
#endif // #ifndef __native_client__ | |
if (arg.key == OIS::KC_R) // cycle polygon rendering mode | |
{ | |
Ogre::String newVal; | |
Ogre::PolygonMode pm; | |
switch (mCamera->getPolygonMode()) | |
{ | |
case Ogre::PM_SOLID: | |
newVal = "Wireframe"; | |
pm = Ogre::PM_WIREFRAME; | |
break; | |
case Ogre::PM_WIREFRAME: | |
newVal = "Points"; | |
pm = Ogre::PM_POINTS; | |
break; | |
default: | |
newVal = "Solid"; | |
pm = Ogre::PM_SOLID; | |
} | |
mCamera->setPolygonMode(pm); | |
mDetailsPanel->setParamValue(10, newVal); | |
} | |
else if(arg.key == OIS::KC_F5) // refresh all textures | |
{ | |
Ogre::TextureManager::getSingleton().reloadAll(); | |
} | |
else if (arg.key == OIS::KC_SYSRQ) // take a screenshot | |
{ | |
mWindow->writeContentsToTimestampedFile("screenshot", ".jpg"); | |
} | |
else if (arg.key == OIS::KC_ESCAPE) | |
{ | |
mShutDown = true; | |
} | |
mCameraMan->injectKeyDown(arg); | |
return true; | |
} | |
bool BaseApplication::keyReleased( const OIS::KeyEvent &arg ) | |
{ | |
mCameraMan->injectKeyUp(arg); | |
return true; | |
} | |
bool BaseApplication::mouseMoved( const OIS::MouseEvent &arg ) | |
{ | |
#ifndef __native_client__ | |
if (mTrayMgr->injectMouseMove(arg)) return true; | |
#endif // #ifndef __native_client__ | |
mCameraMan->injectMouseMove(arg); | |
return true; | |
} | |
bool BaseApplication::mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id ) | |
{ | |
#ifndef __native_client__ | |
if (mTrayMgr->injectMouseDown(arg, id)) return true; | |
#endif // #ifndef __native_client__ | |
mCameraMan->injectMouseDown(arg, id); | |
return true; | |
} | |
bool BaseApplication::mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id ) | |
{ | |
#ifndef __native_client__ | |
if (mTrayMgr->injectMouseUp(arg, id)) return true; | |
#endif // #ifndef __native_client__ | |
mCameraMan->injectMouseUp(arg, id); | |
return true; | |
} | |
//Adjust mouse clipping area | |
void BaseApplication::windowResized(Ogre::RenderWindow* rw) | |
{ | |
unsigned int width, height, depth; | |
int left, top; | |
rw->getMetrics(width, height, depth, left, top); | |
const OIS::MouseState &ms = mMouse->getMouseState(); | |
ms.width = width; | |
ms.height = height; | |
} | |
//Unattach OIS before window shutdown (very important under Linux) | |
void BaseApplication::windowClosed(Ogre::RenderWindow* rw) | |
{ | |
//Only close for window that created OIS (the main window in these demos) | |
if( rw == mWindow ) | |
{ | |
if( mInputManager ) | |
{ | |
mInputManager->destroyInputObject( mMouse ); | |
mInputManager->destroyInputObject( mKeyboard ); | |
OIS::InputManager::destroyInputSystem(mInputManager); | |
mInputManager = 0; | |
} | |
} | |
} | |
Ogre::RenderWindow& BaseApplication::renderWindow() | |
{ | |
if (!mWindow) | |
throw std::runtime_error("renderWindow() called, but invalid mWindow"); | |
return *mWindow; | |
} | |
Ogre::Root& BaseApplication::root() | |
{ | |
if (!mRoot) | |
throw std::runtime_error("root() called, but invalid mRoot"); | |
return *mRoot; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
----------------------------------------------------------------------------- | |
Filename: BaseApplication.h | |
----------------------------------------------------------------------------- | |
This source file is part of the | |
___ __ __ _ _ _ | |
/___\__ _ _ __ ___ / / /\ \ (_) | _(_) | |
// // _` | '__/ _ \ \ \/ \/ / | |/ / | | |
/ \_// (_| | | | __/ \ /\ /| | <| | | |
\___/ \__, |_| \___| \/ \/ |_|_|\_\_| | |
|___/ | |
Tutorial Framework | |
http://www.ogre3d.org/tikiwiki/ | |
----------------------------------------------------------------------------- | |
*/ | |
#ifndef __BaseApplication_h_ | |
#define __BaseApplication_h_ | |
#include <OGRE/OgreCamera.h> | |
#include <OGRE/OgreEntity.h> | |
#include <OGRE/OgreLogManager.h> | |
#include <OGRE/OgreRoot.h> | |
#include <OGRE/OgreViewport.h> | |
#include <OGRE/OgreSceneManager.h> | |
#include <OGRE/OgreRenderWindow.h> | |
#include <OGRE/OgreConfigFile.h> | |
#include <OIS/OISEffect.h> | |
#include <OIS/OISInputManager.h> | |
#include <OIS/OISKeyboard.h> | |
#include <OIS/OISMouse.h> | |
#include <OGRE/SdkTrays.h> | |
#include <OGRE/SdkCameraMan.h> | |
class BaseApplication : public Ogre::FrameListener, public Ogre::WindowEventListener, public OIS::KeyListener, public OIS::MouseListener, OgreBites::SdkTrayListener | |
{ | |
public: | |
BaseApplication(void); | |
virtual ~BaseApplication(void); | |
#ifndef __native_client__ | |
virtual void go(); | |
#else | |
bool load_nacl(); | |
#endif | |
Ogre::RenderWindow& renderWindow(); | |
Ogre::Root& root(); | |
//Adjust mouse clipping area | |
virtual void windowResized(Ogre::RenderWindow* rw); | |
protected: | |
virtual bool setup(); | |
virtual bool configure_plugins(); | |
virtual bool configure(void); | |
virtual void chooseSceneManager(void); | |
virtual void createCamera(void); | |
virtual void createInputDevices(); | |
virtual void createFrameListener(void); | |
virtual void createScene(void) = 0; // Override me! | |
virtual void destroyScene(void); | |
virtual void createViewports(void); | |
virtual void setupResources(void); | |
virtual void createResourceListener(void); | |
virtual void loadResources(void); | |
// Ogre::FrameListener | |
virtual bool frameRenderingQueued(const Ogre::FrameEvent& evt); | |
// OIS::KeyListener | |
virtual bool keyPressed( const OIS::KeyEvent &arg ); | |
virtual bool keyReleased( const OIS::KeyEvent &arg ); | |
// OIS::MouseListener | |
virtual bool mouseMoved( const OIS::MouseEvent &arg ); | |
virtual bool mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id ); | |
virtual bool mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id ); | |
// Ogre::WindowEventListener | |
//Unattach OIS before window shutdown (very important under Linux) | |
virtual void windowClosed(Ogre::RenderWindow* rw); | |
Ogre::Root *mRoot; | |
Ogre::Viewport* mViewport; | |
Ogre::Camera* mCamera; | |
Ogre::SceneManager* mSceneMgr; | |
Ogre::RenderWindow* mWindow; | |
Ogre::String mResourcesCfg; | |
Ogre::String mPluginsCfg; | |
// OgreBites | |
OgreBites::SdkTrayManager* mTrayMgr; | |
OgreBites::SdkCameraMan* mCameraMan; // basic camera controller | |
OgreBites::ParamsPanel* mDetailsPanel; // sample details panel | |
bool mCursorWasVisible; // was cursor visible before dialog appeared | |
bool mShutDown; | |
//OIS Input devices | |
OIS::InputManager* mInputManager; | |
OIS::Mouse* mMouse; | |
OIS::Keyboard* mKeyboard; | |
}; | |
#endif // #ifndef __BaseApplication_h_ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright (c) 2012 <copyright holder> <email> | |
Permission is hereby granted, free of charge, to any person | |
obtaining a copy of this software and associated documentation | |
files (the "Software"), to deal in the Software without | |
restriction, including without limitation the rights to use, | |
copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the | |
Software is furnished to do so, subject to the following | |
conditions: | |
The above copyright notice and this permission notice shall be | |
included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES | |
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT | |
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | |
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | |
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | |
OTHER DEALINGS IN THE SOFTWARE. | |
*/ | |
#include "naclois.h" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright (c) 2012 <copyright holder> <email> | |
Permission is hereby granted, free of charge, to any person | |
obtaining a copy of this software and associated documentation | |
files (the "Software"), to deal in the Software without | |
restriction, including without limitation the rights to use, | |
copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the | |
Software is furnished to do so, subject to the following | |
conditions: | |
The above copyright notice and this permission notice shall be | |
included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES | |
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT | |
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | |
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | |
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | |
OTHER DEALINGS IN THE SOFTWARE. | |
*/ | |
#ifndef NACLOIS_H | |
#define NACLOIS_H | |
#ifdef __native_client__ | |
#include "ppapi/cpp/input_event.h" | |
#include "ppapi/cpp/rect.h" | |
#include "ppapi/cpp/size.h" | |
#include <OIS/OISKeyboard.h> | |
#include <OIS/OISMouse.h> | |
#include <OIS/OISInputManager.h> | |
#include <OIS/OISFactoryCreator.h> | |
namespace detail{ | |
class NaClMouse : public OIS::Mouse | |
{ | |
public: | |
NaClMouse(OIS::InputManager* creator) : | |
OIS::Mouse("", false, 0, creator) | |
{}; | |
void setBuffered(bool){}; | |
void capture(){}; | |
OIS::Interface* queryInterface(OIS::Interface::IType) {return NULL;}; | |
void _initialize(){}; | |
bool HandleInputEvent(const pp::InputEvent& event) | |
{ | |
if(event.GetType() == PP_INPUTEVENT_TYPE_WHEEL) | |
{ | |
const pp::WheelInputEvent * wheelEvent = | |
reinterpret_cast<const pp::WheelInputEvent*>(&event); | |
mState.Z.rel = wheelEvent->GetDelta().y(); | |
if( mListener ) | |
mListener->mouseMoved( OIS::MouseEvent( this, mState ) ); | |
return false; | |
} | |
else | |
{ | |
mState.Z.rel = 0; | |
} | |
const pp::MouseInputEvent * mouseEvent = | |
reinterpret_cast<const pp::MouseInputEvent*>(&event); | |
OIS::MouseButtonID button = OIS::MB_Button3; | |
switch(mouseEvent->GetButton()) | |
{ | |
case PP_INPUTEVENT_MOUSEBUTTON_LEFT: | |
button=OIS::MB_Left; break; | |
case PP_INPUTEVENT_MOUSEBUTTON_MIDDLE: | |
button=OIS::MB_Middle; break; | |
case PP_INPUTEVENT_MOUSEBUTTON_RIGHT: | |
button=OIS::MB_Right; break; | |
case PP_INPUTEVENT_MOUSEBUTTON_NONE: | |
default: | |
break; | |
}; | |
pp::Point point = mouseEvent->GetPosition(); | |
switch(event.GetType()) | |
{ | |
case PP_INPUTEVENT_TYPE_MOUSEDOWN: | |
if (button != OIS::MB_Button3) | |
{ | |
mState.X.rel = 0; | |
mState.Y.rel = 0; | |
mState.buttons |= 1 << button; | |
if( mListener ) | |
return mListener->mousePressed( OIS::MouseEvent( this, mState ), button ); | |
} | |
break; | |
case PP_INPUTEVENT_TYPE_MOUSEUP: | |
if (button != -1) | |
{ | |
mState.X.rel = 0; | |
mState.Y.rel = 0; | |
mState.buttons &= ~(1 << button); | |
if( mListener ) | |
return mListener->mouseReleased( OIS::MouseEvent( this, mState ), button ); | |
} | |
break; | |
case PP_INPUTEVENT_TYPE_MOUSEMOVE: | |
if(mState.X.abs != point.x() && mState.Y.abs != point.y()) | |
{ | |
mState.X.rel = point.x() - mState.X.abs; | |
mState.Y.rel = point.y() - mState.Y.abs; | |
mState.X.abs = point.x(); | |
mState.Y.abs = point.y(); | |
if( mListener ) | |
mListener->mouseMoved( OIS::MouseEvent( this, mState ) ); | |
} | |
break; | |
case PP_INPUTEVENT_TYPE_MOUSEENTER: | |
break; | |
case PP_INPUTEVENT_TYPE_MOUSELEAVE: | |
break; | |
case PP_INPUTEVENT_TYPE_WHEEL: | |
break; | |
case PP_INPUTEVENT_TYPE_CONTEXTMENU: | |
break; | |
default: | |
break; | |
} | |
return false; | |
} | |
}; | |
class NaClKeyboard : public OIS::Keyboard | |
{ | |
public: | |
NaClKeyboard(OIS::InputManager* creator) : OIS::Keyboard("", false, 0, creator) {}; | |
void setBuffered(bool){}; | |
void capture(){}; | |
OIS::Interface* queryInterface(OIS::Interface::IType) {return NULL;}; | |
void _initialize(){}; | |
bool isKeyDown(OIS::KeyCode) const{return false;}; | |
const std::string& getAsString(OIS::KeyCode) | |
{ | |
static const std::string TMP = ""; | |
return TMP; | |
} | |
void copyKeyStates(char*) const{}; | |
bool HandleInputEvent(const pp::InputEvent& event) | |
{ | |
const pp::KeyboardInputEvent *keyboardEvent = | |
reinterpret_cast<const pp::KeyboardInputEvent*>(&event); | |
uint32_t kc = keyboardEvent->GetKeyCode(); | |
switch(event.GetType()) | |
{ | |
case PP_INPUTEVENT_TYPE_KEYDOWN: | |
if( mListener ) | |
mListener->keyPressed( OIS::KeyEvent( this, javascriptCodeToOIS(kc), (unsigned int)kc ) ); | |
break; | |
case PP_INPUTEVENT_TYPE_KEYUP: | |
if( mListener ) | |
mListener->keyReleased( OIS::KeyEvent( this, javascriptCodeToOIS(kc), 0 ) ); | |
break; | |
default: | |
break; | |
} | |
return false; | |
} | |
const OIS::KeyCode javascriptCodeToOIS(const uint32_t kc) | |
{ | |
using namespace OIS; | |
if( 0 > kc || kc >= 222) | |
{ | |
return KC_UNASSIGNED; | |
} | |
static KeyCode j2oCodes[222] = | |
{ | |
KC_UNASSIGNED , KC_UNASSIGNED , KC_UNASSIGNED , KC_UNASSIGNED , KC_UNASSIGNED , KC_UNASSIGNED , | |
KC_UNASSIGNED , KC_UNASSIGNED , KC_BACK , KC_TAB , KC_UNASSIGNED , KC_UNASSIGNED , | |
KC_UNASSIGNED , KC_RETURN , KC_UNASSIGNED , KC_UNASSIGNED , KC_LSHIFT , KC_LCONTROL , | |
KC_LMENU , KC_PAUSE , KC_CAPITAL , KC_UNASSIGNED , KC_UNASSIGNED , KC_UNASSIGNED , | |
KC_UNASSIGNED , KC_UNASSIGNED , KC_UNASSIGNED , KC_ESCAPE , KC_UNASSIGNED , KC_UNASSIGNED , | |
KC_UNASSIGNED , KC_UNASSIGNED , KC_SPACE , KC_PGUP , KC_PGDOWN , KC_END , | |
KC_HOME , KC_LEFT , KC_UP , KC_RIGHT , KC_DOWN , KC_UNASSIGNED , | |
KC_UNASSIGNED , KC_UNASSIGNED , KC_SYSRQ , KC_INSERT , KC_DELETE , KC_UNASSIGNED , | |
KC_0 , KC_1 , KC_2 , KC_3 , KC_4 , KC_5 , | |
KC_6 , KC_7 , KC_8 , KC_9 , KC_UNASSIGNED , KC_COLON , | |
KC_UNASSIGNED , KC_EQUALS , KC_UNASSIGNED , KC_UNASSIGNED , KC_UNASSIGNED , | |
KC_A, KC_B, KC_C, KC_D, KC_E, KC_F, KC_G, KC_H, KC_I, KC_J, KC_K, KC_L, KC_M, KC_N, KC_O, KC_P, KC_Q, | |
KC_R, KC_S, KC_T, KC_U, KC_V, KC_W, KC_X, KC_Y, KC_Z, | |
KC_LWIN , KC_UNASSIGNED , KC_UNASSIGNED , KC_UNASSIGNED | |
}; | |
return j2oCodes[kc]; | |
} | |
}; | |
class IosInputNaCl :public OIS::InputManager, public OIS::FactoryCreator | |
{ | |
public: | |
IosInputNaCl() | |
: InputManager("NaClDummy") | |
, mOISKeyboard(this) | |
, mOISMouse(this) | |
{ | |
} | |
//InputManager Overrides | |
/** @copydoc InputManager::_initialize */ | |
void _initialize(OIS::ParamList&) | |
{ | |
} | |
//FactoryCreator Overrides | |
/** @copydoc FactoryCreator::deviceList */ | |
OIS::DeviceList freeDeviceList() | |
{ | |
OIS::DeviceList ret; | |
ret.insert(std::make_pair(OIS::OISKeyboard, "")); | |
ret.insert(std::make_pair(OIS::OISMouse, "")); | |
return ret; | |
} | |
/** @copydoc FactoryCreator::totalDevices */ | |
int totalDevices(OIS::Type iType) | |
{ | |
return 1; | |
} | |
/** @copydoc FactoryCreator::freeDevices */ | |
int freeDevices(OIS::Type iType) | |
{ | |
return 1; | |
} | |
/** @copydoc FactoryCreator::vendorExist */ | |
bool vendorExist(OIS::Type iType, const std::string & vendor) | |
{ | |
return true; | |
} | |
NaClMouse mOISMouse; | |
NaClKeyboard mOISKeyboard; | |
/** @copydoc FactoryCreator::createObject */ | |
OIS::Object* createObject(OIS::InputManager* creator, OIS::Type iType, bool bufferMode, const std::string & vendor = "") | |
{ | |
switch( iType ) | |
{ | |
case OIS::OISKeyboard: | |
return &mOISKeyboard; | |
break; | |
case OIS::OISMouse: | |
return &mOISMouse; | |
break; | |
case OIS::OISJoyStick: | |
default: return NULL; | |
} | |
} | |
/** @copydoc FactoryCreator::destroyObject */ | |
void destroyObject(OIS::Object* obj) {}; | |
bool HandleInputEvent(const pp::InputEvent& event) | |
{ | |
switch(event.GetType()) | |
{ | |
case PP_INPUTEVENT_TYPE_MOUSEDOWN: | |
case PP_INPUTEVENT_TYPE_MOUSEUP: | |
case PP_INPUTEVENT_TYPE_MOUSEMOVE: | |
case PP_INPUTEVENT_TYPE_MOUSEENTER: | |
case PP_INPUTEVENT_TYPE_MOUSELEAVE: | |
case PP_INPUTEVENT_TYPE_WHEEL: | |
case PP_INPUTEVENT_TYPE_CONTEXTMENU: | |
return mOISMouse.HandleInputEvent(event); | |
break; | |
case PP_INPUTEVENT_TYPE_RAWKEYDOWN: | |
case PP_INPUTEVENT_TYPE_KEYDOWN: | |
case PP_INPUTEVENT_TYPE_KEYUP: | |
case PP_INPUTEVENT_TYPE_CHAR: | |
return mOISKeyboard.HandleInputEvent(event); | |
break; | |
default: | |
return false; | |
break; | |
} | |
} | |
}; | |
} // namespace detail | |
#endif // __native_client__ | |
#endif // NACLOIS_H |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright (c) 2012 <copyright holder> <email> | |
Permission is hereby granted, free of charge, to any person | |
obtaining a copy of this software and associated documentation | |
files (the "Software"), to deal in the Software without | |
restriction, including without limitation the rights to use, | |
copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the | |
Software is furnished to do so, subject to the following | |
conditions: | |
The above copyright notice and this permission notice shall be | |
included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES | |
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT | |
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | |
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | |
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | |
OTHER DEALINGS IN THE SOFTWARE. | |
*/ | |
#include "nacltest.h" | |
nacltest::nacltest() | |
{ | |
} | |
nacltest::~nacltest() | |
{ | |
} | |
void nacltest::createScene() | |
{ | |
using namespace Ogre; | |
mSceneMgr->setAmbientLight(ColourValue(.5,.5,.5,1)); | |
SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); | |
ManualObject* manual = mSceneMgr->createManualObject(); | |
{ | |
manual->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST); | |
manual->position(0,0,0); | |
manual->position(100,100,0); | |
manual->position(0,100,0); | |
manual->position(0,0,0); | |
manual->position(0,100,0); | |
manual->position(100,100,0); | |
manual->end(); | |
} | |
node->attachObject(manual); | |
} | |
bool nacltest::frameRenderingQueued(const Ogre::FrameEvent& evt) | |
{ | |
return BaseApplication::frameRenderingQueued(evt); | |
} | |
bool nacltest::keyPressed(const OIS::KeyEvent& arg) | |
{ | |
return BaseApplication::keyPressed(arg); | |
} | |
#ifndef __native_client__ | |
#ifdef __cplusplus | |
extern "C" { | |
#endif | |
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 | |
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT ) | |
#else | |
int main(int argc, char *argv[]) | |
#endif | |
{ | |
(void)argc; | |
(void)argv; | |
// Create application object | |
nacltest app; | |
try { | |
app.go(); | |
} catch( Ogre::Exception& e ) { | |
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 | |
MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL); | |
#else | |
std::cerr << "An exception has occured: " << | |
e.getFullDescription().c_str() << std::endl; | |
#endif | |
} catch( std::exception& e ) { | |
std::cerr << "An exception has occured: " | |
<< e.what() << std::endl; | |
} | |
return 0; | |
} | |
#ifdef __cplusplus | |
} | |
#endif | |
#else // #ifndef __native_client__ | |
#include "naclutils.h" | |
#include "ppapi/cpp/module.h" | |
namespace pp { | |
Module* CreateModule() { | |
return new detail::OgrePPModule<nacltest>(); | |
} | |
} // namespace pp | |
#endif // #ifndef __native_client__ | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright (c) 2012 <copyright holder> <email> | |
Permission is hereby granted, free of charge, to any person | |
obtaining a copy of this software and associated documentation | |
files (the "Software"), to deal in the Software without | |
restriction, including without limitation the rights to use, | |
copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the | |
Software is furnished to do so, subject to the following | |
conditions: | |
The above copyright notice and this permission notice shall be | |
included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES | |
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT | |
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | |
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | |
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | |
OTHER DEALINGS IN THE SOFTWARE. | |
*/ | |
#ifndef NACLTEST_H | |
#define NACLTEST_H | |
#include "BaseApplication.h" | |
class nacltest : public BaseApplication | |
{ | |
public: | |
nacltest(); | |
virtual ~nacltest(); | |
virtual bool frameRenderingQueued(const Ogre::FrameEvent& evt); | |
virtual bool keyPressed( const OIS::KeyEvent &arg ); | |
protected: | |
virtual void createScene(); | |
}; | |
#endif // NACLTEST_H |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>OgredemoB!</title> | |
<script type="text/javascript"> | |
OgredemoBModule = null; // Global application object. | |
statusText = 'NO-STATUS'; | |
t = null; | |
function rframe() | |
{ | |
OgredemoBModule = document.getElementById('ogredemo_b'); | |
t = setTimeout(rframe,3000); | |
OgredemoBModule.postMessage('renderOneFrame'); | |
/* | |
if (OgredemoBModule.width == 800) | |
OgredemoBModule.width = 801; | |
else | |
OgredemoBModule.width = 800; | |
*/ | |
} | |
// Indicate load success. | |
function moduleDidLoad() { | |
OgredemoBModule = document.getElementById('ogredemo_b'); | |
updateStatus('SUCCESS'); | |
console.log("now initOgre"); | |
OgredemoBModule.postMessage('initOgre:' + (OgredemoBModule.width * window.devicePixelRatio) + ':' + (OgredemoBModule.height * window.devicePixelRatio)); | |
OgredemoBModule.width = 801; // hack for now for resize on start | |
rframe(); | |
return; | |
} | |
// The 'message' event handler. This handler is fired when the NaCl module | |
// posts a message to the browser by calling PPB_Messaging.PostMessage() | |
// (in C) or pp::Instance.PostMessage() (in C++). This implementation | |
// simply displays the content of the message in an alert panel. | |
function handleMessage(message_event) { | |
OgredemoBModule = document.getElementById('ogredemo_b'); | |
//if(message_event.data == "renderedOneFrame") { | |
//OgredemoBModule.postMessage('renderOneFrame'); | |
//return; | |
//} | |
console.log(message_event.data); | |
//alert(message_event.data); | |
} | |
// If the page loads before the Native Client module loads, then set the | |
// status message indicating that the module is still loading. Otherwise, | |
// do not change the status message. | |
function pageDidLoad() { | |
if (OgredemoBModule == null) { | |
updateStatus('LOADING...'); | |
} else { | |
// It's possible that the Native Client module onload event fired | |
// before the page's onload event. In this case, the status message | |
// will reflect 'SUCCESS', but won't be displayed. This call will | |
// display the current message. | |
updateStatus(); | |
} | |
} | |
// Set the global status message. If the element with id 'statusField' | |
// exists, then set its HTML to the status message as well. | |
// opt_message The message test. If this is null or undefined, then | |
// attempt to set the element with id 'statusField' to the value of | |
// |statusText|. | |
function updateStatus(opt_message) { | |
if (opt_message) | |
statusText = opt_message; | |
var statusField = document.getElementById('status_field'); | |
if (statusField) { | |
statusField.innerHTML = statusText; | |
} | |
} | |
</script> | |
</head> | |
<body onload="pageDidLoad()"> | |
<h1>Native Client Module OgredemoB</h1> | |
<p> | |
<!-- Load the published .nexe. This includes the 'nacl' attribute which | |
shows how to load multi-architecture modules. Each entry in the "nexes" | |
object in the .nmf manifest file is a key-value pair: the key is the | |
instruction set architecture ('x86-32', 'x86-64', etc.); the value is a URL | |
for the desired NaCl module. | |
To load the debug versions of your .nexes, set the 'nacl' attribute to the | |
_dbg.nmf version of the manifest file. | |
Note: Since this NaCl module does not use any real-estate in the browser, | |
it's width and height are set to 0. | |
Note: The <EMBED> element is wrapped inside a <DIV>, which has both a 'load' | |
and a 'message' event listener attached. This wrapping method is used | |
instead of attaching the event listeners directly to the <EMBED> element to | |
ensure that the listeners are active before the NaCl module 'load' event | |
fires. This also allows you to use PPB_Messaging.PostMessage() (in C) or | |
pp::Instance.PostMessage() (in C++) from within the initialization code in | |
your NaCl module. | |
--> | |
<div id="listener"> | |
<script type="text/javascript"> | |
var listener = document.getElementById('listener'); | |
listener.addEventListener('load', moduleDidLoad, true); | |
listener.addEventListener('message', handleMessage, true); | |
</script> | |
<embed name="nacl_module" | |
id="ogredemo_b" | |
width="500" height="500" | |
src="nacltest.nmf" | |
type="application/x-nacl" /> | |
</div> | |
</pre> | |
</p> | |
<h2>Status</h2> | |
<div id="status_field">NO-STATUS</div> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright (c) 2012 <copyright holder> <email> | |
Permission is hereby granted, free of charge, to any person | |
obtaining a copy of this software and associated documentation | |
files (the "Software"), to deal in the Software without | |
restriction, including without limitation the rights to use, | |
copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the | |
Software is furnished to do so, subject to the following | |
conditions: | |
The above copyright notice and this permission notice shall be | |
included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES | |
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT | |
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | |
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | |
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | |
OTHER DEALINGS IN THE SOFTWARE. | |
*/ | |
#include "naclutils.h" | |
#ifdef __native_client__ | |
#include <stdint.h> | |
extern "C" | |
{ | |
void* lfind ( const void * key, const void * base, size_t num, size_t width, int (*fncomparison)(const void *, const void * ) ) | |
{ | |
printf("LFIND STUB/KLUDGE BY REALAZTHAT, THIS JUST AINT IMPLEMENTED IN NACL NEWLIB HAHA"); | |
return 0; | |
} | |
} | |
#endif // __native_client__ | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright (c) 2012 <copyright holder> <email> | |
Permission is hereby granted, free of charge, to any person | |
obtaining a copy of this software and associated documentation | |
files (the "Software"), to deal in the Software without | |
restriction, including without limitation the rights to use, | |
copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the | |
Software is furnished to do so, subject to the following | |
conditions: | |
The above copyright notice and this permission notice shall be | |
included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES | |
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT | |
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | |
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | |
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | |
OTHER DEALINGS IN THE SOFTWARE. | |
*/ | |
#ifndef NACLUTILS_H | |
#define NACLUTILS_H | |
#ifdef __native_client__ | |
#include <OGRE/OgreLog.h> | |
#include <boost/scoped_ptr.hpp> | |
#include "ppapi/cpp/instance.h" | |
#include "ppapi/cpp/module.h" | |
#include "ppapi/cpp/var.h" | |
#include "ppapi/cpp/completion_callback.h" | |
#include "ppapi/gles2/gl2ext_ppapi.h" | |
#include <GLES2/gl2.h> | |
#include <stdint.h> | |
namespace Ogre{ | |
struct GLES2Plugin; | |
struct OctreePlugin; | |
} // namespace Ogre | |
namespace detail{ | |
struct IosInputNaCl; | |
template<typename ApplicationT> | |
struct NaClApplication; | |
// A small helper RAII class that implements a scoped pthread_mutex lock. | |
struct ScopedMutexLock | |
{ | |
public: | |
explicit ScopedMutexLock(pthread_mutex_t* mutex) : mutex_(mutex) | |
{ | |
if (pthread_mutex_lock(mutex_) != 0) | |
{ | |
mutex_ = NULL; | |
} | |
} | |
~ScopedMutexLock() | |
{ | |
if (mutex_) | |
pthread_mutex_unlock(mutex_); | |
} | |
bool is_valid() const | |
{ | |
return mutex_ != NULL; | |
} | |
private: | |
pthread_mutex_t* mutex_; // Weak reference. | |
}; | |
template<typename OgrePPInstanceT> | |
struct NaclLogListener : public Ogre::LogListener | |
{ | |
NaclLogListener(OgrePPInstanceT& ogrePPInstance); | |
virtual void messageLogged(const Ogre::String& message, | |
Ogre::LogMessageLevel lml, | |
bool maskDebug, | |
const Ogre::String& logName, | |
bool& skipThisMessage); | |
OgrePPInstanceT& ogrePPInstance; | |
}; | |
template<typename ApplicationT> | |
struct OgrePPInstance : public pp::Instance { | |
public: | |
typedef OgrePPInstance self_t; | |
explicit OgrePPInstance(PP_Instance instance); | |
void initOgre(uint32_t width, uint32_t height); | |
virtual ~OgrePPInstance(); | |
virtual void HandleMessage(const pp::Var& var_message); | |
virtual bool HandleInputEvent(const pp::InputEvent& event); | |
virtual void DidChangeFocus(bool has_focus); | |
virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]); | |
// Called whenever the in-browser window changes size. | |
virtual void DidChangeView(const pp::Rect& position, const pp::Rect& clip); | |
void renderOneFrame(); | |
typedef NaClApplication< ApplicationT > NaclApplicationT; | |
boost::scoped_ptr<NaclApplicationT> application; | |
boost::scoped_ptr<IosInputNaCl> mIosInputNaCl; | |
pp::CompletionCallbackFactory<self_t> mCcFactory; | |
bool mWasOgreInit; | |
int mWidth, mHeight; | |
pp::CompletionCallback mNaClSwapCallback; | |
bool mSwapFinished; | |
bool mFrameRenderFinished; | |
pthread_mutex_t input_mutex_; | |
private: | |
void onSwapCallback(int32_t result); | |
void resize(); | |
}; | |
template<typename ApplicationT> | |
struct NaClApplication : public ApplicationT | |
{ | |
public: | |
typedef OgrePPInstance< ApplicationT > OgrePPInstanceT; | |
NaClApplication(OgrePPInstanceT& ogrePPInstance); | |
virtual bool configure_plugins(); | |
virtual void createInputDevices(); | |
virtual bool configure(); | |
OgrePPInstanceT& ogrePPInstance; | |
boost::scoped_ptr<Ogre::GLES2Plugin> mGLES2Plugin; | |
boost::scoped_ptr<Ogre::OctreePlugin> octreePlugin; | |
}; | |
template<typename Application> | |
struct OgrePPModule : public pp::Module { | |
public: | |
OgrePPModule() | |
: pp::Module() | |
{} | |
virtual ~OgrePPModule() { | |
glTerminatePPAPI(); | |
} | |
/// Called by the browser when the module is first loaded and ready to run. | |
/// This is called once per module, not once per instance of the module on | |
/// the page. | |
virtual bool Init() { | |
return glInitializePPAPI(get_browser_interface()) == GL_TRUE; | |
return true; | |
} | |
virtual pp::Instance* CreateInstance(PP_Instance instance) { | |
return new OgrePPInstance< Application > (instance); | |
} | |
}; | |
} // namespace detail | |
#include "naclutils.inl.h" | |
#endif // __native_client__ | |
#endif // NACLUTILS_H |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "naclutils.h" | |
#include "naclois.h" | |
#include "ppapi/cpp/input_event.h" | |
#include <OGRE/RenderSystems/GLES2/OgreGLES2Plugin.h> | |
#include <OGRE/Plugins/OctreeSceneManager/OgreOctreePlugin.h> | |
#include <OGRE/OgreRoot.h> | |
#include <stdexcept> | |
namespace detail{ | |
template<typename OgrePPInstanceT> | |
NaclLogListener<OgrePPInstanceT>:: | |
NaclLogListener(OgrePPInstanceT& ogrePPInstance) | |
: ogrePPInstance(ogrePPInstance) | |
{ | |
} | |
template<typename OgrePPInstanceT> | |
void | |
NaclLogListener<OgrePPInstanceT>:: | |
messageLogged(const Ogre::String& message, | |
Ogre::LogMessageLevel lml, | |
bool maskDebug, | |
const Ogre::String& logName, | |
bool& skipThisMessage) | |
{ | |
ogrePPInstance.PostMessage(message.c_str()); | |
} | |
template<typename ApplicationT> | |
NaClApplication<ApplicationT>:: | |
NaClApplication(OgrePPInstanceT& ogrePPInstance) | |
: ogrePPInstance(ogrePPInstance) | |
{ | |
} | |
template<typename ApplicationT> | |
bool | |
NaClApplication<ApplicationT>:: | |
configure_plugins() | |
{ | |
using namespace Ogre; | |
///NACL log | |
{ | |
///FIXME: should this be cleaned up?? probably yeah ... | |
NaclLogListener<OgrePPInstanceT>* logListener = new NaclLogListener<OgrePPInstanceT>(ogrePPInstance); | |
Ogre::LogManager::getSingleton().getDefaultLog()->addListener(logListener); | |
} | |
///GLES2 | |
{ | |
mGLES2Plugin.reset(new GLES2Plugin); | |
ApplicationT::mRoot->installPlugin(mGLES2Plugin.get()); | |
const RenderSystemList& availRenderers = ApplicationT::mRoot->getAvailableRenderers(); | |
if (availRenderers.empty()) | |
throw std::runtime_error("No available renderers"); | |
ApplicationT::mRoot->setRenderSystem(availRenderers.front()); | |
} | |
///Scene Manager | |
{ | |
octreePlugin.reset(new OctreePlugin); | |
ApplicationT::mRoot->installPlugin(octreePlugin.get()); | |
} | |
return true; | |
} | |
template<typename ApplicationT> | |
bool | |
NaClApplication<ApplicationT>:: | |
configure() | |
{ | |
using namespace Ogre; | |
ApplicationT::mRoot->initialise(false); | |
const bool fullscreen = false; | |
const bool vsync = false; | |
NameValuePairList params; | |
//params["vsync"] = "false"; | |
params["pp::Instance"] = StringConverter::toString((unsigned long)&ogrePPInstance); | |
params["SwapCallback"] = Ogre::StringConverter::toString((unsigned long)&(ogrePPInstance.mNaClSwapCallback)); | |
//Prepare window | |
ApplicationT::mWindow = ApplicationT::mRoot->createRenderWindow( | |
"Barebones Ogre test", | |
ogrePPInstance.mWidth, | |
ogrePPInstance.mHeight, | |
fullscreen, | |
¶ms | |
); | |
LogManager::getSingleton().logMessage(String(__FILE__) + ": " + StringConverter::toString(__LINE__)); | |
if (!ApplicationT::mWindow) | |
return false; | |
LogManager::getSingleton().logMessage(String(__FILE__) + ": " + StringConverter::toString(__LINE__)); | |
//Apply window settings | |
ApplicationT::mWindow->setActive(true); | |
ApplicationT::mWindow->setAutoUpdated(false); | |
LogManager::getSingleton().logMessage(String(__FILE__) + ": " + StringConverter::toString(__LINE__)); | |
return true; | |
} | |
template<typename ApplicationT> | |
void | |
NaClApplication<ApplicationT>:: | |
createInputDevices() | |
{ | |
Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing NACL OIS ***"); | |
OIS::ParamList pl; | |
size_t windowHnd = 0; | |
std::ostringstream windowHndStr; | |
ApplicationT::mWindow->getCustomAttribute("WINDOW", &windowHnd); | |
windowHndStr << windowHnd; | |
pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str())); | |
ApplicationT::mInputManager = ogrePPInstance.mIosInputNaCl.get(); | |
//mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true )); | |
//mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true )); | |
ApplicationT::mKeyboard = &ogrePPInstance.mIosInputNaCl->mOISKeyboard; | |
ApplicationT::mMouse = &ogrePPInstance.mIosInputNaCl->mOISMouse; | |
ogrePPInstance.RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE | PP_INPUTEVENT_CLASS_WHEEL | PP_INPUTEVENT_CLASS_KEYBOARD); | |
ApplicationT::mMouse->setEventCallback(this); | |
ApplicationT::mKeyboard->setEventCallback(this); | |
} | |
template<typename ApplicationT> | |
OgrePPInstance<ApplicationT>:: | |
OgrePPInstance(PP_Instance instance) | |
: pp::Instance(instance) | |
, mCcFactory(this) | |
, mWasOgreInit(false) | |
, mWidth(1), mHeight(1) | |
, mSwapFinished(false) | |
, mFrameRenderFinished(false) | |
{ | |
pthread_mutex_init(&input_mutex_, NULL); | |
} | |
template<typename ApplicationT> | |
OgrePPInstance<ApplicationT>:: | |
~OgredemoBInstance() | |
{ | |
pthread_mutex_destroy(&input_mutex_); | |
} | |
template<typename ApplicationT> | |
void | |
OgrePPInstance<ApplicationT>:: | |
initOgre(uint32_t width, uint32_t height) | |
{ | |
using namespace Ogre; | |
try { | |
PostMessage((String(__FILE__) + ": " + StringConverter::toString(__LINE__)).c_str()); | |
mIosInputNaCl.reset(new IosInputNaCl()); | |
application.reset(new NaclApplicationT(*this)); | |
if (!application->load_nacl()) | |
throw std::runtime_error("Error loading"); | |
PostMessage("done ogre init!!!"); | |
mWasOgreInit = true; | |
resize(); | |
renderOneFrame(); | |
} catch( Ogre::Exception& e ) { | |
PostMessage( std::string("An exception has occured: ") + e.getFullDescription().c_str() ); | |
} catch( std::exception& e ) { | |
PostMessage( std::string("An exception has occured: ") + e.what() ); | |
} | |
} | |
template<typename ApplicationT> | |
bool | |
OgrePPInstance<ApplicationT>:: | |
HandleInputEvent(const pp::InputEvent& event) | |
{ | |
using namespace Ogre; | |
ScopedMutexLock scoped_mutex(&input_mutex_); | |
return mIosInputNaCl->HandleInputEvent(event); | |
} | |
template<typename ApplicationT> | |
void | |
OgrePPInstance<ApplicationT>:: | |
DidChangeFocus(bool has_focus) | |
{ | |
pp::Instance::DidChangeFocus(has_focus); | |
} | |
template<typename ApplicationT> | |
void | |
OgrePPInstance<ApplicationT>:: | |
resize() | |
{ | |
std::stringstream s; | |
s << "resize:"; | |
s << mWidth; | |
s << "x"; | |
s << mHeight; | |
PostMessage(pp::Var(s.str().c_str())); | |
application->renderWindow().resize(mWidth, mHeight); | |
///FIXME: other viewports? | |
application->renderWindow().getViewport(0)->_updateDimensions(); | |
application->windowResized(&(application->renderWindow())); | |
} | |
template<typename ApplicationT> | |
void | |
OgrePPInstance<ApplicationT>:: | |
onSwapCallback(int32_t result) | |
{ | |
if(mWasOgreInit) | |
{ | |
mSwapFinished = true; | |
if(mFrameRenderFinished) | |
{ | |
renderOneFrame(); | |
} | |
} | |
} | |
template<typename ApplicationT> | |
void | |
OgrePPInstance<ApplicationT>:: | |
renderOneFrame() | |
{ | |
using namespace Ogre; | |
if(mWasOgreInit) | |
{ | |
try | |
{ | |
ScopedMutexLock scoped_mutex(&input_mutex_); | |
mSwapFinished = false; | |
mFrameRenderFinished = false; | |
mNaClSwapCallback = mCcFactory.NewCallback(&self_t::onSwapCallback); | |
application->root().renderOneFrame(); | |
mFrameRenderFinished = true; | |
if(mSwapFinished) | |
{ | |
mNaClSwapCallback = mCcFactory.NewCallback(&self_t::onSwapCallback); | |
mNaClSwapCallback.Run(0); | |
} | |
} | |
catch( Exception& e ) | |
{ | |
std::string error; | |
error = e.getFullDescription().c_str(); | |
// handle js messages here | |
PostMessage(pp::Var(error.c_str())); | |
} | |
catch( std::exception& e ) | |
{ | |
// handle js messages here | |
PostMessage(pp::Var(e.what())); | |
} | |
} | |
PostMessage("renderedOneFrame"); | |
} | |
template<typename ApplicationT> | |
void | |
OgrePPInstance<ApplicationT>:: | |
DidChangeView(const pp::Rect& position, const pp::Rect& clip) | |
{ | |
using namespace Ogre; | |
if(mWasOgreInit) | |
{ | |
try | |
{ | |
if (position.size().width() == mWidth && | |
position.size().height() == mHeight) | |
{ | |
return; // Size didn't change, no need to update anything. | |
} | |
mWidth = position.size().width(); | |
mHeight = position.size().height(); | |
resize(); | |
} | |
catch( Exception& e ) | |
{ | |
PostMessage(e.getFullDescription().c_str()); | |
} | |
catch( std::exception& e ) | |
{ | |
PostMessage(e.what()); | |
} | |
} | |
} | |
template<typename ApplicationT> | |
bool | |
OgrePPInstance<ApplicationT>:: | |
Init(uint32_t argc, const char* argn[], const char* argv[]) | |
{ | |
// We don't want to do anything here - else the plugin will not load. | |
// Also - it is easier to load the resources by passing on the urls | |
// in a message later. | |
Ogre::Log::setInstance(this); | |
return true; | |
} | |
template<typename ApplicationT> | |
void | |
OgrePPInstance<ApplicationT>:: | |
HandleMessage(const pp::Var& message) | |
{ | |
using namespace Ogre; | |
if (!message.is_string()) | |
return; | |
String messageAsString = message.AsString(); | |
PostMessage(pp::Var(("HandleMessage(\"" + messageAsString + "\")").c_str())); | |
static const String kMessageArgumentSeparator = ":"; | |
static const String kInitOgreId = "initOgre"; | |
if(message == "renderOneFrame") | |
{ | |
renderOneFrame(); | |
} | |
StringVector messagesParts = StringUtil::split(messageAsString, kMessageArgumentSeparator); | |
if(messagesParts.size() > 0) | |
{ | |
String messageType = messagesParts[0]; | |
PostMessage(pp::Var(messageType.c_str())); | |
/* | |
if(messageType == kLoadUrlMethodId) | |
{ | |
if(messagesParts.size() > 1) | |
{ | |
String url = messagesParts[1]; | |
loadResourcesFromUrl(url); | |
} | |
} | |
*/ | |
if(messageType == kInitOgreId) | |
{ | |
PostMessage(messagesParts[1].c_str()); | |
PostMessage(messagesParts[2].c_str()); | |
mWidth = atoi(messagesParts[1].c_str()); | |
mHeight = atoi(messagesParts[2].c_str()); | |
initOgre(mWidth, mHeight); | |
} | |
/* | |
if(messageType == kGetDownloadProgressId) | |
{ | |
mFileDownload.getDownloadProgress(); | |
} | |
*/ | |
} | |
} | |
} // namespace detail |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment