main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /** Example 020 Managed Lights
  2. Written by Colin MacDonald. This tutorial explains the use of the Light Manager
  3. of Irrlicht. It enables the use of more dynamic light sources than the actual
  4. hardware supports. Further applications of the Light Manager, such as per scene
  5. node callbacks, are left out for simplicity of the example.
  6. */
  7. #include <irrlicht.h>
  8. #include "driverChoice.h"
  9. #include "exampleHelper.h"
  10. using namespace irr;
  11. using namespace core;
  12. #if defined(_MSC_VER)
  13. #pragma comment(lib, "Irrlicht.lib")
  14. #endif // MSC_VER
  15. /*
  16. Normally, you are limited to 8 dynamic lights per scene: this is a hardware limit. If you
  17. want to use more dynamic lights in your scene, then you can register an optional light
  18. manager that allows you to to turn lights on and off at specific point during rendering.
  19. You are still limited to 8 lights, but the limit is per scene node.
  20. This is completely optional: if you do not register a light manager, then a default
  21. distance-based scheme will be used to prioritise hardware lights based on their distance
  22. from the active camera.
  23. NO_MANAGEMENT disables the light manager and shows Irrlicht's default light behaviour.
  24. The 8 lights nearest to the camera will be turned on, and other lights will be turned off.
  25. In this example, this produces a funky looking but incoherent light display.
  26. LIGHTS_NEAREST_NODE shows an implementation that turns on a limited number of lights
  27. per mesh scene node. If finds the 3 lights that are nearest to the node being rendered,
  28. and turns them on, turning all other lights off. This works, but as it operates on every
  29. light for every node, it does not scale well with many lights. The flickering you can see
  30. in this demo is due to the lights swapping their relative positions from the cubes
  31. (a deliberate demonstration of the limitations of this technique).
  32. LIGHTS_IN_ZONE shows a technique for turning on lights based on a 'zone'. Each empty scene
  33. node is considered to be the parent of a zone. When nodes are rendered, they turn off all
  34. lights, then find their parent 'zone' and turn on all lights that are inside that zone, i.e.
  35. are descendents of it in the scene graph. This produces true 'local' lighting for each cube
  36. in this example. You could use a similar technique to locally light all meshes in (e.g.)
  37. a room, without the lights spilling out to other rooms.
  38. This light manager is also an event receiver; this is purely for simplicity in this example,
  39. it's neither necessary nor recommended for a real application.
  40. */
  41. class CMyLightManager : public scene::ILightManager, public IEventReceiver
  42. {
  43. typedef enum
  44. {
  45. NO_MANAGEMENT,
  46. LIGHTS_NEAREST_NODE,
  47. LIGHTS_IN_ZONE
  48. }
  49. LightManagementMode;
  50. LightManagementMode Mode;
  51. LightManagementMode RequestedMode;
  52. // These data represent the state information that this light manager
  53. // is interested in.
  54. scene::ISceneManager * SceneManager;
  55. core::array<scene::ISceneNode*> * SceneLightList;
  56. scene::E_SCENE_NODE_RENDER_PASS CurrentRenderPass;
  57. scene::ISceneNode * CurrentSceneNode;
  58. public:
  59. CMyLightManager(scene::ISceneManager* sceneManager)
  60. : Mode(NO_MANAGEMENT), RequestedMode(NO_MANAGEMENT),
  61. SceneManager(sceneManager), SceneLightList(0),
  62. CurrentRenderPass(scene::ESNRP_NONE), CurrentSceneNode(0)
  63. { }
  64. // The input receiver interface, which just switches light management strategy
  65. bool OnEvent(const SEvent & event)
  66. {
  67. bool handled = false;
  68. if (event.EventType == irr::EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown)
  69. {
  70. handled = true;
  71. switch(event.KeyInput.Key)
  72. {
  73. case irr::KEY_KEY_1:
  74. RequestedMode = NO_MANAGEMENT;
  75. break;
  76. case irr::KEY_KEY_2:
  77. RequestedMode = LIGHTS_NEAREST_NODE;
  78. break;
  79. case irr::KEY_KEY_3:
  80. RequestedMode = LIGHTS_IN_ZONE;
  81. break;
  82. default:
  83. handled = false;
  84. break;
  85. }
  86. if(NO_MANAGEMENT == RequestedMode)
  87. SceneManager->setLightManager(0); // Show that it's safe to register the light manager
  88. else
  89. SceneManager->setLightManager(this);
  90. }
  91. return handled;
  92. }
  93. // This is called before the first scene node is rendered.
  94. virtual void OnPreRender(core::array<scene::ISceneNode*> & lightList)
  95. {
  96. // Update the mode; changing it here ensures that it's consistent throughout a render
  97. Mode = RequestedMode;
  98. // Store the light list. I am free to alter this list until the end of OnPostRender().
  99. SceneLightList = &lightList;
  100. }
  101. // Called after the last scene node is rendered.
  102. virtual void OnPostRender()
  103. {
  104. // Since light management might be switched off in the event handler, we'll turn all
  105. // lights on to ensure that they are in a consistent state. You wouldn't normally have
  106. // to do this when using a light manager, since you'd continue to do light management
  107. // yourself.
  108. for (u32 i = 0; i < SceneLightList->size(); i++)
  109. (*SceneLightList)[i]->setVisible(true);
  110. }
  111. virtual void OnRenderPassPreRender(scene::E_SCENE_NODE_RENDER_PASS renderPass)
  112. {
  113. // I don't have to do anything here except remember which render pass I am in.
  114. CurrentRenderPass = renderPass;
  115. }
  116. virtual void OnRenderPassPostRender(scene::E_SCENE_NODE_RENDER_PASS renderPass)
  117. {
  118. // I only want solid nodes to be lit, so after the solid pass, turn all lights off.
  119. if (scene::ESNRP_SOLID == renderPass)
  120. {
  121. for (u32 i = 0; i < SceneLightList->size(); ++i)
  122. (*SceneLightList)[i]->setVisible(false);
  123. }
  124. }
  125. // This is called before the specified scene node is rendered
  126. virtual void OnNodePreRender(scene::ISceneNode* node)
  127. {
  128. CurrentSceneNode = node;
  129. // This light manager only considers solid objects, but you are free to manipulate
  130. // lights during any phase, depending on your requirements.
  131. if (scene::ESNRP_SOLID != CurrentRenderPass)
  132. return;
  133. // And in fact for this example, I only want to consider lighting for cube scene
  134. // nodes. You will probably want to deal with lighting for (at least) mesh /
  135. // animated mesh scene nodes as well.
  136. if (node->getType() != scene::ESNT_CUBE)
  137. return;
  138. if (LIGHTS_NEAREST_NODE == Mode)
  139. {
  140. // This is a naive implementation that prioritises every light in the scene
  141. // by its proximity to the node being rendered. This produces some flickering
  142. // when lights orbit closer to a cube than its 'zone' lights.
  143. const vector3df nodePosition = node->getAbsolutePosition();
  144. // Sort the light list by prioritising them based on their distance from the node
  145. // that's about to be rendered.
  146. array<LightDistanceElement> sortingArray;
  147. sortingArray.reallocate(SceneLightList->size());
  148. u32 i;
  149. for(i = 0; i < SceneLightList->size(); ++i)
  150. {
  151. scene::ISceneNode* lightNode = (*SceneLightList)[i];
  152. const f64 distance = lightNode->getAbsolutePosition().getDistanceFromSQ(nodePosition);
  153. sortingArray.push_back(LightDistanceElement(lightNode, distance));
  154. }
  155. sortingArray.sort();
  156. // The list is now sorted by proximity to the node.
  157. // Turn on the three nearest lights, and turn the others off.
  158. for(i = 0; i < sortingArray.size(); ++i)
  159. sortingArray[i].node->setVisible(i < 3);
  160. }
  161. else if(LIGHTS_IN_ZONE == Mode)
  162. {
  163. // Empty scene nodes are used to represent 'zones'. For each solid mesh that
  164. // is being rendered, turn off all lights, then find its 'zone' parent, and turn
  165. // on all lights that are found under that node in the scene graph.
  166. // This is a general purpose algorithm that doesn't use any special
  167. // knowledge of how this particular scene graph is organised.
  168. for (u32 i = 0; i < SceneLightList->size(); ++i)
  169. {
  170. if ((*SceneLightList)[i]->getType() != scene::ESNT_LIGHT)
  171. continue;
  172. scene::ILightSceneNode* lightNode = static_cast<scene::ILightSceneNode*>((*SceneLightList)[i]);
  173. video::SLight & lightData = lightNode->getLightData();
  174. if (video::ELT_DIRECTIONAL != lightData.Type)
  175. lightNode->setVisible(false);
  176. }
  177. scene::ISceneNode * parentZone = findZone(node);
  178. if (parentZone)
  179. turnOnZoneLights(parentZone);
  180. }
  181. }
  182. // Called after the specified scene node is rendered
  183. virtual void OnNodePostRender(scene::ISceneNode* node)
  184. {
  185. // I don't need to do any light management after individual node rendering.
  186. }
  187. private:
  188. // Find the empty scene node that is the parent of the specified node
  189. scene::ISceneNode * findZone(scene::ISceneNode * node)
  190. {
  191. if (!node)
  192. return 0;
  193. if (node->getType() == scene::ESNT_EMPTY)
  194. return node;
  195. return findZone(node->getParent());
  196. }
  197. // Turn on all lights that are children (directly or indirectly) of the
  198. // specified scene node.
  199. void turnOnZoneLights(scene::ISceneNode * node)
  200. {
  201. core::list<scene::ISceneNode*> const & children = node->getChildren();
  202. for (core::list<scene::ISceneNode*>::ConstIterator child = children.begin();
  203. child != children.end(); ++child)
  204. {
  205. if ((*child)->getType() == scene::ESNT_LIGHT)
  206. (*child)->setVisible(true);
  207. else // Assume that lights don't have any children that are also lights
  208. turnOnZoneLights(*child);
  209. }
  210. }
  211. // A utility class to aid in sorting scene nodes into a distance order
  212. class LightDistanceElement
  213. {
  214. public:
  215. LightDistanceElement() {};
  216. LightDistanceElement(scene::ISceneNode* n, f64 d)
  217. : node(n), distance(d) { }
  218. scene::ISceneNode* node;
  219. f64 distance;
  220. // Lower distance elements are sorted to the start of the array
  221. bool operator < (const LightDistanceElement& other) const
  222. {
  223. return (distance < other.distance);
  224. }
  225. };
  226. };
  227. /*
  228. */
  229. int main(int argumentCount, char * argumentValues[])
  230. {
  231. // ask user for driver
  232. video::E_DRIVER_TYPE driverType=driverChoiceConsole();
  233. if (driverType==video::EDT_COUNT)
  234. return 1;
  235. IrrlichtDevice *device = createDevice(driverType,
  236. dimension2d<u32>(640, 480), 32);
  237. if(!device)
  238. return -1;
  239. f32 const lightRadius = 60.f; // Enough to reach the far side of each 'zone'
  240. video::IVideoDriver* driver = device->getVideoDriver();
  241. scene::ISceneManager* smgr = device->getSceneManager();
  242. gui::IGUIEnvironment* guienv = device->getGUIEnvironment();
  243. const io::path mediaPath = getExampleMediaPath();
  244. gui::IGUISkin* skin = guienv->getSkin();
  245. if (skin)
  246. {
  247. skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
  248. gui::IGUIFont* font = guienv->getFont(mediaPath + "fontlucida.png");
  249. if(font)
  250. skin->setFont(font);
  251. }
  252. guienv->addStaticText(L"1 - No light management", core::rect<s32>(10,10,200,30));
  253. guienv->addStaticText(L"2 - Closest 3 lights", core::rect<s32>(10,30,200,50));
  254. guienv->addStaticText(L"3 - Lights in zone", core::rect<s32>(10,50,200,70));
  255. /*
  256. Add several "zones". You could use this technique to light individual rooms, for example.
  257. */
  258. for(f32 zoneX = -100.f; zoneX <= 100.f; zoneX += 50.f)
  259. for(f32 zoneY = -60.f; zoneY <= 60.f; zoneY += 60.f)
  260. {
  261. // Start with an empty scene node, which we will use to represent a zone.
  262. scene::ISceneNode * zoneRoot = smgr->addEmptySceneNode();
  263. zoneRoot->setPosition(vector3df(zoneX, zoneY, 0));
  264. // Each zone contains a rotating cube
  265. scene::IMeshSceneNode * node = smgr->addCubeSceneNode(15, zoneRoot);
  266. scene::ISceneNodeAnimator * rotation = smgr->createRotationAnimator(vector3df(0.25f, 0.5f, 0.75f));
  267. node->addAnimator(rotation);
  268. rotation->drop();
  269. // And each cube has three lights attached to it. The lights are attached to billboards so
  270. // that we can see where they are. The billboards are attached to the cube, so that the
  271. // lights are indirect descendents of the same empty scene node as the cube.
  272. scene::IBillboardSceneNode * billboard = smgr->addBillboardSceneNode(node);
  273. billboard->setPosition(vector3df(0, -14, 30));
  274. billboard->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR );
  275. billboard->setMaterialTexture(0, driver->getTexture(mediaPath + "particle.bmp"));
  276. billboard->setMaterialFlag(video::EMF_LIGHTING, false);
  277. smgr->addLightSceneNode(billboard, vector3df(0, 0, 0), video::SColorf(1, 0, 0), lightRadius);
  278. billboard = smgr->addBillboardSceneNode(node);
  279. billboard->setPosition(vector3df(-21, -14, -21));
  280. billboard->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR );
  281. billboard->setMaterialTexture(0, driver->getTexture(mediaPath + "particle.bmp"));
  282. billboard->setMaterialFlag(video::EMF_LIGHTING, false);
  283. smgr->addLightSceneNode(billboard, vector3df(0, 0, 0), video::SColorf(0, 1, 0), lightRadius);
  284. billboard = smgr->addBillboardSceneNode(node);
  285. billboard->setPosition(vector3df(21, -14, -21));
  286. billboard->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR );
  287. billboard->setMaterialTexture(0, driver->getTexture(mediaPath + "particle.bmp"));
  288. billboard->setMaterialFlag(video::EMF_LIGHTING, false);
  289. smgr->addLightSceneNode(billboard, vector3df(0, 0, 0), video::SColorf(0, 0, 1), lightRadius);
  290. // Each cube also has a smaller cube rotating around it, to show that the cubes are being
  291. // lit by the lights in their 'zone', not just lights that are their direct children.
  292. node = smgr->addCubeSceneNode(5, node);
  293. node->setPosition(vector3df(0, 21, 0));
  294. }
  295. smgr->addCameraSceneNode(0, vector3df(0,0,-130), vector3df(0,0,0));
  296. CMyLightManager * myLightManager = new CMyLightManager(smgr);
  297. smgr->setLightManager(0); // This is the default: we won't do light management until told to do it.
  298. device->setEventReceiver(myLightManager);
  299. int lastFps = -1;
  300. while(device->run())
  301. {
  302. driver->beginScene(video::ECBF_COLOR | video::ECBF_DEPTH, video::SColor(255,100,101,140));
  303. smgr->drawAll();
  304. guienv->drawAll();
  305. driver->endScene();
  306. int fps = driver->getFPS();
  307. if(fps != lastFps)
  308. {
  309. lastFps = fps;
  310. core::stringw str = L"Managed Lights [";
  311. str += driver->getName();
  312. str += "] FPS:";
  313. str += fps;
  314. device->setWindowCaption(str.c_str());
  315. }
  316. }
  317. myLightManager->drop(); // Drop my implicit reference
  318. device->drop();
  319. return 0;
  320. }
  321. /*
  322. **/