Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 14.76 KB | None | 0 0
  1. #pragma once
  2. #include <iostream>
  3. #include <vector>
  4. #include <irrlicht.h>
  5. #include "EventReceiver.h"
  6. #include "CMeshCombiner.h"
  7. #include "ScreenQuad.h"
  8. #include "Model.h"
  9.  
  10. #define LIMIT_FPS
  11. #define PROG_NAME L"Test"
  12. #define _OVERRIDE_  //override
  13. #ifdef _IRR_WINDOWS_
  14.     #pragma comment(lib, "Irrlicht.lib")
  15.     //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
  16. #endif
  17. #ifdef _IRR_ANDROID_PLATFORM_
  18.     #include <android_native_app_glue.h>
  19.     #include "android_tools.h"
  20.     const stringc DATA_DIR="media/";
  21. #else
  22.     const stringc DATA_DIR="../media/";
  23. #endif
  24.  
  25. /*
  26. TODO pois jos ei tarvii
  27. #ifdef _IRR_WINDOWS_
  28.     #include <hash_map>
  29.     using namespace stdext;
  30. #endif
  31. #if __GNUC__ >= 4 && __GNUC_MINOR__ >= 2
  32.     // gcc 4.2 and greater uses tr1::unordered_set
  33.     // see http://gcc.gnu.org/gcc-4.3/changes.html
  34.     #include <tr1/unordered_map>
  35.     #define hash_map std::tr1::unordered_map
  36. #endif
  37. */
  38.  
  39. using namespace irr;
  40. using namespace core;
  41. using namespace scene;
  42. using namespace video;
  43. using namespace io;
  44. using namespace gui;
  45.  
  46. E_DRIVER_TYPE driverType;
  47. IrrlichtDevice *device = 0;
  48. IVideoDriver *driver = 0;
  49. ISceneManager *sceneManager = 0;
  50. IFileSystem *fileSystem = 0;
  51.  
  52. class Program
  53. {
  54. protected: 
  55.     int screenWidth, screenHeight;
  56.  
  57.     MyEventReceiver input;
  58.     ICameraSceneNode *camera;
  59.  
  60.     IGUIEnvironment *guienv;
  61.     IGUIFont *font;
  62.  
  63.     int lastFPS;
  64.     bool running;
  65.  
  66.     const static bool fullScreen=false, VSync=true;
  67.  
  68. public:
  69.     Program()
  70.     {
  71.         lastFPS = -1;
  72.         running=true;
  73.     }
  74.  
  75. #ifndef _IRR_ANDROID_PLATFORM_
  76.     // kutsu vain kerran main():sta
  77.     bool init(E_DRIVER_TYPE type, int w, int h)
  78.     {
  79.         if(device==0)
  80.         {
  81.             screenWidth=w; screenHeight=h;
  82.  
  83.             driverType=type;
  84.             device = createDevice(driverType, dimension2d<u32>(w, h), 32, fullScreen, false, VSync, &input);
  85.  
  86.             if (!device)
  87.             {
  88.                 device->getLogger()->log("Cannot create device.");
  89.                 return false;
  90.             }
  91.  
  92.             device->setWindowCaption(PROG_NAME);
  93.  
  94.             driver = device->getVideoDriver();
  95.             sceneManager = device->getSceneManager();
  96.             guienv = device->getGUIEnvironment();
  97.             fileSystem = device->getFileSystem();
  98.  
  99.             IGUISkin* skin = guienv->getSkin();
  100.             if(screenWidth<500)
  101.                 font = guienv->getFont(DATA_DIR + "font/Arial.png");
  102.             else
  103.                 font = guienv->getFont(DATA_DIR + "font/bigfont.png");
  104.             if (font) skin->setFont(font);
  105.         }
  106.    
  107.         return true;
  108.     }
  109. #else
  110.     // kutsu vain kerran main():sta
  111.     bool init(E_DRIVER_TYPE type, int w, int h, android_app* app)
  112.     {
  113.         if(device==0)
  114.         {
  115.             driverType=type;
  116.  
  117.             // create device
  118.             SIrrlichtCreationParameters param;
  119.             param.DriverType = type;                  // android:glEsVersion in AndroidManifest.xml should be "0x00020000"
  120.             param.WindowSize = dimension2d<u32>(w,h); // using 0,0 it will automatically set it to the maximal size
  121.             param.PrivateData = app;
  122.             param.Bits = 24;
  123.             param.ZBufferBits = 16;
  124.             param.AntiAlias  = 0;
  125.             // Logging is written to a file. So your application should disable all logging when you distribute your
  126.             // application or it can fill up that file over time.
  127. #ifndef _DEBUG
  128.             param.LoggingLevel = ELL_NONE; 
  129. #endif
  130.             device = createDeviceEx(param);
  131.             device->sleep(1000, false);
  132.             if(!device)
  133.             {
  134.                 device->getLogger()->log("Cannot create device.");
  135.                 return false;
  136.             }
  137.  
  138.             device->setEventReceiver(&input);
  139.             driver = device->getVideoDriver();
  140.             sceneManager = device->getSceneManager();
  141.             guienv = device->getGUIEnvironment();
  142.  
  143.             /* Access to the Android native window. You often need this when accessing NDK functions like we are doing here.
  144.                Note that windowWidth/windowHeight have already subtracted things like the taskbar which your device might have,
  145.                so you get the real size of your render-window.
  146.             */
  147.             ANativeWindow* nativeWindow = static_cast<ANativeWindow*>(driver->getExposedVideoData().OGLESAndroid.Window);
  148.             int32_t windowWidth = ANativeWindow_getWidth(app->window);
  149.             int32_t windowHeight = ANativeWindow_getHeight(app->window);
  150.  
  151.             screenWidth=windowWidth;
  152.             screenHeight=windowHeight;
  153.  
  154.             /* Get display metrics. We are accessing the Java functions of the JVM directly in this case as there is no NDK function for that yet.
  155.                Checkout android_tools.cpp if you want to know how that is done. */
  156.             irr::android::SDisplayMetrics displayMetrics;
  157.             memset(&displayMetrics, 0, sizeof displayMetrics);
  158.             irr::android::getDisplayMetrics(app, displayMetrics);
  159.  
  160.             /* For troubleshooting you can use the Irrlicht logger.
  161.                The Irrlicht logging messages are send to the Android logging system using the tag "Irrlicht".
  162.                They stay in a file there, so you can check them even after running your app.
  163.                You can watch them with the command: "adb logcat Irrlicht:V *:S"
  164.                (this means Irrlicht _V_erbose and all other messages _S_ilent).
  165.                Clean the logging file with: "adb logcat -c".
  166.                See http://developer.android.com/tools/debugging/debugging-log.html for more advanced log options.
  167.             */
  168.             char strDisplay[1000];
  169.             sprintf(strDisplay, "Window size:(%d/%d)\nDisplay size:(%d/%d)", windowWidth, windowHeight, displayMetrics.widthPixels, displayMetrics.heightPixels);
  170.             device->getLogger()->log(strDisplay);
  171.            
  172.             fileSystem = device->getFileSystem();
  173.  
  174.             // The Android assets file-system does not know which sub-directories it has (blame google).
  175.             // So we have to add all sub-directories in assets manually. Otherwise we could still open the files,
  176.             // but existFile checks will fail (which are for example needed by getFont).
  177.             for ( u32 i=0; i < fileSystem->getFileArchiveCount(); ++i )
  178.             {
  179.                 IFileArchive* archive = fileSystem->getFileArchive(i);
  180.                 if ( archive->getType() == EFAT_ANDROID_ASSET )
  181.                 {
  182.                     archive->addDirectoryToFileList(DATA_DIR);
  183.                     archive->addDirectoryToFileList(DATA_DIR+"font/");
  184.                     archive->addDirectoryToFileList(DATA_DIR+"test1/");
  185.                     archive->addDirectoryToFileList(DATA_DIR+"textures/");
  186.                     break;
  187.                 }
  188.             }
  189.  
  190.             IGUISkin* skin = guienv->getSkin();
  191.             if(screenWidth<500)
  192.                 font = guienv->getFont(DATA_DIR + "font/Arial.png");
  193.             else
  194.                 font = guienv->getFont(DATA_DIR + "font/bigfont.png");
  195.             if (font) skin->setFont(font);
  196.         }
  197.         return true;
  198.     }
  199. #endif
  200.  
  201.     void setFPSCamera()
  202.     {
  203.         device->getCursorControl()->setVisible(false);
  204.         SKeyMap keyMap[8];
  205.         keyMap[0].Action = EKA_MOVE_FORWARD;
  206.         keyMap[0].KeyCode = KEY_KEY_W;
  207.         keyMap[1].Action = EKA_MOVE_BACKWARD;
  208.         keyMap[1].KeyCode = KEY_KEY_S;
  209.         keyMap[2].Action = EKA_STRAFE_LEFT;
  210.         keyMap[2].KeyCode = KEY_KEY_A;
  211.         keyMap[3].Action = EKA_STRAFE_RIGHT;
  212.         keyMap[3].KeyCode = KEY_KEY_D;
  213.         camera = sceneManager->addCameraSceneNodeFPS(0, 100, 0.02f, -1, keyMap, 4);
  214.         camera->setPosition(vector3df(0,2,-1));
  215.         camera->setNearValue(0.1f);
  216.         camera->setFarValue(1000);
  217.         //camera->setTarget(vector3df(0,0,0));
  218.     }
  219.  
  220.     void showFPS()
  221.     {
  222.         int fps = driver->getFPS();
  223.         if (lastFPS != fps)
  224.         {
  225.             core::stringw tmp(PROG_NAME);
  226.             tmp += L"    ";
  227.             tmp += driver->getName();
  228.             tmp += L"    Poly: ";
  229.             tmp += driver->getPrimitiveCountDrawn();
  230.             tmp += L"    FPS: ";
  231.             tmp += fps;
  232.             device->setWindowCaption(tmp.c_str());
  233.             lastFPS = fps;
  234.         }
  235.     }
  236.  
  237.     void run()
  238.     {
  239.         u32 then = device->getTimer()->getTime();
  240.         bool firstTime=true;
  241.  
  242.         while(running && device->run())
  243.         {
  244.             if(device->isWindowActive())
  245.             {
  246.                 // Work out a frame delta time.
  247.                 const u32 now = device->getTimer()->getTime();
  248.                 const f32 frameDeltaTime = (f32)(now - then) / 1000.f; // Time in seconds
  249.                 then = now;
  250.  
  251.                 driver->beginScene(true, true, SColor(255,50,50,150));
  252.                 if(firstTime)
  253.                 {
  254.                     firstTime=false;
  255.                     render(0);
  256.                 }
  257.                 else
  258.                     render(frameDeltaTime);
  259.  
  260.                 driver->endScene();
  261.  
  262. #ifdef _DEBUG
  263. #ifndef _IRR_ANDROID_PLATFORM_
  264.                 showFPS();
  265. #endif
  266. #endif
  267.  
  268.                 // limit fps (about 60):
  269. #ifdef LIMIT_FPS
  270.                 irr::ITimer* timer = device->getTimer();
  271.                 irr::u32 timeThisFrame = timer->getTime();
  272.                 while( (timer->getTime() - timeThisFrame) <= 16 ) timer->tick();
  273. #endif
  274.             }
  275.             device->yield();
  276.  
  277.         }
  278.  
  279.         clearScene();
  280.     }
  281.  
  282.     virtual void render(f32 frameDeltaTime) _OVERRIDE_
  283.     {
  284.     }
  285.  
  286.     virtual void createScene() _OVERRIDE_
  287.     {
  288.     }
  289.  
  290.     virtual void clearScene() _OVERRIDE_
  291.     {
  292.         sceneManager->clear();
  293.         guienv->clear();
  294.     }
  295.  
  296.     IMetaTriangleSelector *createTriangleSelectors()
  297.     {
  298.         // Create a meta triangle selector to hold several triangle selectors.
  299.         IMetaTriangleSelector *meta = sceneManager->createMetaTriangleSelector();
  300.         array<ISceneNode *> nodes;
  301.         sceneManager->getSceneNodesFromType(ESNT_ANY, nodes); // Find all nodes
  302.  
  303.         for (u32 i=0; i < nodes.size(); ++i)
  304.         {
  305.             ISceneNode *node = nodes[i];
  306.             ITriangleSelector *selector = 0;
  307.             switch(node->getType())
  308.             {
  309.             case scene::ESNT_ANIMATED_MESH:
  310.                 // Because the selector won't animate with the mesh,
  311.                 // and is only being used for camera collision, we'll just use an approximate
  312.                 // bounding box instead of ((scene::IAnimatedMeshSceneNode*)node)->getMesh(0)
  313.                 selector = sceneManager->createTriangleSelectorFromBoundingBox(node);
  314.                 node->setTriangleSelector(selector);
  315.                 break;
  316.  
  317.             case scene::ESNT_MESH:
  318.                 selector = sceneManager->createTriangleSelector(((IMeshSceneNode*)node)->getMesh(), node);
  319.                 node->setTriangleSelector(selector);
  320.                 break;
  321.  
  322.             case scene::ESNT_TERRAIN:
  323.                 selector = sceneManager->createTerrainTriangleSelector((ITerrainSceneNode*)node);
  324.                 break;
  325.  
  326.             case scene::ESNT_OCTREE:
  327.                 selector = sceneManager->createOctreeTriangleSelector(((IMeshSceneNode*)node)->getMesh(), node);
  328.                 break;
  329.  
  330.             default:
  331.                 // Don't create a selector for this node type
  332.                 break;
  333.             }
  334.  
  335.             if(selector)
  336.             {
  337.                 // Add it to the meta selector, which will take a reference to it
  338.                 meta->addTriangleSelector(selector);
  339.                 // And drop my reference to it, so that the meta selector owns it.
  340.                 selector->drop();
  341.             }
  342.         }
  343.         return meta;
  344.     }
  345.  
  346.  
  347.      
  348.     void draw2DImage(irr::video::ITexture* texture, irr::core::rect<irr::s32> sourceRect, const core::matrix4& mat, bool useAlphaChannel, irr::video::SColor color, bool useFiltering/* = true*/, bool usePremultipliedAlpha/* = false*/)
  349.     {
  350.           //irr::video::SMaterial material;
  351.         irr::video::SMaterial& material = driver->getMaterial2D();
  352.  
  353.         /*
  354.         if(usePremultipliedAlpha)
  355.         {
  356.             color.color = PremultiplyAlpha(color.color);
  357.         }
  358.         */
  359.  
  360.         // Store and clear the world matrix
  361.         irr::core::matrix4 oldWorldMat = driver->getTransform(irr::video::ETS_WORLD);
  362.         // Store and clear the projection matrix
  363.         irr::core::matrix4 oldProjMat = driver->getTransform(irr::video::ETS_PROJECTION);
  364.         // Store and clear the view matrix
  365.         irr::core::matrix4 oldViewMat = driver->getTransform(irr::video::ETS_VIEW);
  366.  
  367.         core::matrix4 m;
  368.         // this fixes some problems with pixel exact rendering, but also breaks nice texturing
  369.         driver->setTransform(irr::video::ETS_WORLD, mat);
  370.  
  371.         // adjust the view such that pixel center aligns with texels
  372.         // Otherwise, subpixel artifacts will occur
  373.         if(driver->getDriverType() == video::EDT_DIRECT3D9)
  374.             m.setTranslation(core::vector3df(-0.5f,-0.5f,0));
  375.         driver->setTransform(irr::video::ETS_VIEW, m);
  376.  
  377.         const core::dimension2d<u32>& renderTargetSize = driver->getCurrentRenderTargetSize();
  378.         m.buildProjectionMatrixOrthoLH(f32(renderTargetSize.Width), f32(-(s32)(renderTargetSize.Height)), -1.0, 1.0);
  379.         m.setTranslation(core::vector3df(-1,1,0));
  380.         driver->setTransform(irr::video::ETS_PROJECTION, m);
  381.  
  382.         // Find the positions of corners
  383.         irr::core::vector3df corner[4];
  384.  
  385.         f32 halfWidth = (f32)(sourceRect.getWidth())*0.5f;
  386.         f32 halfHeight = (f32)(sourceRect.getHeight())*0.5f;
  387.         corner[0] = irr::core::vector3df(0.0f - halfWidth, 0.0f - halfHeight, 0.0f);
  388.         corner[1] = irr::core::vector3df(0.0f + halfWidth, 0.0f - halfHeight, 0.0f);
  389.         corner[2] = irr::core::vector3df(0.0f - halfWidth, 0.0f + halfHeight, 0.0f);
  390.         corner[3] = irr::core::vector3df(0.0f + halfWidth, 0.0f + halfHeight, 0.0f);
  391.  
  392.  
  393.         // Find the uv coordinates of the sourceRect
  394.         irr::core::vector2df uvCorner[4];
  395.         uvCorner[0] = irr::core::vector2df((f32)sourceRect.UpperLeftCorner.X,(f32)sourceRect.UpperLeftCorner.Y);
  396.         uvCorner[1] = irr::core::vector2df((f32)sourceRect.LowerRightCorner.X,(f32)sourceRect.UpperLeftCorner.Y);
  397.         uvCorner[2] = irr::core::vector2df((f32)sourceRect.UpperLeftCorner.X,(f32)sourceRect.LowerRightCorner.Y);
  398.         uvCorner[3] = irr::core::vector2df((f32)sourceRect.LowerRightCorner.X,(f32)sourceRect.LowerRightCorner.Y);
  399.         const irr::core::dimension2d<u32>& texSize = texture->getOriginalSize();
  400.         for (int x = 0; x < 4; x++)
  401.         {
  402.             float uvX = uvCorner[x].X/(float)texSize.Width;
  403.             float uvY = uvCorner[x].Y/(float)texSize.Height;
  404.             uvCorner[x] = irr::core::vector2df(uvX,uvY);
  405.         }
  406.  
  407.         // Vertices for the image
  408.         irr::video::S3DVertex vertices[4];
  409.         irr::u16 indices[6] = { 0, 1, 2, 3 ,2 ,1 };
  410.  
  411.         for (int x = 0; x < 4; x++)
  412.         {
  413.             vertices[x].Pos = corner[x];
  414.             vertices[x].TCoords = uvCorner[x];
  415.             vertices[x].Color = color;
  416.         }
  417.  
  418.         //driver->enableMaterial2D(true);
  419.         material.Lighting = false;
  420.         material.ZWriteEnable = false;
  421.         material.ZBuffer = false;
  422.         material.BackfaceCulling = false;
  423.         //material.AntiAliasing = true;
  424.         material.TextureLayer[0].Texture = texture;
  425.         // Fix dark border appearance when texture scaled down with bilinear or trilinear filter on
  426.         if(uvCorner[0].X >= 0.0f && uvCorner[3].X <= 1.0f)
  427.             material.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE;
  428.         else
  429.             material.TextureLayer[0].TextureWrapU = video::ETC_REPEAT;
  430.         if(uvCorner[0].Y >= 0.0f && uvCorner[3].Y <= 1.0f)
  431.             material.TextureLayer[0].TextureWrapV = video::ETC_CLAMP_TO_EDGE;
  432.         else
  433.             material.TextureLayer[0].TextureWrapV = video::ETC_REPEAT;
  434.  
  435.         if(usePremultipliedAlpha)
  436.             material.MaterialTypeParam = irr::video::pack_textureBlendFunc(irr::video::EBF_ONE, irr::video::EBF_ONE_MINUS_SRC_ALPHA, irr::video::EMFN_MODULATE_1X, irr::video::EAS_TEXTURE | irr::video::EAS_VERTEX_COLOR);
  437.         else
  438.             material.MaterialTypeParam = irr::video::pack_textureBlendFunc(irr::video::EBF_SRC_ALPHA, irr::video::EBF_ONE_MINUS_SRC_ALPHA, irr::video::EMFN_MODULATE_1X, irr::video::EAS_TEXTURE | irr::video::EAS_VERTEX_COLOR);
  439.  
  440.         if (useAlphaChannel)
  441.             material.MaterialType = irr::video::EMT_ONETEXTURE_BLEND;
  442.         else
  443.             material.MaterialType = irr::video::EMT_SOLID;
  444.  
  445.         material.TextureLayer[0].BilinearFilter = false;
  446.         material.TextureLayer[0].TrilinearFilter = useFiltering;
  447.  
  448.         driver->setMaterial(material);
  449.         //driver->draw2DVertexPrimitiveList(&vertices[0],4,&indices[0],2);
  450.         driver->drawIndexedTriangleList(&vertices[0],4,&indices[0],2);
  451.  
  452.         //driver->enableMaterial2D(false);
  453.  
  454.         // Restore projection and view matrices
  455.         driver->setTransform(irr::video::ETS_WORLD,oldWorldMat);
  456.         driver->setTransform(irr::video::ETS_PROJECTION,oldProjMat);
  457.         driver->setTransform(irr::video::ETS_VIEW,oldViewMat);
  458.     }
  459.  
  460. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement