callback.cpp 11 KB

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