callback.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /*
  2. * Copyright 2011-2017 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "common.h"
  6. #include "bgfx_utils.h"
  7. #include "imgui/imgui.h"
  8. #include <bx/allocator.h>
  9. #include <bx/file.h>
  10. #include <bx/string.h>
  11. #include "aviwriter.h"
  12. #include <inttypes.h>
  13. #include <bimg/bimg.h>
  14. namespace
  15. {
  16. struct PosColorVertex
  17. {
  18. float m_x;
  19. float m_y;
  20. float m_z;
  21. uint32_t m_abgr;
  22. static void init()
  23. {
  24. ms_decl
  25. .begin()
  26. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  27. .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
  28. .end();
  29. };
  30. static bgfx::VertexDecl ms_decl;
  31. };
  32. bgfx::VertexDecl PosColorVertex::ms_decl;
  33. static PosColorVertex s_cubeVertices[8] =
  34. {
  35. {-1.0f, 1.0f, 1.0f, 0xff000000 },
  36. { 1.0f, 1.0f, 1.0f, 0xff0000ff },
  37. {-1.0f, -1.0f, 1.0f, 0xff00ff00 },
  38. { 1.0f, -1.0f, 1.0f, 0xff00ffff },
  39. {-1.0f, 1.0f, -1.0f, 0xffff0000 },
  40. { 1.0f, 1.0f, -1.0f, 0xffff00ff },
  41. {-1.0f, -1.0f, -1.0f, 0xffffff00 },
  42. { 1.0f, -1.0f, -1.0f, 0xffffffff },
  43. };
  44. static const uint16_t s_cubeIndices[36] =
  45. {
  46. 0, 1, 2, // 0
  47. 1, 3, 2,
  48. 4, 6, 5, // 2
  49. 5, 6, 7,
  50. 0, 2, 4, // 4
  51. 4, 2, 6,
  52. 1, 5, 3, // 6
  53. 5, 7, 3,
  54. 0, 4, 1, // 8
  55. 4, 5, 1,
  56. 2, 3, 6, // 10
  57. 6, 3, 7,
  58. };
  59. void savePng(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _srcPitch, const void* _src, bool _grayscale, bool _yflip)
  60. {
  61. bx::FileWriter writer;
  62. bx::Error err;
  63. if (bx::open(&writer, _filePath, false, &err) )
  64. {
  65. bimg::imageWritePng(&writer, _width, _height, _srcPitch, _src, _grayscale, _yflip, &err);
  66. bx::close(&writer);
  67. }
  68. }
  69. void saveTga(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _srcPitch, const void* _src, bool _grayscale, bool _yflip)
  70. {
  71. bx::FileWriter writer;
  72. bx::Error err;
  73. if (bx::open(&writer, _filePath, false, &err) )
  74. {
  75. bimg::imageWriteTga(&writer, _width, _height, _srcPitch, _src, _grayscale, _yflip, &err);
  76. bx::close(&writer);
  77. }
  78. }
  79. struct BgfxCallback : public bgfx::CallbackI
  80. {
  81. virtual ~BgfxCallback()
  82. {
  83. }
  84. virtual void fatal(bgfx::Fatal::Enum _code, const char* _str) override
  85. {
  86. // Something unexpected happened, inform user and bail out.
  87. bx::debugPrintf("Fatal error: 0x%08x: %s", _code, _str);
  88. // Must terminate, continuing will cause crash anyway.
  89. abort();
  90. }
  91. virtual void traceVargs(const char* _filePath, uint16_t _line, const char* _format, va_list _argList) override
  92. {
  93. bx::debugPrintf("%s (%d): ", _filePath, _line);
  94. bx::debugPrintfVargs(_format, _argList);
  95. }
  96. virtual uint32_t cacheReadSize(uint64_t _id) override
  97. {
  98. char filePath[256];
  99. bx::snprintf(filePath, sizeof(filePath), "temp/%016" PRIx64, _id);
  100. // Use cache id as filename.
  101. bx::FileReaderI* reader = entry::getFileReader();
  102. bx::Error err;
  103. if (bx::open(reader, filePath, &err) )
  104. {
  105. uint32_t size = (uint32_t)bx::getSize(reader);
  106. bx::close(reader);
  107. // Return size of shader file.
  108. return size;
  109. }
  110. // Return 0 if shader is not found.
  111. return 0;
  112. }
  113. virtual bool cacheRead(uint64_t _id, void* _data, uint32_t _size) override
  114. {
  115. char filePath[256];
  116. bx::snprintf(filePath, sizeof(filePath), "temp/%016" PRIx64, _id);
  117. // Use cache id as filename.
  118. bx::FileReaderI* reader = entry::getFileReader();
  119. bx::Error err;
  120. if (bx::open(reader, filePath, &err) )
  121. {
  122. // Read shader.
  123. uint32_t result = bx::read(reader, _data, _size, &err);
  124. bx::close(reader);
  125. // Make sure that read size matches requested size.
  126. return result == _size;
  127. }
  128. // Shader is not found in cache, needs to be rebuilt.
  129. return false;
  130. }
  131. virtual void cacheWrite(uint64_t _id, const void* _data, uint32_t _size) override
  132. {
  133. char filePath[256];
  134. bx::snprintf(filePath, sizeof(filePath), "temp/%016" PRIx64, _id);
  135. // Use cache id as filename.
  136. bx::FileWriterI* writer = entry::getFileWriter();
  137. bx::Error err;
  138. if (bx::open(writer, filePath, false, &err) )
  139. {
  140. // Write shader to cache location.
  141. bx::write(writer, _data, _size, &err);
  142. bx::close(writer);
  143. }
  144. }
  145. virtual void screenShot(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _pitch, const void* _data, uint32_t /*_size*/, bool _yflip) override
  146. {
  147. char temp[1024];
  148. // Save screen shot as PNG.
  149. bx::snprintf(temp, BX_COUNTOF(temp), "%s.png", _filePath);
  150. savePng(temp, _width, _height, _pitch, _data, false, _yflip);
  151. // Save screen shot as TGA.
  152. bx::snprintf(temp, BX_COUNTOF(temp), "%s.tga", _filePath);
  153. saveTga(temp, _width, _height, _pitch, _data, false, _yflip);
  154. }
  155. virtual void captureBegin(uint32_t _width, uint32_t _height, uint32_t /*_pitch*/, bgfx::TextureFormat::Enum /*_format*/, bool _yflip) override
  156. {
  157. m_writer = BX_NEW(entry::getAllocator(), AviWriter)(entry::getFileWriter() );
  158. if (!m_writer->open("temp/capture.avi", _width, _height, 60, _yflip) )
  159. {
  160. BX_DELETE(entry::getAllocator(), m_writer);
  161. m_writer = NULL;
  162. }
  163. }
  164. virtual void captureEnd() override
  165. {
  166. if (NULL != m_writer)
  167. {
  168. m_writer->close();
  169. BX_DELETE(entry::getAllocator(), m_writer);
  170. m_writer = NULL;
  171. }
  172. }
  173. virtual void captureFrame(const void* _data, uint32_t /*_size*/) override
  174. {
  175. if (NULL != m_writer)
  176. {
  177. m_writer->frame(_data);
  178. }
  179. }
  180. AviWriter* m_writer;
  181. };
  182. const size_t kNaturalAlignment = 8;
  183. class BgfxAllocator : public bx::AllocatorI
  184. {
  185. public:
  186. BgfxAllocator()
  187. : m_numBlocks(0)
  188. , m_maxBlocks(0)
  189. {
  190. }
  191. virtual ~BgfxAllocator()
  192. {
  193. }
  194. virtual void* realloc(void* _ptr, size_t _size, size_t _align, const char* _file, uint32_t _line) override
  195. {
  196. if (0 == _size)
  197. {
  198. if (NULL != _ptr)
  199. {
  200. if (kNaturalAlignment >= _align)
  201. {
  202. bx::debugPrintf("%s(%d): FREE %p\n", _file, _line, _ptr);
  203. ::free(_ptr);
  204. --m_numBlocks;
  205. }
  206. else
  207. {
  208. bx::alignedFree(this, _ptr, _align, _file, _line);
  209. }
  210. }
  211. return NULL;
  212. }
  213. else if (NULL == _ptr)
  214. {
  215. if (kNaturalAlignment >= _align)
  216. {
  217. void* ptr = ::malloc(_size);
  218. bx::debugPrintf("%s(%d): ALLOC %p of %d byte(s)\n", _file, _line, ptr, _size);
  219. ++m_numBlocks;
  220. m_maxBlocks = bx::uint32_max(m_maxBlocks, m_numBlocks);
  221. return ptr;
  222. }
  223. return bx::alignedAlloc(this, _size, _align, _file, _line);
  224. }
  225. if (kNaturalAlignment >= _align)
  226. {
  227. void* ptr = ::realloc(_ptr, _size);
  228. bx::debugPrintf("%s(%d): REALLOC %p (old %p) of %d byte(s)\n", _file, _line, ptr, _ptr, _size);
  229. if (NULL == _ptr)
  230. {
  231. ++m_numBlocks;
  232. m_maxBlocks = bx::uint32_max(m_maxBlocks, m_numBlocks);
  233. }
  234. return ptr;
  235. }
  236. return bx::alignedRealloc(this, _ptr, _size, _align, _file, _line);
  237. }
  238. void dumpStats() const
  239. {
  240. bx::debugPrintf("Allocator stats: num blocks %d (peak: %d)\n", m_numBlocks, m_maxBlocks);
  241. }
  242. private:
  243. uint32_t m_numBlocks;
  244. uint32_t m_maxBlocks;
  245. };
  246. class ExampleCallback : public entry::AppI
  247. {
  248. public:
  249. ExampleCallback(const char* _name, const char* _description)
  250. : entry::AppI(_name, _description)
  251. {
  252. }
  253. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  254. {
  255. Args args(_argc, _argv);
  256. m_width = _width;
  257. m_height = _height;
  258. m_debug = BGFX_DEBUG_NONE;
  259. m_reset = 0
  260. | BGFX_RESET_VSYNC
  261. | BGFX_RESET_CAPTURE
  262. | BGFX_RESET_MSAA_X16
  263. ;
  264. bgfx::init(
  265. args.m_type
  266. , args.m_pciId
  267. , 0
  268. , &m_callback // custom callback handler
  269. , &m_allocator // custom allocator
  270. );
  271. bgfx::reset(m_width, m_height, m_reset);
  272. // Enable debug text.
  273. bgfx::setDebug(m_debug);
  274. // Set view 0 clear state.
  275. bgfx::setViewClear(0
  276. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  277. , 0x303030ff
  278. , 1.0f
  279. , 0
  280. );
  281. // Create vertex stream declaration.
  282. PosColorVertex::init();
  283. // Create static vertex buffer.
  284. m_vbh = bgfx::createVertexBuffer(
  285. bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
  286. , PosColorVertex::ms_decl
  287. );
  288. // Create static index buffer.
  289. m_ibh = bgfx::createIndexBuffer(bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) );
  290. // Create program from shaders.
  291. m_program = loadProgram("vs_callback", "fs_callback");
  292. m_time = 0.0f;
  293. m_frame = 0;
  294. imguiCreate();
  295. }
  296. virtual int shutdown() override
  297. {
  298. imguiDestroy();
  299. // Cleanup.
  300. bgfx::destroy(m_ibh);
  301. bgfx::destroy(m_vbh);
  302. bgfx::destroy(m_program);
  303. // Shutdown bgfx.
  304. bgfx::shutdown();
  305. m_allocator.dumpStats();
  306. return 0;
  307. }
  308. bool update() override
  309. {
  310. bool exit = false;
  311. // 5 second 60Hz video
  312. if (m_frame < 300)
  313. {
  314. ++m_frame;
  315. }
  316. else
  317. {
  318. m_reset &= ~BGFX_RESET_CAPTURE;
  319. exit = entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState);
  320. imguiBeginFrame(m_mouseState.m_mx
  321. , m_mouseState.m_my
  322. , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  323. | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  324. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  325. , m_mouseState.m_mz
  326. , uint16_t(m_width)
  327. , uint16_t(m_height)
  328. );
  329. showExampleDialog(this);
  330. imguiEndFrame();
  331. }
  332. if (!exit)
  333. {
  334. // Set view 0 default viewport.
  335. bgfx::setViewRect(0, 0, 0, bgfx::BackbufferRatio::Equal);
  336. // This dummy draw call is here to make sure that view 0 is cleared
  337. // if no other draw calls are submitted to view 0.
  338. bgfx::touch(0);
  339. float at[3] = { 0.0f, 0.0f, 0.0f };
  340. float eye[3] = { 0.0f, 0.0f, -35.0f };
  341. float view[16];
  342. float proj[16];
  343. bx::mtxLookAt(view, eye, at);
  344. bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f, bgfx::getCaps()->homogeneousDepth);
  345. // Set view and projection matrix for view 0.
  346. bgfx::setViewTransform(0, view, proj);
  347. m_time += 1.0f/60.0f;
  348. // Submit 11x11 cubes.
  349. for (uint32_t yy = 0; yy < 11; ++yy)
  350. {
  351. for (uint32_t xx = 0; xx < 11-yy; ++xx)
  352. {
  353. float mtx[16];
  354. bx::mtxRotateXY(mtx, m_time + xx*0.21f, m_time + yy*0.37f);
  355. mtx[12] = -15.0f + float(xx)*3.0f;
  356. mtx[13] = -15.0f + float(yy)*3.0f;
  357. mtx[14] = 0.0f;
  358. // Set model matrix for rendering.
  359. bgfx::setTransform(mtx);
  360. // Set vertex and index buffer.
  361. bgfx::setVertexBuffer(0, m_vbh);
  362. bgfx::setIndexBuffer(m_ibh);
  363. // Set render states.
  364. bgfx::setState(BGFX_STATE_DEFAULT);
  365. // Submit primitive for rendering to view 0.
  366. bgfx::submit(0, m_program);
  367. }
  368. }
  369. // Take screen shot at frame 150.
  370. if (150 == m_frame)
  371. {
  372. bgfx::FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
  373. bgfx::requestScreenShot(fbh, "temp/frame150");
  374. }
  375. // Advance to next frame. Rendering thread will be kicked to
  376. // process submitted rendering primitives.
  377. bgfx::frame();
  378. return true;
  379. }
  380. return false;
  381. }
  382. BgfxCallback m_callback;
  383. BgfxAllocator m_allocator;
  384. entry::MouseState m_mouseState;
  385. uint32_t m_width;
  386. uint32_t m_height;
  387. uint32_t m_debug;
  388. uint32_t m_reset;
  389. bgfx::VertexBufferHandle m_vbh;
  390. bgfx::IndexBufferHandle m_ibh;
  391. bgfx::ProgramHandle m_program;
  392. float m_time;
  393. uint32_t m_frame;
  394. };
  395. } // namespace
  396. ENTRY_IMPLEMENT_MAIN(ExampleCallback, "07-callback", "Implementing application specific callbacks for taking screen shots, caching OpenGL binary shaders, and video capture.");