callback.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. /*
  2. * Copyright 2011-2012 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include <bgfx.h>
  6. #include <bx/bx.h>
  7. #include <bx/timer.h>
  8. #include <bx/readerwriter.h>
  9. #include <bx/string.h>
  10. #include "../common/dbg.h"
  11. #include "../common/math.h"
  12. #include <inttypes.h>
  13. #include <stdio.h>
  14. #include <string.h>
  15. struct PosColorVertex
  16. {
  17. float m_x;
  18. float m_y;
  19. float m_z;
  20. uint32_t m_abgr;
  21. };
  22. static bgfx::VertexDecl s_PosColorDecl;
  23. static PosColorVertex s_cubeVertices[8] =
  24. {
  25. {-1.0f, 1.0f, 1.0f, 0xff000000 },
  26. { 1.0f, 1.0f, 1.0f, 0xff0000ff },
  27. {-1.0f, -1.0f, 1.0f, 0xff00ff00 },
  28. { 1.0f, -1.0f, 1.0f, 0xff00ffff },
  29. {-1.0f, 1.0f, -1.0f, 0xffff0000 },
  30. { 1.0f, 1.0f, -1.0f, 0xffff00ff },
  31. {-1.0f, -1.0f, -1.0f, 0xffffff00 },
  32. { 1.0f, -1.0f, -1.0f, 0xffffffff },
  33. };
  34. static const uint16_t s_cubeIndices[36] =
  35. {
  36. 0, 2, 1, // 0
  37. 1, 2, 3,
  38. 4, 5, 6, // 2
  39. 5, 7, 6,
  40. 0, 4, 2, // 4
  41. 4, 6, 2,
  42. 1, 3, 5, // 6
  43. 5, 3, 7,
  44. 0, 1, 4, // 8
  45. 4, 1, 5,
  46. 2, 6, 3, // 10
  47. 6, 7, 3,
  48. };
  49. static const char* s_shaderPath = NULL;
  50. static void shaderFilePath(char* _out, const char* _name)
  51. {
  52. strcpy(_out, s_shaderPath);
  53. strcat(_out, _name);
  54. strcat(_out, ".bin");
  55. }
  56. long int fsize(FILE* _file)
  57. {
  58. long int pos = ftell(_file);
  59. fseek(_file, 0L, SEEK_END);
  60. long int size = ftell(_file);
  61. fseek(_file, pos, SEEK_SET);
  62. return size;
  63. }
  64. static const bgfx::Memory* load(const char* _filePath)
  65. {
  66. FILE* file = fopen(_filePath, "rb");
  67. if (NULL != file)
  68. {
  69. uint32_t size = (uint32_t)fsize(file);
  70. const bgfx::Memory* mem = bgfx::alloc(size+1);
  71. size_t ignore = fread(mem->data, 1, size, file);
  72. BX_UNUSED(ignore);
  73. fclose(file);
  74. mem->data[mem->size-1] = '\0';
  75. return mem;
  76. }
  77. return NULL;
  78. }
  79. static const bgfx::Memory* loadShader(const char* _name)
  80. {
  81. char filePath[512];
  82. shaderFilePath(filePath, _name);
  83. return load(filePath);
  84. }
  85. void saveTga(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _srcPitch, const void* _src, bool _grayscale, bool _yflip)
  86. {
  87. FILE* file = fopen(_filePath, "wb");
  88. if ( NULL != file )
  89. {
  90. uint8_t type = _grayscale ? 3 : 2;
  91. uint8_t bpp = _grayscale ? 8 : 32;
  92. putc(0, file);
  93. putc(0, file);
  94. putc(type, file);
  95. putc(0, file);
  96. putc(0, file);
  97. putc(0, file);
  98. putc(0, file);
  99. putc(0, file);
  100. putc(0, file);
  101. putc(0, file);
  102. putc(0, file);
  103. putc(0, file);
  104. putc(_width&0xff, file);
  105. putc( (_width>>8)&0xff, file);
  106. putc(_height&0xff, file);
  107. putc( (_height>>8)&0xff, file);
  108. putc(bpp, file);
  109. putc(32, file);
  110. uint32_t dstPitch = _width*bpp/8;
  111. if (_yflip)
  112. {
  113. uint8_t* data = (uint8_t*)_src + _srcPitch*_height - _srcPitch;
  114. for (uint32_t yy = 0; yy < _height; ++yy)
  115. {
  116. fwrite(data, dstPitch, 1, file);
  117. data -= _srcPitch;
  118. }
  119. }
  120. else
  121. {
  122. uint8_t* data = (uint8_t*)_src;
  123. for (uint32_t yy = 0; yy < _height; ++yy)
  124. {
  125. fwrite(data, dstPitch, 1, file);
  126. data += _srcPitch;
  127. }
  128. }
  129. fclose(file);
  130. }
  131. }
  132. // Simple AVI writer. VideoLAN and VirtualDub can decode it.
  133. // Needs some bits to get jiggled to work with other players. But it's good
  134. // enough for an example.
  135. struct AviWriter
  136. {
  137. AviWriter()
  138. : m_frame(NULL)
  139. , m_frameSize(0)
  140. , m_width(0)
  141. , m_height(0)
  142. , m_yflip(false)
  143. {
  144. }
  145. bool open(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _fps, bool _yflip)
  146. {
  147. if (0 != m_writer.open(_filePath) )
  148. {
  149. return false;
  150. }
  151. m_frameSize = _width * _height * 3;
  152. m_frame = new uint8_t[m_frameSize + 8];
  153. m_width = _width;
  154. m_height = _height;
  155. // Bgfx returns _yflip true for OpenGL since bottom left corner is 0, 0. In D3D top left corner
  156. // is 0, 0. DIB expect OpenGL style coordinates, so this is inverted logic for AVI writer.
  157. m_yflip = !_yflip;
  158. bx::StaticMemoryBlockWriter mem(m_frame, 8);
  159. // Stream Data (LIST 'movi' Chunk) http://msdn.microsoft.com/en-us/library/ms899496.aspx
  160. bx::write(&mem, BX_MAKEFOURCC('0', '0', 'd', 'b') );
  161. bx::write(&mem, m_frameSize);
  162. bx::write(&m_writer, BX_MAKEFOURCC('R', 'I', 'F', 'F') );
  163. bx::write(&m_writer, UINT32_C(0) );
  164. bx::write(&m_writer, BX_MAKEFOURCC('A', 'V', 'I', ' ') );
  165. // AVI RIFF Form http://msdn.microsoft.com/en-us/library/ms899422.aspx
  166. bx::write(&m_writer, BX_MAKEFOURCC('L', 'I', 'S', 'T') );
  167. bx::write(&m_writer, UINT32_C(196) );
  168. bx::write(&m_writer, BX_MAKEFOURCC('h', 'd', 'r', 'l') );
  169. // AVI Main Header http://msdn.microsoft.com/en-us/library/ms779632.aspx
  170. bx::write(&m_writer, BX_MAKEFOURCC('a', 'v', 'i', 'h') );
  171. bx::write(&m_writer, UINT32_C(56) );
  172. bx::write(&m_writer, UINT32_C(0) ); // dwMicroSecPerFrame
  173. bx::write(&m_writer, UINT32_C(0) ); // dwMaxBytesPerSec
  174. bx::write(&m_writer, UINT32_C(0) ); // dwPaddingGranularity
  175. bx::write(&m_writer, UINT32_C(0) ); // dwFlags
  176. bx::write(&m_writer, UINT32_C(0) ); // dwTotalFrames
  177. bx::write(&m_writer, UINT32_C(0) ); // dwInitialFrames
  178. bx::write(&m_writer, UINT32_C(1) ); // dwStreams
  179. bx::write(&m_writer, UINT32_C(0) ); // dwSuggestedBufferSize
  180. bx::write(&m_writer, _width); // dwWidth
  181. bx::write(&m_writer, _height); // dwHeight
  182. bx::write(&m_writer, UINT32_C(0) ); // dwReserved0
  183. bx::write(&m_writer, UINT32_C(0) ); // dwReserved1
  184. bx::write(&m_writer, UINT32_C(0) ); // dwReserved2
  185. bx::write(&m_writer, UINT32_C(0) ); // dwReserved3
  186. bx::write(&m_writer, BX_MAKEFOURCC('L', 'I', 'S', 'T') );
  187. bx::write(&m_writer, UINT32_C(120) );
  188. bx::write(&m_writer, BX_MAKEFOURCC('s', 't', 'r', 'l') );
  189. // AVISTREAMHEADER Structure http://msdn.microsoft.com/en-us/library/ms779638.aspx
  190. bx::write(&m_writer, BX_MAKEFOURCC('s', 't', 'r', 'h') );
  191. bx::write(&m_writer, UINT32_C(56) );
  192. // AVI Stream Headers http://msdn.microsoft.com/en-us/library/ms899423.aspx
  193. bx::write(&m_writer, BX_MAKEFOURCC('v', 'i', 'd', 's') ); // fccType
  194. bx::write(&m_writer, BX_MAKEFOURCC('D', 'I', 'B', ' ') ); // fccHandler
  195. bx::write(&m_writer, UINT32_C(0) ); // dwFlags
  196. bx::write(&m_writer, UINT16_C(0) ); // wPriority
  197. bx::write(&m_writer, UINT16_C(0) ); // wLanguage
  198. bx::write(&m_writer, UINT32_C(0) ); // dwInitialFrames
  199. bx::write(&m_writer, UINT32_C(1000) ); // dwScale
  200. bx::write(&m_writer, 1000*_fps); // dwRate
  201. bx::write(&m_writer, UINT32_C(0) ); // dwStart
  202. bx::write(&m_writer, UINT32_C(0) ); // dwLength
  203. bx::write(&m_writer, UINT32_C(0) ); // dwSuggestedBufferSize
  204. bx::write(&m_writer, UINT32_C(0) ); // dwQuality
  205. bx::write(&m_writer, UINT32_C(0) ); // dwSampleSize
  206. bx::write(&m_writer, INT16_C(0) ); // rcFrame.left
  207. bx::write(&m_writer, INT16_C(0) ); // rcFrame.top
  208. bx::write(&m_writer, INT16_C(0) ); // rcFrame.right
  209. bx::write(&m_writer, INT16_C(0) ); // rcFrame.bottom
  210. bx::write(&m_writer, BX_MAKEFOURCC('s', 't', 'r', 'f') );
  211. bx::write(&m_writer, UINT32_C(44) );
  212. // BITMAPINFOHEADER structure http://msdn.microsoft.com/en-us/library/windows/desktop/dd318229%28v=vs.85%29.aspx
  213. bx::write(&m_writer, UINT32_C(40) ); // biSize
  214. bx::write(&m_writer, _width); // biWidth
  215. bx::write(&m_writer, _height); // biHeight
  216. bx::write(&m_writer, UINT16_C(1) ); // biPlanes
  217. bx::write(&m_writer, UINT16_C(24) ); // biBitCount
  218. bx::write(&m_writer, UINT32_C(0) ); // biCompression
  219. bx::write(&m_writer, UINT32_C(0) ); // biSizeImage
  220. bx::write(&m_writer, UINT32_C(0) ); // biXPelsPerMeter
  221. bx::write(&m_writer, UINT32_C(0) ); // biYPelsPerMeter
  222. bx::write(&m_writer, UINT32_C(0) ); // biClrUsed
  223. bx::write(&m_writer, UINT32_C(0) ); // biClrImportant
  224. bx::write(&m_writer, UINT32_C(0) );
  225. bx::write(&m_writer, BX_MAKEFOURCC('L', 'I', 'S', 'T') );
  226. bx::write(&m_writer, UINT32_C(0) );
  227. bx::write(&m_writer, BX_MAKEFOURCC('m', 'o', 'v', 'i') );
  228. return true;
  229. }
  230. void close()
  231. {
  232. if (NULL != m_frame)
  233. {
  234. m_writer.close();
  235. delete [] m_frame;
  236. m_frame = NULL;
  237. m_frameSize = 0;
  238. }
  239. }
  240. void frame(const void* _data)
  241. {
  242. if (NULL != m_frame)
  243. {
  244. uint32_t width = m_width;
  245. uint32_t height = m_height;
  246. uint8_t* bgr = &m_frame[8];
  247. if (m_yflip)
  248. {
  249. for (uint32_t yy = 0; yy < height; ++yy)
  250. {
  251. const uint8_t* bgra = (const uint8_t*)_data + (height-1-yy)*width*4;
  252. for (uint32_t ii = 0; ii < width; ++ii)
  253. {
  254. bgr[0] = bgra[0];
  255. bgr[1] = bgra[1];
  256. bgr[2] = bgra[2];
  257. bgr += 3;
  258. bgra += 4;
  259. }
  260. }
  261. }
  262. else
  263. {
  264. const uint8_t* bgra = (const uint8_t*)_data;
  265. for (uint32_t ii = 0, num = m_frameSize/3; ii < num; ++ii)
  266. {
  267. bgr[0] = bgra[0];
  268. bgr[1] = bgra[1];
  269. bgr[2] = bgra[2];
  270. bgr += 3;
  271. bgra += 4;
  272. }
  273. }
  274. bx::write(&m_writer, m_frame, m_frameSize+8);
  275. }
  276. }
  277. bx::CrtFileWriter m_writer;
  278. uint8_t* m_frame;
  279. uint32_t m_frameSize;
  280. uint32_t m_width;
  281. uint32_t m_height;
  282. bool m_yflip;
  283. };
  284. struct BgfxCallback : public bgfx::CallbackI
  285. {
  286. virtual ~BgfxCallback()
  287. {
  288. }
  289. virtual void fatal(bgfx::Fatal::Enum _code, const char* _str) BX_OVERRIDE
  290. {
  291. // Something unexpected happened, inform user and bail out.
  292. dbgPrintf("Fatal error: 0x%08x: %s", _code, _str);
  293. // Must terminate, continuing will cause crash anyway.
  294. abort();
  295. }
  296. virtual uint32_t cacheReadSize(uint64_t _id) BX_OVERRIDE
  297. {
  298. char filePath[256];
  299. bx::snprintf(filePath, sizeof(filePath), "%016" PRIx64, _id);
  300. // Use cache id as filename.
  301. FILE* file = fopen(filePath, "rb");
  302. if (NULL != file)
  303. {
  304. uint32_t size = fsize(file);
  305. fclose(file);
  306. // Return size of shader file.
  307. return size;
  308. }
  309. // Return 0 if shader is not found.
  310. return 0;
  311. }
  312. virtual bool cacheRead(uint64_t _id, void* _data, uint32_t _size) BX_OVERRIDE
  313. {
  314. char filePath[256];
  315. bx::snprintf(filePath, sizeof(filePath), "%016" PRIx64, _id);
  316. // Use cache id as filename.
  317. FILE* file = fopen(filePath, "rb");
  318. if (NULL != file)
  319. {
  320. // Read shader.
  321. size_t result = fread(_data, 1, _size, file);
  322. fclose(file);
  323. // Make sure that read size matches requested size.
  324. return result == _size;
  325. }
  326. // Shader is not found in cache, needs to be rebuilt.
  327. return false;
  328. }
  329. virtual void cacheWrite(uint64_t _id, const void* _data, uint32_t _size) BX_OVERRIDE
  330. {
  331. char filePath[256];
  332. bx::snprintf(filePath, sizeof(filePath), "%016" PRIx64, _id);
  333. // Use cache id as filename.
  334. FILE* file = fopen(filePath, "wb");
  335. if (NULL != file)
  336. {
  337. // Write shader to cache location.
  338. fwrite(_data, 1, _size, file);
  339. fclose(file);
  340. }
  341. }
  342. 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
  343. {
  344. // Save screen shot as TGA.
  345. saveTga(_filePath, _width, _height, _pitch, _data, false, _yflip);
  346. }
  347. virtual void captureBegin(uint32_t _width, uint32_t _height, uint32_t _pitch, bgfx::TextureFormat::Enum /*_format*/, bool _yflip) BX_OVERRIDE
  348. {
  349. m_writer = new AviWriter;
  350. if (!m_writer->open("capture.avi", _width, _height, 60, _yflip) )
  351. {
  352. delete m_writer;
  353. m_writer = NULL;
  354. }
  355. }
  356. virtual void captureEnd() BX_OVERRIDE
  357. {
  358. if (NULL != m_writer)
  359. {
  360. m_writer->close();
  361. }
  362. }
  363. virtual void captureFrame(const void* _data, uint32_t /*_size*/) BX_OVERRIDE
  364. {
  365. if (NULL != m_writer)
  366. {
  367. m_writer->frame(_data);
  368. }
  369. }
  370. AviWriter* m_writer;
  371. };
  372. int _main_(int _argc, char** _argv)
  373. {
  374. BgfxCallback callback;
  375. bgfx::init(&callback);
  376. bgfx::reset(1280, 720, BGFX_RESET_CAPTURE);
  377. // Enable debug text.
  378. bgfx::setDebug(BGFX_DEBUG_TEXT);
  379. // Set view 0 default viewport.
  380. bgfx::setViewRect(0, 0, 0, 1280, 720);
  381. // Set view 0 clear state.
  382. bgfx::setViewClear(0
  383. , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT
  384. , 0x303030ff
  385. , 1.0f
  386. , 0
  387. );
  388. // Setup root path for binary shaders. Shader binaries are different
  389. // for each renderer.
  390. switch (bgfx::getRendererType() )
  391. {
  392. default:
  393. case bgfx::RendererType::Direct3D9:
  394. s_shaderPath = "shaders/dx9/";
  395. break;
  396. case bgfx::RendererType::Direct3D11:
  397. s_shaderPath = "shaders/dx11/";
  398. break;
  399. case bgfx::RendererType::OpenGL:
  400. s_shaderPath = "shaders/glsl/";
  401. break;
  402. case bgfx::RendererType::OpenGLES2:
  403. case bgfx::RendererType::OpenGLES3:
  404. s_shaderPath = "shaders/gles/";
  405. break;
  406. }
  407. // Create vertex stream declaration.
  408. s_PosColorDecl.begin();
  409. s_PosColorDecl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float);
  410. s_PosColorDecl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true);
  411. s_PosColorDecl.end();
  412. const bgfx::Memory* mem;
  413. // Create static vertex buffer.
  414. mem = bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) );
  415. bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(mem, s_PosColorDecl);
  416. // Create static index buffer.
  417. mem = bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) );
  418. bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(mem);
  419. // Load vertex shader.
  420. mem = loadShader("vs_callback");
  421. bgfx::VertexShaderHandle vsh = bgfx::createVertexShader(mem);
  422. // Load fragment shader.
  423. mem = loadShader("fs_callback");
  424. bgfx::FragmentShaderHandle fsh = bgfx::createFragmentShader(mem);
  425. // Create program from shaders.
  426. bgfx::ProgramHandle program = bgfx::createProgram(vsh, fsh);
  427. // We can destroy vertex and fragment shader here since
  428. // their reference is kept inside bgfx after calling createProgram.
  429. // Vertex and fragment shader will be destroyed once program is
  430. // destroyed.
  431. bgfx::destroyVertexShader(vsh);
  432. bgfx::destroyFragmentShader(fsh);
  433. float time = 0.0f;
  434. // 5 second 60Hz video
  435. for (uint32_t frame = 0; frame < 300; ++frame)
  436. {
  437. // This dummy draw call is here to make sure that view 0 is cleared
  438. // if no other draw calls are submitted to view 0.
  439. bgfx::submit(0);
  440. int64_t now = bx::getHPCounter();
  441. static int64_t last = now;
  442. const int64_t frameTime = now - last;
  443. last = now;
  444. const double freq = double(bx::getHPFrequency() );
  445. const double toMs = 1000.0/freq;
  446. // Use debug font to print information about this example.
  447. bgfx::dbgTextClear();
  448. bgfx::dbgTextPrintf( 0, 1, 0x4f, "bgfx/examples/07-callback");
  449. bgfx::dbgTextPrintf( 0, 2, 0x6f, "Description: Implementing application specific callbacks for taking screen shots,");
  450. bgfx::dbgTextPrintf(13, 3, 0x6f, "caching OpenGL binary shaders, and video capture.");
  451. bgfx::dbgTextPrintf( 0, 4, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);
  452. float at[3] = { 0.0f, 0.0f, 0.0f };
  453. float eye[3] = { 0.0f, 0.0f, -35.0f };
  454. float view[16];
  455. float proj[16];
  456. mtxLookAt(view, eye, at);
  457. mtxProj(proj, 60.0f, 16.0f/9.0f, 0.1f, 100.0f);
  458. // Set view and projection matrix for view 0.
  459. bgfx::setViewTransform(0, view, proj);
  460. time += 1.0f/60.0f;
  461. // Submit 11x11 cubes.
  462. for (uint32_t yy = 0; yy < 11; ++yy)
  463. {
  464. for (uint32_t xx = 0; xx < 11-yy; ++xx)
  465. {
  466. float mtx[16];
  467. mtxRotateXY(mtx, time + xx*0.21f, time + yy*0.37f);
  468. mtx[12] = -15.0f + float(xx)*3.0f;
  469. mtx[13] = -15.0f + float(yy)*3.0f;
  470. mtx[14] = 0.0f;
  471. // Set model matrix for rendering.
  472. bgfx::setTransform(mtx);
  473. // Set vertex and fragment shaders.
  474. bgfx::setProgram(program);
  475. // Set vertex and index buffer.
  476. bgfx::setVertexBuffer(vbh);
  477. bgfx::setIndexBuffer(ibh);
  478. // Set render states.
  479. bgfx::setState(BGFX_STATE_RGB_WRITE
  480. |BGFX_STATE_DEPTH_WRITE
  481. |BGFX_STATE_DEPTH_TEST_LESS
  482. );
  483. // Submit primitive for rendering to view 0.
  484. bgfx::submit(0);
  485. }
  486. }
  487. // Take screen shot at frame 150.
  488. if (150 == frame)
  489. {
  490. bgfx::saveScreenShot("frame150.tga");
  491. }
  492. // Advance to next frame. Rendering thread will be kicked to
  493. // process submitted rendering primitives.
  494. bgfx::frame();
  495. }
  496. // Cleanup.
  497. bgfx::destroyIndexBuffer(ibh);
  498. bgfx::destroyVertexBuffer(vbh);
  499. bgfx::destroyProgram(program);
  500. // Shutdown bgfx.
  501. bgfx::shutdown();
  502. return 0;
  503. }