callback.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /*
  2. * Copyright 2011-2018 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 void profilerBegin(const char* /*_name*/, uint32_t /*_abgr*/, const char* /*_filePath*/, uint16_t /*_line*/) override
  97. {
  98. }
  99. virtual void profilerBeginLiteral(const char* /*_name*/, uint32_t /*_abgr*/, const char* /*_filePath*/, uint16_t /*_line*/) override
  100. {
  101. }
  102. virtual void profilerEnd() override
  103. {
  104. }
  105. virtual uint32_t cacheReadSize(uint64_t _id) override
  106. {
  107. char filePath[256];
  108. bx::snprintf(filePath, sizeof(filePath), "temp/%016" PRIx64, _id);
  109. // Use cache id as filename.
  110. bx::FileReaderI* reader = entry::getFileReader();
  111. bx::Error err;
  112. if (bx::open(reader, filePath, &err) )
  113. {
  114. uint32_t size = (uint32_t)bx::getSize(reader);
  115. bx::close(reader);
  116. // Return size of shader file.
  117. return size;
  118. }
  119. // Return 0 if shader is not found.
  120. return 0;
  121. }
  122. virtual bool cacheRead(uint64_t _id, void* _data, uint32_t _size) override
  123. {
  124. char filePath[256];
  125. bx::snprintf(filePath, sizeof(filePath), "temp/%016" PRIx64, _id);
  126. // Use cache id as filename.
  127. bx::FileReaderI* reader = entry::getFileReader();
  128. bx::Error err;
  129. if (bx::open(reader, filePath, &err) )
  130. {
  131. // Read shader.
  132. uint32_t result = bx::read(reader, _data, _size, &err);
  133. bx::close(reader);
  134. // Make sure that read size matches requested size.
  135. return result == _size;
  136. }
  137. // Shader is not found in cache, needs to be rebuilt.
  138. return false;
  139. }
  140. virtual void cacheWrite(uint64_t _id, const void* _data, uint32_t _size) override
  141. {
  142. char filePath[256];
  143. bx::snprintf(filePath, sizeof(filePath), "temp/%016" PRIx64, _id);
  144. // Use cache id as filename.
  145. bx::FileWriterI* writer = entry::getFileWriter();
  146. bx::Error err;
  147. if (bx::open(writer, filePath, false, &err) )
  148. {
  149. // Write shader to cache location.
  150. bx::write(writer, _data, _size, &err);
  151. bx::close(writer);
  152. }
  153. }
  154. virtual void screenShot(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _pitch, const void* _data, uint32_t /*_size*/, bool _yflip) override
  155. {
  156. char temp[1024];
  157. // Save screen shot as PNG.
  158. bx::snprintf(temp, BX_COUNTOF(temp), "%s.png", _filePath);
  159. savePng(temp, _width, _height, _pitch, _data, false, _yflip);
  160. // Save screen shot as TGA.
  161. bx::snprintf(temp, BX_COUNTOF(temp), "%s.tga", _filePath);
  162. saveTga(temp, _width, _height, _pitch, _data, false, _yflip);
  163. }
  164. virtual void captureBegin(uint32_t _width, uint32_t _height, uint32_t /*_pitch*/, bgfx::TextureFormat::Enum /*_format*/, bool _yflip) override
  165. {
  166. m_writer = BX_NEW(entry::getAllocator(), AviWriter)(entry::getFileWriter() );
  167. if (!m_writer->open("temp/capture.avi", _width, _height, 60, _yflip) )
  168. {
  169. BX_DELETE(entry::getAllocator(), m_writer);
  170. m_writer = NULL;
  171. }
  172. }
  173. virtual void captureEnd() override
  174. {
  175. if (NULL != m_writer)
  176. {
  177. m_writer->close();
  178. BX_DELETE(entry::getAllocator(), m_writer);
  179. m_writer = NULL;
  180. }
  181. }
  182. virtual void captureFrame(const void* _data, uint32_t /*_size*/) override
  183. {
  184. if (NULL != m_writer)
  185. {
  186. m_writer->frame(_data);
  187. }
  188. }
  189. AviWriter* m_writer;
  190. };
  191. const size_t kNaturalAlignment = 8;
  192. class BgfxAllocator : public bx::AllocatorI
  193. {
  194. public:
  195. BgfxAllocator()
  196. : m_numBlocks(0)
  197. , m_maxBlocks(0)
  198. {
  199. }
  200. virtual ~BgfxAllocator()
  201. {
  202. }
  203. virtual void* realloc(void* _ptr, size_t _size, size_t _align, const char* _file, uint32_t _line) override
  204. {
  205. if (0 == _size)
  206. {
  207. if (NULL != _ptr)
  208. {
  209. if (kNaturalAlignment >= _align)
  210. {
  211. bx::debugPrintf("%s(%d): FREE %p\n", _file, _line, _ptr);
  212. ::free(_ptr);
  213. --m_numBlocks;
  214. }
  215. else
  216. {
  217. bx::alignedFree(this, _ptr, _align, _file, _line);
  218. }
  219. }
  220. return NULL;
  221. }
  222. else if (NULL == _ptr)
  223. {
  224. if (kNaturalAlignment >= _align)
  225. {
  226. void* ptr = ::malloc(_size);
  227. bx::debugPrintf("%s(%d): ALLOC %p of %d byte(s)\n", _file, _line, ptr, _size);
  228. ++m_numBlocks;
  229. m_maxBlocks = bx::uint32_max(m_maxBlocks, m_numBlocks);
  230. return ptr;
  231. }
  232. return bx::alignedAlloc(this, _size, _align, _file, _line);
  233. }
  234. if (kNaturalAlignment >= _align)
  235. {
  236. void* ptr = ::realloc(_ptr, _size);
  237. bx::debugPrintf("%s(%d): REALLOC %p (old %p) of %d byte(s)\n", _file, _line, ptr, _ptr, _size);
  238. if (NULL == _ptr)
  239. {
  240. ++m_numBlocks;
  241. m_maxBlocks = bx::uint32_max(m_maxBlocks, m_numBlocks);
  242. }
  243. return ptr;
  244. }
  245. return bx::alignedRealloc(this, _ptr, _size, _align, _file, _line);
  246. }
  247. void dumpStats() const
  248. {
  249. bx::debugPrintf("Allocator stats: num blocks %d (peak: %d)\n", m_numBlocks, m_maxBlocks);
  250. }
  251. private:
  252. uint32_t m_numBlocks;
  253. uint32_t m_maxBlocks;
  254. };
  255. class ExampleCallback : public entry::AppI
  256. {
  257. public:
  258. ExampleCallback(const char* _name, const char* _description)
  259. : entry::AppI(_name, _description)
  260. {
  261. }
  262. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  263. {
  264. Args args(_argc, _argv);
  265. m_width = _width;
  266. m_height = _height;
  267. m_debug = BGFX_DEBUG_NONE;
  268. m_reset = 0
  269. | BGFX_RESET_VSYNC
  270. | BGFX_RESET_CAPTURE
  271. | BGFX_RESET_MSAA_X16
  272. ;
  273. bgfx::init(
  274. args.m_type
  275. , args.m_pciId
  276. , 0
  277. , &m_callback // custom callback handler
  278. , &m_allocator // custom allocator
  279. );
  280. bgfx::reset(m_width, m_height, m_reset);
  281. // Enable debug text.
  282. bgfx::setDebug(m_debug);
  283. // Set view 0 clear state.
  284. bgfx::setViewClear(0
  285. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  286. , 0x303030ff
  287. , 1.0f
  288. , 0
  289. );
  290. // Create vertex stream declaration.
  291. PosColorVertex::init();
  292. // Create static vertex buffer.
  293. m_vbh = bgfx::createVertexBuffer(
  294. bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
  295. , PosColorVertex::ms_decl
  296. );
  297. // Create static index buffer.
  298. m_ibh = bgfx::createIndexBuffer(bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) );
  299. // Create program from shaders.
  300. m_program = loadProgram("vs_callback", "fs_callback");
  301. m_time = 0.0f;
  302. m_frame = 0;
  303. imguiCreate();
  304. }
  305. virtual int shutdown() override
  306. {
  307. imguiDestroy();
  308. // Cleanup.
  309. bgfx::destroy(m_ibh);
  310. bgfx::destroy(m_vbh);
  311. bgfx::destroy(m_program);
  312. // Shutdown bgfx.
  313. bgfx::shutdown();
  314. m_allocator.dumpStats();
  315. return 0;
  316. }
  317. bool update() override
  318. {
  319. bool exit = false;
  320. // 5 second 60Hz video
  321. if (m_frame < 300)
  322. {
  323. ++m_frame;
  324. }
  325. else
  326. {
  327. m_reset &= ~BGFX_RESET_CAPTURE;
  328. exit = entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState);
  329. imguiBeginFrame(m_mouseState.m_mx
  330. , m_mouseState.m_my
  331. , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  332. | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  333. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  334. , m_mouseState.m_mz
  335. , uint16_t(m_width)
  336. , uint16_t(m_height)
  337. );
  338. showExampleDialog(this);
  339. imguiEndFrame();
  340. }
  341. if (!exit)
  342. {
  343. // Set view 0 default viewport.
  344. bgfx::setViewRect(0, 0, 0, bgfx::BackbufferRatio::Equal);
  345. // This dummy draw call is here to make sure that view 0 is cleared
  346. // if no other draw calls are submitted to view 0.
  347. bgfx::touch(0);
  348. float at[3] = { 0.0f, 0.0f, 0.0f };
  349. float eye[3] = { 0.0f, 0.0f, -35.0f };
  350. float view[16];
  351. float proj[16];
  352. bx::mtxLookAt(view, eye, at);
  353. bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f, bgfx::getCaps()->homogeneousDepth);
  354. // Set view and projection matrix for view 0.
  355. bgfx::setViewTransform(0, view, proj);
  356. m_time += 1.0f/60.0f;
  357. // Submit 11x11 cubes.
  358. for (uint32_t yy = 0; yy < 11; ++yy)
  359. {
  360. for (uint32_t xx = 0; xx < 11-yy; ++xx)
  361. {
  362. float mtx[16];
  363. bx::mtxRotateXY(mtx, m_time + xx*0.21f, m_time + yy*0.37f);
  364. mtx[12] = -15.0f + float(xx)*3.0f;
  365. mtx[13] = -15.0f + float(yy)*3.0f;
  366. mtx[14] = 0.0f;
  367. // Set model matrix for rendering.
  368. bgfx::setTransform(mtx);
  369. // Set vertex and index buffer.
  370. bgfx::setVertexBuffer(0, m_vbh);
  371. bgfx::setIndexBuffer(m_ibh);
  372. // Set render states.
  373. bgfx::setState(BGFX_STATE_DEFAULT);
  374. // Submit primitive for rendering to view 0.
  375. bgfx::submit(0, m_program);
  376. }
  377. }
  378. // Take screen shot at frame 150.
  379. if (150 == m_frame)
  380. {
  381. bgfx::FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
  382. bgfx::requestScreenShot(fbh, "temp/frame150");
  383. }
  384. // Advance to next frame. Rendering thread will be kicked to
  385. // process submitted rendering primitives.
  386. bgfx::frame();
  387. return true;
  388. }
  389. return false;
  390. }
  391. BgfxCallback m_callback;
  392. BgfxAllocator m_allocator;
  393. entry::MouseState m_mouseState;
  394. uint32_t m_width;
  395. uint32_t m_height;
  396. uint32_t m_debug;
  397. uint32_t m_reset;
  398. bgfx::VertexBufferHandle m_vbh;
  399. bgfx::IndexBufferHandle m_ibh;
  400. bgfx::ProgramHandle m_program;
  401. float m_time;
  402. uint32_t m_frame;
  403. };
  404. } // namespace
  405. ENTRY_IMPLEMENT_MAIN(ExampleCallback, "07-callback", "Implementing application specific callbacks for taking screen shots, caching OpenGL binary shaders, and video capture.");