main.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /** Example 023 SMeshBufferHandling
  2. A tutorial by geoff.
  3. In this tutorial we'll learn how to create custom meshes and deal with them
  4. with Irrlicht. We'll create an interesting heightmap with some lighting effects.
  5. With keys 1,2,3 you can choose a different mesh layout, which is put into the
  6. mesh buffers as desired. All positions, normals, etc. are updated accordingly.
  7. Ok, let's start with the headers (I think there's nothing to say about it)
  8. */
  9. #include <irrlicht.h>
  10. #include "driverChoice.h"
  11. #ifdef _MSC_VER
  12. #pragma comment(lib, "Irrlicht.lib")
  13. #endif
  14. //Namespaces for the engine
  15. using namespace irr;
  16. using namespace video;
  17. using namespace core;
  18. using namespace scene;
  19. using namespace io;
  20. using namespace gui;
  21. /* This is the type of the functions which work out the colour. */
  22. typedef SColor colour_func(f32 x, f32 y, f32 z);
  23. /* Here comes a set of functions which can be used for coloring the nodes while
  24. creating the mesh. */
  25. // Greyscale, based on the height.
  26. SColor grey(f32, f32, f32 z)
  27. {
  28. u32 n = (u32)(255.f * z);
  29. return SColor(255, n, n, n);
  30. }
  31. // Interpolation between blue and white, with red added in one
  32. // direction and green in the other.
  33. SColor yellow(f32 x, f32 y, f32)
  34. {
  35. return SColor(255, 128 + (u32)(127.f * x), 128 + (u32)(127.f * y), 255);
  36. }
  37. // Pure white.
  38. SColor white(f32, f32, f32) { return SColor(255, 255, 255, 255); }
  39. /* The type of the functions which generate the heightmap. x and y
  40. range between -0.5 and 0.5, and s is the scale of the heightmap. */
  41. typedef f32 generate_func(s16 x, s16 y, f32 s);
  42. // An interesting sample function :-)
  43. f32 eggbox(s16 x, s16 y, f32 s)
  44. {
  45. const f32 r = 4.f*sqrtf((f32)(x*x + y*y))/s;
  46. const f32 z = (f32)exp(-r * 2) * (cosf(0.2f * x) + cosf(0.2f * y));
  47. return 0.25f+0.25f*z;
  48. }
  49. // A rather dumb sine function :-/
  50. f32 moresine(s16 x, s16 y, f32 s)
  51. {
  52. const f32 xx=0.3f*(f32)x/s;
  53. const f32 yy=12*y/s;
  54. const f32 z = sinf(xx*xx+yy)*sinf(xx+yy*yy);
  55. return 0.25f + 0.25f * z;
  56. }
  57. // A simple function
  58. f32 justexp(s16 x, s16 y, f32 s)
  59. {
  60. const f32 xx=6*x/s;
  61. const f32 yy=6*y/s;
  62. const f32 z = (xx*xx+yy*yy);
  63. return 0.3f*z*cosf(xx*yy);
  64. }
  65. /* A simple class for representing heightmaps. Most of this should be obvious. */
  66. class HeightMap
  67. {
  68. private:
  69. const u16 Width;
  70. const u16 Height;
  71. f32 s;
  72. core::array<f32> data;
  73. public:
  74. HeightMap(u16 _w, u16 _h) : Width(_w), Height(_h), s(0.f), data(0)
  75. {
  76. s = sqrtf((f32)(Width * Width + Height * Height));
  77. data.set_used(Width * Height);
  78. }
  79. // Fill the heightmap with values generated from f.
  80. void generate(generate_func f)
  81. {
  82. u32 i=0;
  83. for(u16 y = 0; y < Height; ++y)
  84. for(u16 x = 0; x < Width; ++x)
  85. set(i++, calc(f, x, y));
  86. }
  87. u16 height() const { return Height; }
  88. u16 width() const { return Width; }
  89. f32 calc(generate_func f, u16 x, u16 y) const
  90. {
  91. const f32 xx = (f32)x - Width*0.5f;
  92. const f32 yy = (f32)y - Height*0.5f;
  93. return f((u16)xx, (u16)yy, s);
  94. }
  95. // The height at (x, y) is at position y * Width + x.
  96. void set(u16 x, u16 y, f32 z) { data[y * Width + x] = z; }
  97. void set(u32 i, f32 z) { data[i] = z; }
  98. f32 get(u16 x, u16 y) const { return data[y * Width + x]; }
  99. /* The only difficult part. This considers the normal at (x, y) to
  100. be the cross product of the vectors between the adjacent points
  101. in the horizontal and vertical directions.
  102. s is a scaling factor, which is necessary if the height units are
  103. different from the coordinate units; for example, if your map has
  104. heights in meters and the coordinates are in units of a
  105. kilometer. */
  106. vector3df getnormal(u16 x, u16 y, f32 s) const
  107. {
  108. const f32 zc = get(x, y);
  109. f32 zl, zr, zu, zd;
  110. if (x == 0)
  111. {
  112. zr = get(x + 1, y);
  113. zl = zc + zc - zr;
  114. }
  115. else if (x == Width - 1)
  116. {
  117. zl = get(x - 1, y);
  118. zr = zc + zc - zl;
  119. }
  120. else
  121. {
  122. zr = get(x + 1, y);
  123. zl = get(x - 1, y);
  124. }
  125. if (y == 0)
  126. {
  127. zd = get(x, y + 1);
  128. zu = zc + zc - zd;
  129. }
  130. else if (y == Height - 1)
  131. {
  132. zu = get(x, y - 1);
  133. zd = zc + zc - zu;
  134. }
  135. else
  136. {
  137. zd = get(x, y + 1);
  138. zu = get(x, y - 1);
  139. }
  140. return vector3df(s * 2 * (zl - zr), 4, s * 2 * (zd - zu)).normalize();
  141. }
  142. };
  143. /* A class which generates a mesh from a heightmap. */
  144. class TMesh
  145. {
  146. private:
  147. u16 Width;
  148. u16 Height;
  149. f32 Scale;
  150. public:
  151. SMesh* Mesh;
  152. TMesh() : Width(0), Height(0), Scale(1.f), Mesh(0)
  153. {
  154. Mesh = new SMesh();
  155. }
  156. ~TMesh()
  157. {
  158. Mesh->drop();
  159. }
  160. // Unless the heightmap is small, it won't all fit into a single
  161. // SMeshBuffer. This function chops it into pieces and generates a
  162. // buffer from each one.
  163. void init(const HeightMap &hm, f32 scale, colour_func cf, IVideoDriver *driver)
  164. {
  165. Scale = scale;
  166. const u32 mp = driver -> getMaximalPrimitiveCount();
  167. Width = hm.width();
  168. Height = hm.height();
  169. const u32 sw = mp / (6 * Height); // the width of each piece
  170. u32 i=0;
  171. for(u32 y0 = 0; y0 < Height; y0 += sw)
  172. {
  173. u16 y1 = y0 + sw;
  174. if (y1 >= Height)
  175. y1 = Height - 1; // the last one might be narrower
  176. addstrip(hm, cf, y0, y1, i);
  177. ++i;
  178. }
  179. if (i<Mesh->getMeshBufferCount())
  180. {
  181. // clear the rest
  182. for (u32 j=i; j<Mesh->getMeshBufferCount(); ++j)
  183. {
  184. Mesh->getMeshBuffer(j)->drop();
  185. }
  186. Mesh->MeshBuffers.erase(i,Mesh->getMeshBufferCount()-i);
  187. }
  188. // set dirty flag to make sure that hardware copies of this
  189. // buffer are also updated, see IMesh::setHardwareMappingHint
  190. Mesh->setDirty();
  191. Mesh->recalculateBoundingBox();
  192. }
  193. // Generate a SMeshBuffer which represents all the vertices and
  194. // indices for values of y between y0 and y1, and add it to the
  195. // mesh.
  196. void addstrip(const HeightMap &hm, colour_func cf, u16 y0, u16 y1, u32 bufNum)
  197. {
  198. SMeshBuffer *buf = 0;
  199. if (bufNum<Mesh->getMeshBufferCount())
  200. {
  201. buf = (SMeshBuffer*)Mesh->getMeshBuffer(bufNum);
  202. }
  203. else
  204. {
  205. // create new buffer
  206. buf = new SMeshBuffer();
  207. Mesh->addMeshBuffer(buf);
  208. // to simplify things we drop here but continue using buf
  209. buf->drop();
  210. }
  211. buf->Vertices.set_used((1 + y1 - y0) * Width);
  212. u32 i=0;
  213. for (u16 y = y0; y <= y1; ++y)
  214. {
  215. for (u16 x = 0; x < Width; ++x)
  216. {
  217. const f32 z = hm.get(x, y);
  218. const f32 xx = (f32)x/(f32)Width;
  219. const f32 yy = (f32)y/(f32)Height;
  220. S3DVertex& v = buf->Vertices[i++];
  221. v.Pos.set(x, Scale * z, y);
  222. v.Normal.set(hm.getnormal(x, y, Scale));
  223. v.Color=cf(xx, yy, z);
  224. v.TCoords.set(xx, yy);
  225. }
  226. }
  227. buf->Indices.set_used(6 * (Width - 1) * (y1 - y0));
  228. i=0;
  229. for(u16 y = y0; y < y1; ++y)
  230. {
  231. for(u16 x = 0; x < Width - 1; ++x)
  232. {
  233. const u16 n = (y-y0) * Width + x;
  234. buf->Indices[i]=n;
  235. buf->Indices[++i]=n + Width;
  236. buf->Indices[++i]=n + Width + 1;
  237. buf->Indices[++i]=n + Width + 1;
  238. buf->Indices[++i]=n + 1;
  239. buf->Indices[++i]=n;
  240. ++i;
  241. }
  242. }
  243. buf->recalculateBoundingBox();
  244. }
  245. };
  246. /*
  247. Our event receiver implementation, taken from tutorial 4.
  248. */
  249. class MyEventReceiver : public IEventReceiver
  250. {
  251. public:
  252. // This is the one method that we have to implement
  253. virtual bool OnEvent(const SEvent& event)
  254. {
  255. // Remember whether each key is down or up
  256. if (event.EventType == irr::EET_KEY_INPUT_EVENT)
  257. KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;
  258. return false;
  259. }
  260. // This is used to check whether a key is being held down
  261. virtual bool IsKeyDown(EKEY_CODE keyCode) const
  262. {
  263. return KeyIsDown[keyCode];
  264. }
  265. MyEventReceiver()
  266. {
  267. for (u32 i=0; i<KEY_KEY_CODES_COUNT; ++i)
  268. KeyIsDown[i] = false;
  269. }
  270. private:
  271. // We use this array to store the current state of each key
  272. bool KeyIsDown[KEY_KEY_CODES_COUNT];
  273. };
  274. /*
  275. Much of this is code taken from some of the examples. We merely set
  276. up a mesh from a heightmap, light it with a moving light, and allow
  277. the user to navigate around it.
  278. */
  279. int main(int argc, char* argv[])
  280. {
  281. // ask user for driver
  282. video::E_DRIVER_TYPE driverType=driverChoiceConsole();
  283. if (driverType==video::EDT_COUNT)
  284. return 1;
  285. MyEventReceiver receiver;
  286. IrrlichtDevice* device = createDevice(driverType,
  287. core::dimension2du(800, 600), 32, false, false, false,
  288. &receiver);
  289. if(device == 0)
  290. return 1;
  291. IVideoDriver *driver = device->getVideoDriver();
  292. ISceneManager *smgr = device->getSceneManager();
  293. device->setWindowCaption(L"Irrlicht Example for SMesh usage.");
  294. /*
  295. Create the custom mesh and initialize with a heightmap
  296. */
  297. TMesh mesh;
  298. HeightMap hm = HeightMap(255, 255);
  299. hm.generate(eggbox);
  300. mesh.init(hm, 50.f, grey, driver);
  301. // Add the mesh to the scene graph
  302. IMeshSceneNode* meshnode = smgr -> addMeshSceneNode(mesh.Mesh);
  303. meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING, false);
  304. meshnode->getMaterial(0).Shininess = 80.f;
  305. // light is just for nice effects
  306. ILightSceneNode *node = smgr->addLightSceneNode(0, vector3df(0,100,0),
  307. SColorf(1.0f, 0.6f, 0.7f, 1.0f), 500.0f);
  308. if (node)
  309. {
  310. node->getLightData().Attenuation.set(0.f, 1.f/500.f, 0.f);
  311. ISceneNodeAnimator* anim = smgr->createFlyCircleAnimator(vector3df(0,150,0),250.0f);
  312. if (anim)
  313. {
  314. node->addAnimator(anim);
  315. anim->drop();
  316. }
  317. }
  318. ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS();
  319. if (camera)
  320. {
  321. camera->setPosition(vector3df(-20.f, 150.f, -20.f));
  322. camera->setTarget(vector3df(200.f, -80.f, 150.f));
  323. camera->setFarValue(20000.0f);
  324. }
  325. switchToMayaCamera(device);
  326. /*
  327. Just a usual render loop with event handling. The custom mesh is
  328. a usual part of the scene graph which gets rendered by drawAll.
  329. */
  330. while(device->run())
  331. {
  332. if(!device->isWindowActive())
  333. {
  334. device->sleep(100);
  335. continue;
  336. }
  337. if(receiver.IsKeyDown(irr::KEY_KEY_W))
  338. {
  339. meshnode->setMaterialFlag(video::EMF_WIREFRAME, !meshnode->getMaterial(0).Wireframe);
  340. }
  341. else if(receiver.IsKeyDown(irr::KEY_KEY_1))
  342. {
  343. hm.generate(eggbox);
  344. mesh.init(hm, 50.f, grey, driver);
  345. }
  346. else if(receiver.IsKeyDown(irr::KEY_KEY_2))
  347. {
  348. hm.generate(moresine);
  349. mesh.init(hm, 50.f, yellow, driver);
  350. }
  351. else if(receiver.IsKeyDown(irr::KEY_KEY_3))
  352. {
  353. hm.generate(justexp);
  354. mesh.init(hm, 50.f, yellow, driver);
  355. }
  356. driver->beginScene(video::ECBF_COLOR | video::ECBF_DEPTH, SColor(0xff000000));
  357. smgr->drawAll();
  358. driver->endScene();
  359. }
  360. device->drop();
  361. return 0;
  362. }
  363. /*
  364. That's it! Just compile and play around with the program.
  365. **/