debug_utils.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <condition_variable>
  6. #include <cstring>
  7. #include <fstream>
  8. #include <list>
  9. #include <map>
  10. #include <mutex>
  11. #include <string>
  12. #ifdef HAVE_PNG
  13. #include <png.h>
  14. #endif
  15. #include <nihstro/float24.h>
  16. #include <nihstro/shader_binary.h>
  17. #include "common/assert.h"
  18. #include "common/color.h"
  19. #include "common/common_types.h"
  20. #include "common/file_util.h"
  21. #include "common/math_util.h"
  22. #include "common/vector_math.h"
  23. #include "core/settings.h"
  24. #include "video_core/pica.h"
  25. #include "video_core/pica_state.h"
  26. #include "video_core/renderer_base.h"
  27. #include "video_core/utils.h"
  28. #include "video_core/video_core.h"
  29. #include "video_core/debug_utils/debug_utils.h"
  30. using nihstro::DVLBHeader;
  31. using nihstro::DVLEHeader;
  32. using nihstro::DVLPHeader;
  33. namespace Pica {
  34. void DebugContext::OnEvent(Event event, void* data) {
  35. if (!breakpoints[event].enabled)
  36. return;
  37. {
  38. std::unique_lock<std::mutex> lock(breakpoint_mutex);
  39. // Commit the hardware renderer's framebuffer so it will show on debug widgets
  40. VideoCore::g_renderer->Rasterizer()->FlushFramebuffer();
  41. // TODO: Should stop the CPU thread here once we multithread emulation.
  42. active_breakpoint = event;
  43. at_breakpoint = true;
  44. // Tell all observers that we hit a breakpoint
  45. for (auto& breakpoint_observer : breakpoint_observers) {
  46. breakpoint_observer->OnPicaBreakPointHit(event, data);
  47. }
  48. // Wait until another thread tells us to Resume()
  49. resume_from_breakpoint.wait(lock, [&]{ return !at_breakpoint; });
  50. }
  51. }
  52. void DebugContext::Resume() {
  53. {
  54. std::lock_guard<std::mutex> lock(breakpoint_mutex);
  55. // Tell all observers that we are about to resume
  56. for (auto& breakpoint_observer : breakpoint_observers) {
  57. breakpoint_observer->OnPicaResume();
  58. }
  59. // Resume the waiting thread (i.e. OnEvent())
  60. at_breakpoint = false;
  61. }
  62. resume_from_breakpoint.notify_one();
  63. }
  64. std::shared_ptr<DebugContext> g_debug_context; // TODO: Get rid of this global
  65. namespace DebugUtils {
  66. void DumpShader(const std::string& filename, const Regs::ShaderConfig& config, const Shader::ShaderSetup& setup, const Regs::VSOutputAttributes* output_attributes)
  67. {
  68. struct StuffToWrite {
  69. const u8* pointer;
  70. u32 size;
  71. };
  72. std::vector<StuffToWrite> writing_queue;
  73. u32 write_offset = 0;
  74. auto QueueForWriting = [&writing_queue,&write_offset](const u8* pointer, u32 size) {
  75. writing_queue.push_back({pointer, size});
  76. u32 old_write_offset = write_offset;
  77. write_offset += size;
  78. return old_write_offset;
  79. };
  80. // First off, try to translate Pica state (one enum for output attribute type and component)
  81. // into shbin format (separate type and component mask).
  82. union OutputRegisterInfo {
  83. enum Type : u64 {
  84. POSITION = 0,
  85. QUATERNION = 1,
  86. COLOR = 2,
  87. TEXCOORD0 = 3,
  88. TEXCOORD1 = 5,
  89. TEXCOORD2 = 6,
  90. VIEW = 8,
  91. };
  92. BitField< 0, 64, u64> hex;
  93. BitField< 0, 16, Type> type;
  94. BitField<16, 16, u64> id;
  95. BitField<32, 4, u64> component_mask;
  96. };
  97. // This is put into a try-catch block to make sure we notice unknown configurations.
  98. std::vector<OutputRegisterInfo> output_info_table;
  99. for (unsigned i = 0; i < 7; ++i) {
  100. using OutputAttributes = Pica::Regs::VSOutputAttributes;
  101. // TODO: It's still unclear how the attribute components map to the register!
  102. // Once we know that, this code probably will not make much sense anymore.
  103. std::map<OutputAttributes::Semantic, std::pair<OutputRegisterInfo::Type, u32> > map = {
  104. { OutputAttributes::POSITION_X, { OutputRegisterInfo::POSITION, 1} },
  105. { OutputAttributes::POSITION_Y, { OutputRegisterInfo::POSITION, 2} },
  106. { OutputAttributes::POSITION_Z, { OutputRegisterInfo::POSITION, 4} },
  107. { OutputAttributes::POSITION_W, { OutputRegisterInfo::POSITION, 8} },
  108. { OutputAttributes::QUATERNION_X, { OutputRegisterInfo::QUATERNION, 1} },
  109. { OutputAttributes::QUATERNION_Y, { OutputRegisterInfo::QUATERNION, 2} },
  110. { OutputAttributes::QUATERNION_Z, { OutputRegisterInfo::QUATERNION, 4} },
  111. { OutputAttributes::QUATERNION_W, { OutputRegisterInfo::QUATERNION, 8} },
  112. { OutputAttributes::COLOR_R, { OutputRegisterInfo::COLOR, 1} },
  113. { OutputAttributes::COLOR_G, { OutputRegisterInfo::COLOR, 2} },
  114. { OutputAttributes::COLOR_B, { OutputRegisterInfo::COLOR, 4} },
  115. { OutputAttributes::COLOR_A, { OutputRegisterInfo::COLOR, 8} },
  116. { OutputAttributes::TEXCOORD0_U, { OutputRegisterInfo::TEXCOORD0, 1} },
  117. { OutputAttributes::TEXCOORD0_V, { OutputRegisterInfo::TEXCOORD0, 2} },
  118. { OutputAttributes::TEXCOORD1_U, { OutputRegisterInfo::TEXCOORD1, 1} },
  119. { OutputAttributes::TEXCOORD1_V, { OutputRegisterInfo::TEXCOORD1, 2} },
  120. { OutputAttributes::TEXCOORD2_U, { OutputRegisterInfo::TEXCOORD2, 1} },
  121. { OutputAttributes::TEXCOORD2_V, { OutputRegisterInfo::TEXCOORD2, 2} },
  122. { OutputAttributes::VIEW_X, { OutputRegisterInfo::VIEW, 1} },
  123. { OutputAttributes::VIEW_Y, { OutputRegisterInfo::VIEW, 2} },
  124. { OutputAttributes::VIEW_Z, { OutputRegisterInfo::VIEW, 4} }
  125. };
  126. for (const auto& semantic : std::vector<OutputAttributes::Semantic>{
  127. output_attributes[i].map_x,
  128. output_attributes[i].map_y,
  129. output_attributes[i].map_z,
  130. output_attributes[i].map_w }) {
  131. if (semantic == OutputAttributes::INVALID)
  132. continue;
  133. try {
  134. OutputRegisterInfo::Type type = map.at(semantic).first;
  135. u32 component_mask = map.at(semantic).second;
  136. auto it = std::find_if(output_info_table.begin(), output_info_table.end(),
  137. [&i, &type](const OutputRegisterInfo& info) {
  138. return info.id == i && info.type == type;
  139. }
  140. );
  141. if (it == output_info_table.end()) {
  142. output_info_table.emplace_back();
  143. output_info_table.back().type.Assign(type);
  144. output_info_table.back().component_mask.Assign(component_mask);
  145. output_info_table.back().id.Assign(i);
  146. } else {
  147. it->component_mask.Assign(it->component_mask | component_mask);
  148. }
  149. } catch (const std::out_of_range& ) {
  150. DEBUG_ASSERT_MSG(false, "Unknown output attribute mapping");
  151. LOG_ERROR(HW_GPU, "Unknown output attribute mapping: %03x, %03x, %03x, %03x",
  152. (int)output_attributes[i].map_x.Value(),
  153. (int)output_attributes[i].map_y.Value(),
  154. (int)output_attributes[i].map_z.Value(),
  155. (int)output_attributes[i].map_w.Value());
  156. }
  157. }
  158. }
  159. struct {
  160. DVLBHeader header;
  161. u32 dvle_offset;
  162. } dvlb{ {DVLBHeader::MAGIC_WORD, 1 } }; // 1 DVLE
  163. DVLPHeader dvlp{ DVLPHeader::MAGIC_WORD };
  164. DVLEHeader dvle{ DVLEHeader::MAGIC_WORD };
  165. QueueForWriting(reinterpret_cast<const u8*>(&dvlb), sizeof(dvlb));
  166. u32 dvlp_offset = QueueForWriting(reinterpret_cast<const u8*>(&dvlp), sizeof(dvlp));
  167. dvlb.dvle_offset = QueueForWriting(reinterpret_cast<const u8*>(&dvle), sizeof(dvle));
  168. // TODO: Reduce the amount of binary code written to relevant portions
  169. dvlp.binary_offset = write_offset - dvlp_offset;
  170. dvlp.binary_size_words = setup.program_code.size();
  171. QueueForWriting(reinterpret_cast<const u8*>(setup.program_code.data()), setup.program_code.size() * sizeof(u32));
  172. dvlp.swizzle_info_offset = write_offset - dvlp_offset;
  173. dvlp.swizzle_info_num_entries = setup.swizzle_data.size();
  174. u32 dummy = 0;
  175. for (unsigned int i = 0; i < setup.swizzle_data.size(); ++i) {
  176. QueueForWriting(reinterpret_cast<const u8*>(&setup.swizzle_data[i]), sizeof(setup.swizzle_data[i]));
  177. QueueForWriting(reinterpret_cast<const u8*>(&dummy), sizeof(dummy));
  178. }
  179. dvle.main_offset_words = config.main_offset;
  180. dvle.output_register_table_offset = write_offset - dvlb.dvle_offset;
  181. dvle.output_register_table_size = static_cast<u32>(output_info_table.size());
  182. QueueForWriting(reinterpret_cast<const u8*>(output_info_table.data()), static_cast<u32>(output_info_table.size() * sizeof(OutputRegisterInfo)));
  183. // TODO: Create a label table for "main"
  184. std::vector<nihstro::ConstantInfo> constant_table;
  185. for (unsigned i = 0; i < setup.uniforms.b.size(); ++i) {
  186. nihstro::ConstantInfo constant;
  187. memset(&constant, 0, sizeof(constant));
  188. constant.type = nihstro::ConstantInfo::Bool;
  189. constant.regid = i;
  190. constant.b = setup.uniforms.b[i];
  191. constant_table.emplace_back(constant);
  192. }
  193. for (unsigned i = 0; i < setup.uniforms.i.size(); ++i) {
  194. nihstro::ConstantInfo constant;
  195. memset(&constant, 0, sizeof(constant));
  196. constant.type = nihstro::ConstantInfo::Int;
  197. constant.regid = i;
  198. constant.i.x = setup.uniforms.i[i].x;
  199. constant.i.y = setup.uniforms.i[i].y;
  200. constant.i.z = setup.uniforms.i[i].z;
  201. constant.i.w = setup.uniforms.i[i].w;
  202. constant_table.emplace_back(constant);
  203. }
  204. for (unsigned i = 0; i < sizeof(setup.uniforms.f) / sizeof(setup.uniforms.f[0]); ++i) {
  205. nihstro::ConstantInfo constant;
  206. memset(&constant, 0, sizeof(constant));
  207. constant.type = nihstro::ConstantInfo::Float;
  208. constant.regid = i;
  209. constant.f.x = nihstro::to_float24(setup.uniforms.f[i].x.ToFloat32());
  210. constant.f.y = nihstro::to_float24(setup.uniforms.f[i].y.ToFloat32());
  211. constant.f.z = nihstro::to_float24(setup.uniforms.f[i].z.ToFloat32());
  212. constant.f.w = nihstro::to_float24(setup.uniforms.f[i].w.ToFloat32());
  213. // Store constant if it's different from zero..
  214. if (setup.uniforms.f[i].x.ToFloat32() != 0.0 ||
  215. setup.uniforms.f[i].y.ToFloat32() != 0.0 ||
  216. setup.uniforms.f[i].z.ToFloat32() != 0.0 ||
  217. setup.uniforms.f[i].w.ToFloat32() != 0.0)
  218. constant_table.emplace_back(constant);
  219. }
  220. dvle.constant_table_offset = write_offset - dvlb.dvle_offset;
  221. dvle.constant_table_size = constant_table.size();
  222. for (const auto& constant : constant_table) {
  223. QueueForWriting(reinterpret_cast<const u8*>(&constant), sizeof(constant));
  224. }
  225. // Write data to file
  226. std::ofstream file(filename, std::ios_base::out | std::ios_base::binary);
  227. for (const auto& chunk : writing_queue) {
  228. file.write(reinterpret_cast<const char*>(chunk.pointer), chunk.size);
  229. }
  230. }
  231. static std::unique_ptr<PicaTrace> pica_trace;
  232. static std::mutex pica_trace_mutex;
  233. static int is_pica_tracing = false;
  234. void StartPicaTracing()
  235. {
  236. if (is_pica_tracing) {
  237. LOG_WARNING(HW_GPU, "StartPicaTracing called even though tracing already running!");
  238. return;
  239. }
  240. std::lock_guard<std::mutex> lock(pica_trace_mutex);
  241. pica_trace = std::make_unique<PicaTrace>();
  242. is_pica_tracing = true;
  243. }
  244. bool IsPicaTracing()
  245. {
  246. return is_pica_tracing != 0;
  247. }
  248. void OnPicaRegWrite(PicaTrace::Write write)
  249. {
  250. // Double check for is_pica_tracing to avoid pointless locking overhead
  251. if (!is_pica_tracing)
  252. return;
  253. std::lock_guard<std::mutex> lock(pica_trace_mutex);
  254. if (!is_pica_tracing)
  255. return;
  256. pica_trace->writes.push_back(write);
  257. }
  258. std::unique_ptr<PicaTrace> FinishPicaTracing()
  259. {
  260. if (!is_pica_tracing) {
  261. LOG_WARNING(HW_GPU, "FinishPicaTracing called even though tracing isn't running!");
  262. return {};
  263. }
  264. // signalize that no further tracing should be performed
  265. is_pica_tracing = false;
  266. // Wait until running tracing is finished
  267. std::lock_guard<std::mutex> lock(pica_trace_mutex);
  268. std::unique_ptr<PicaTrace> ret(std::move(pica_trace));
  269. return std::move(ret);
  270. }
  271. const Math::Vec4<u8> LookupTexture(const u8* source, int x, int y, const TextureInfo& info, bool disable_alpha) {
  272. const unsigned int coarse_x = x & ~7;
  273. const unsigned int coarse_y = y & ~7;
  274. if (info.format != Regs::TextureFormat::ETC1 &&
  275. info.format != Regs::TextureFormat::ETC1A4) {
  276. // TODO(neobrain): Fix code design to unify vertical block offsets!
  277. source += coarse_y * info.stride;
  278. }
  279. // TODO: Assert that width/height are multiples of block dimensions
  280. switch (info.format) {
  281. case Regs::TextureFormat::RGBA8:
  282. {
  283. auto res = Color::DecodeRGBA8(source + VideoCore::GetMortonOffset(x, y, 4));
  284. return { res.r(), res.g(), res.b(), static_cast<u8>(disable_alpha ? 255 : res.a()) };
  285. }
  286. case Regs::TextureFormat::RGB8:
  287. {
  288. auto res = Color::DecodeRGB8(source + VideoCore::GetMortonOffset(x, y, 3));
  289. return { res.r(), res.g(), res.b(), 255 };
  290. }
  291. case Regs::TextureFormat::RGB5A1:
  292. {
  293. auto res = Color::DecodeRGB5A1(source + VideoCore::GetMortonOffset(x, y, 2));
  294. return { res.r(), res.g(), res.b(), static_cast<u8>(disable_alpha ? 255 : res.a()) };
  295. }
  296. case Regs::TextureFormat::RGB565:
  297. {
  298. auto res = Color::DecodeRGB565(source + VideoCore::GetMortonOffset(x, y, 2));
  299. return { res.r(), res.g(), res.b(), 255 };
  300. }
  301. case Regs::TextureFormat::RGBA4:
  302. {
  303. auto res = Color::DecodeRGBA4(source + VideoCore::GetMortonOffset(x, y, 2));
  304. return { res.r(), res.g(), res.b(), static_cast<u8>(disable_alpha ? 255 : res.a()) };
  305. }
  306. case Regs::TextureFormat::IA8:
  307. {
  308. const u8* source_ptr = source + VideoCore::GetMortonOffset(x, y, 2);
  309. if (disable_alpha) {
  310. // Show intensity as red, alpha as green
  311. return { source_ptr[1], source_ptr[0], 0, 255 };
  312. } else {
  313. return { source_ptr[1], source_ptr[1], source_ptr[1], source_ptr[0] };
  314. }
  315. }
  316. case Regs::TextureFormat::RG8:
  317. {
  318. auto res = Color::DecodeRG8(source + VideoCore::GetMortonOffset(x, y, 2));
  319. return { res.r(), res.g(), 0, 255 };
  320. }
  321. case Regs::TextureFormat::I8:
  322. {
  323. const u8* source_ptr = source + VideoCore::GetMortonOffset(x, y, 1);
  324. return { *source_ptr, *source_ptr, *source_ptr, 255 };
  325. }
  326. case Regs::TextureFormat::A8:
  327. {
  328. const u8* source_ptr = source + VideoCore::GetMortonOffset(x, y, 1);
  329. if (disable_alpha) {
  330. return { *source_ptr, *source_ptr, *source_ptr, 255 };
  331. } else {
  332. return { 0, 0, 0, *source_ptr };
  333. }
  334. }
  335. case Regs::TextureFormat::IA4:
  336. {
  337. const u8* source_ptr = source + VideoCore::GetMortonOffset(x, y, 1);
  338. u8 i = Color::Convert4To8(((*source_ptr) & 0xF0) >> 4);
  339. u8 a = Color::Convert4To8((*source_ptr) & 0xF);
  340. if (disable_alpha) {
  341. // Show intensity as red, alpha as green
  342. return { i, a, 0, 255 };
  343. } else {
  344. return { i, i, i, a };
  345. }
  346. }
  347. case Regs::TextureFormat::I4:
  348. {
  349. u32 morton_offset = VideoCore::GetMortonOffset(x, y, 1);
  350. const u8* source_ptr = source + morton_offset / 2;
  351. u8 i = (morton_offset % 2) ? ((*source_ptr & 0xF0) >> 4) : (*source_ptr & 0xF);
  352. i = Color::Convert4To8(i);
  353. return { i, i, i, 255 };
  354. }
  355. case Regs::TextureFormat::A4:
  356. {
  357. u32 morton_offset = VideoCore::GetMortonOffset(x, y, 1);
  358. const u8* source_ptr = source + morton_offset / 2;
  359. u8 a = (morton_offset % 2) ? ((*source_ptr & 0xF0) >> 4) : (*source_ptr & 0xF);
  360. a = Color::Convert4To8(a);
  361. if (disable_alpha) {
  362. return { a, a, a, 255 };
  363. } else {
  364. return { 0, 0, 0, a };
  365. }
  366. }
  367. case Regs::TextureFormat::ETC1:
  368. case Regs::TextureFormat::ETC1A4:
  369. {
  370. bool has_alpha = (info.format == Regs::TextureFormat::ETC1A4);
  371. // ETC1 further subdivides each 8x8 tile into four 4x4 subtiles
  372. const int subtile_width = 4;
  373. const int subtile_height = 4;
  374. int subtile_index = ((x / subtile_width) & 1) + 2 * ((y / subtile_height) & 1);
  375. unsigned subtile_bytes = has_alpha ? 2 : 1; // TODO: Name...
  376. const u64* source_ptr = (const u64*)(source
  377. + coarse_x * subtile_bytes * 4
  378. + coarse_y * subtile_bytes * 4 * (info.width / 8)
  379. + subtile_index * subtile_bytes * 8);
  380. u64 alpha = 0xFFFFFFFFFFFFFFFF;
  381. if (has_alpha) {
  382. alpha = *source_ptr;
  383. source_ptr++;
  384. }
  385. union ETC1Tile {
  386. // Each of these two is a collection of 16 bits (one per lookup value)
  387. BitField< 0, 16, u64> table_subindexes;
  388. BitField<16, 16, u64> negation_flags;
  389. unsigned GetTableSubIndex(unsigned index) const {
  390. return (table_subindexes >> index) & 1;
  391. }
  392. bool GetNegationFlag(unsigned index) const {
  393. return ((negation_flags >> index) & 1) == 1;
  394. }
  395. BitField<32, 1, u64> flip;
  396. BitField<33, 1, u64> differential_mode;
  397. BitField<34, 3, u64> table_index_2;
  398. BitField<37, 3, u64> table_index_1;
  399. union {
  400. // delta value + base value
  401. BitField<40, 3, s64> db;
  402. BitField<43, 5, u64> b;
  403. BitField<48, 3, s64> dg;
  404. BitField<51, 5, u64> g;
  405. BitField<56, 3, s64> dr;
  406. BitField<59, 5, u64> r;
  407. } differential;
  408. union {
  409. BitField<40, 4, u64> b2;
  410. BitField<44, 4, u64> b1;
  411. BitField<48, 4, u64> g2;
  412. BitField<52, 4, u64> g1;
  413. BitField<56, 4, u64> r2;
  414. BitField<60, 4, u64> r1;
  415. } separate;
  416. const Math::Vec3<u8> GetRGB(int x, int y) const {
  417. int texel = 4 * x + y;
  418. if (flip)
  419. std::swap(x, y);
  420. // Lookup base value
  421. Math::Vec3<int> ret;
  422. if (differential_mode) {
  423. ret.r() = static_cast<int>(differential.r);
  424. ret.g() = static_cast<int>(differential.g);
  425. ret.b() = static_cast<int>(differential.b);
  426. if (x >= 2) {
  427. ret.r() += static_cast<int>(differential.dr);
  428. ret.g() += static_cast<int>(differential.dg);
  429. ret.b() += static_cast<int>(differential.db);
  430. }
  431. ret.r() = Color::Convert5To8(ret.r());
  432. ret.g() = Color::Convert5To8(ret.g());
  433. ret.b() = Color::Convert5To8(ret.b());
  434. } else {
  435. if (x < 2) {
  436. ret.r() = Color::Convert4To8(static_cast<u8>(separate.r1));
  437. ret.g() = Color::Convert4To8(static_cast<u8>(separate.g1));
  438. ret.b() = Color::Convert4To8(static_cast<u8>(separate.b1));
  439. } else {
  440. ret.r() = Color::Convert4To8(static_cast<u8>(separate.r2));
  441. ret.g() = Color::Convert4To8(static_cast<u8>(separate.g2));
  442. ret.b() = Color::Convert4To8(static_cast<u8>(separate.b2));
  443. }
  444. }
  445. // Add modifier
  446. unsigned table_index = static_cast<int>((x < 2) ? table_index_1.Value() : table_index_2.Value());
  447. static const std::array<std::array<u8, 2>, 8> etc1_modifier_table = {{
  448. {{ 2, 8 }}, {{ 5, 17 }}, {{ 9, 29 }}, {{ 13, 42 }},
  449. {{ 18, 60 }}, {{ 24, 80 }}, {{ 33, 106 }}, {{ 47, 183 }}
  450. }};
  451. int modifier = etc1_modifier_table.at(table_index).at(GetTableSubIndex(texel));
  452. if (GetNegationFlag(texel))
  453. modifier *= -1;
  454. ret.r() = MathUtil::Clamp(ret.r() + modifier, 0, 255);
  455. ret.g() = MathUtil::Clamp(ret.g() + modifier, 0, 255);
  456. ret.b() = MathUtil::Clamp(ret.b() + modifier, 0, 255);
  457. return ret.Cast<u8>();
  458. }
  459. } const *etc1_tile = reinterpret_cast<const ETC1Tile*>(source_ptr);
  460. alpha >>= 4 * ((x & 3) * 4 + (y & 3));
  461. return Math::MakeVec(etc1_tile->GetRGB(x & 3, y & 3),
  462. disable_alpha ? (u8)255 : Color::Convert4To8(alpha & 0xF));
  463. }
  464. default:
  465. LOG_ERROR(HW_GPU, "Unknown texture format: %x", (u32)info.format);
  466. DEBUG_ASSERT(false);
  467. return {};
  468. }
  469. }
  470. TextureInfo TextureInfo::FromPicaRegister(const Regs::TextureConfig& config,
  471. const Regs::TextureFormat& format)
  472. {
  473. TextureInfo info;
  474. info.physical_address = config.GetPhysicalAddress();
  475. info.width = config.width;
  476. info.height = config.height;
  477. info.format = format;
  478. info.stride = Pica::Regs::NibblesPerPixel(info.format) * info.width / 2;
  479. return info;
  480. }
  481. #ifdef HAVE_PNG
  482. // Adapter functions to libpng to write/flush to File::IOFile instances.
  483. static void WriteIOFile(png_structp png_ptr, png_bytep data, png_size_t length) {
  484. auto* fp = static_cast<FileUtil::IOFile*>(png_get_io_ptr(png_ptr));
  485. if (!fp->WriteBytes(data, length))
  486. png_error(png_ptr, "Failed to write to output PNG file.");
  487. }
  488. static void FlushIOFile(png_structp png_ptr) {
  489. auto* fp = static_cast<FileUtil::IOFile*>(png_get_io_ptr(png_ptr));
  490. if (!fp->Flush())
  491. png_error(png_ptr, "Failed to flush to output PNG file.");
  492. }
  493. #endif
  494. void DumpTexture(const Pica::Regs::TextureConfig& texture_config, u8* data) {
  495. #ifndef HAVE_PNG
  496. return;
  497. #else
  498. if (!data)
  499. return;
  500. // Write data to file
  501. static int dump_index = 0;
  502. std::string filename = std::string("texture_dump") + std::to_string(++dump_index) + std::string(".png");
  503. u32 row_stride = texture_config.width * 3;
  504. u8* buf;
  505. char title[] = "Citra texture dump";
  506. char title_key[] = "Title";
  507. png_structp png_ptr = nullptr;
  508. png_infop info_ptr = nullptr;
  509. // Open file for writing (binary mode)
  510. FileUtil::IOFile fp(filename, "wb");
  511. // Initialize write structure
  512. png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
  513. if (png_ptr == nullptr) {
  514. LOG_ERROR(Debug_GPU, "Could not allocate write struct");
  515. goto finalise;
  516. }
  517. // Initialize info structure
  518. info_ptr = png_create_info_struct(png_ptr);
  519. if (info_ptr == nullptr) {
  520. LOG_ERROR(Debug_GPU, "Could not allocate info struct");
  521. goto finalise;
  522. }
  523. // Setup Exception handling
  524. if (setjmp(png_jmpbuf(png_ptr))) {
  525. LOG_ERROR(Debug_GPU, "Error during png creation");
  526. goto finalise;
  527. }
  528. png_set_write_fn(png_ptr, static_cast<void*>(&fp), WriteIOFile, FlushIOFile);
  529. // Write header (8 bit color depth)
  530. png_set_IHDR(png_ptr, info_ptr, texture_config.width, texture_config.height,
  531. 8, PNG_COLOR_TYPE_RGB /*_ALPHA*/, PNG_INTERLACE_NONE,
  532. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  533. png_text title_text;
  534. title_text.compression = PNG_TEXT_COMPRESSION_NONE;
  535. title_text.key = title_key;
  536. title_text.text = title;
  537. png_set_text(png_ptr, info_ptr, &title_text, 1);
  538. png_write_info(png_ptr, info_ptr);
  539. buf = new u8[row_stride * texture_config.height];
  540. for (unsigned y = 0; y < texture_config.height; ++y) {
  541. for (unsigned x = 0; x < texture_config.width; ++x) {
  542. TextureInfo info;
  543. info.width = texture_config.width;
  544. info.height = texture_config.height;
  545. info.stride = row_stride;
  546. info.format = g_state.regs.texture0_format;
  547. Math::Vec4<u8> texture_color = LookupTexture(data, x, y, info);
  548. buf[3 * x + y * row_stride ] = texture_color.r();
  549. buf[3 * x + y * row_stride + 1] = texture_color.g();
  550. buf[3 * x + y * row_stride + 2] = texture_color.b();
  551. }
  552. }
  553. // Write image data
  554. for (unsigned y = 0; y < texture_config.height; ++y)
  555. {
  556. u8* row_ptr = (u8*)buf + y * row_stride;
  557. png_write_row(png_ptr, row_ptr);
  558. }
  559. delete[] buf;
  560. // End write
  561. png_write_end(png_ptr, nullptr);
  562. finalise:
  563. if (info_ptr != nullptr) png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  564. if (png_ptr != nullptr) png_destroy_write_struct(&png_ptr, (png_infopp)nullptr);
  565. #endif
  566. }
  567. void DumpTevStageConfig(const std::array<Pica::Regs::TevStageConfig,6>& stages)
  568. {
  569. using Source = Pica::Regs::TevStageConfig::Source;
  570. using ColorModifier = Pica::Regs::TevStageConfig::ColorModifier;
  571. using AlphaModifier = Pica::Regs::TevStageConfig::AlphaModifier;
  572. using Operation = Pica::Regs::TevStageConfig::Operation;
  573. std::string stage_info = "Tev setup:\n";
  574. for (size_t index = 0; index < stages.size(); ++index) {
  575. const auto& tev_stage = stages[index];
  576. static const std::map<Source, std::string> source_map = {
  577. { Source::PrimaryColor, "PrimaryColor" },
  578. { Source::Texture0, "Texture0" },
  579. { Source::Texture1, "Texture1" },
  580. { Source::Texture2, "Texture2" },
  581. { Source::Constant, "Constant" },
  582. { Source::Previous, "Previous" },
  583. };
  584. static const std::map<ColorModifier, std::string> color_modifier_map = {
  585. { ColorModifier::SourceColor, { "%source.rgb" } },
  586. { ColorModifier::SourceAlpha, { "%source.aaa" } },
  587. };
  588. static const std::map<AlphaModifier, std::string> alpha_modifier_map = {
  589. { AlphaModifier::SourceAlpha, "%source.a" },
  590. { AlphaModifier::OneMinusSourceAlpha, "(255 - %source.a)" },
  591. };
  592. static const std::map<Operation, std::string> combiner_map = {
  593. { Operation::Replace, "%source1" },
  594. { Operation::Modulate, "(%source1 * %source2) / 255" },
  595. { Operation::Add, "(%source1 + %source2)" },
  596. { Operation::Lerp, "lerp(%source1, %source2, %source3)" },
  597. };
  598. static auto ReplacePattern =
  599. [](const std::string& input, const std::string& pattern, const std::string& replacement) -> std::string {
  600. size_t start = input.find(pattern);
  601. if (start == std::string::npos)
  602. return input;
  603. std::string ret = input;
  604. ret.replace(start, pattern.length(), replacement);
  605. return ret;
  606. };
  607. static auto GetColorSourceStr =
  608. [](const Source& src, const ColorModifier& modifier) {
  609. auto src_it = source_map.find(src);
  610. std::string src_str = "Unknown";
  611. if (src_it != source_map.end())
  612. src_str = src_it->second;
  613. auto modifier_it = color_modifier_map.find(modifier);
  614. std::string modifier_str = "%source.????";
  615. if (modifier_it != color_modifier_map.end())
  616. modifier_str = modifier_it->second;
  617. return ReplacePattern(modifier_str, "%source", src_str);
  618. };
  619. static auto GetColorCombinerStr =
  620. [](const Regs::TevStageConfig& tev_stage) {
  621. auto op_it = combiner_map.find(tev_stage.color_op);
  622. std::string op_str = "Unknown op (%source1, %source2, %source3)";
  623. if (op_it != combiner_map.end())
  624. op_str = op_it->second;
  625. op_str = ReplacePattern(op_str, "%source1", GetColorSourceStr(tev_stage.color_source1, tev_stage.color_modifier1));
  626. op_str = ReplacePattern(op_str, "%source2", GetColorSourceStr(tev_stage.color_source2, tev_stage.color_modifier2));
  627. return ReplacePattern(op_str, "%source3", GetColorSourceStr(tev_stage.color_source3, tev_stage.color_modifier3));
  628. };
  629. static auto GetAlphaSourceStr =
  630. [](const Source& src, const AlphaModifier& modifier) {
  631. auto src_it = source_map.find(src);
  632. std::string src_str = "Unknown";
  633. if (src_it != source_map.end())
  634. src_str = src_it->second;
  635. auto modifier_it = alpha_modifier_map.find(modifier);
  636. std::string modifier_str = "%source.????";
  637. if (modifier_it != alpha_modifier_map.end())
  638. modifier_str = modifier_it->second;
  639. return ReplacePattern(modifier_str, "%source", src_str);
  640. };
  641. static auto GetAlphaCombinerStr =
  642. [](const Regs::TevStageConfig& tev_stage) {
  643. auto op_it = combiner_map.find(tev_stage.alpha_op);
  644. std::string op_str = "Unknown op (%source1, %source2, %source3)";
  645. if (op_it != combiner_map.end())
  646. op_str = op_it->second;
  647. op_str = ReplacePattern(op_str, "%source1", GetAlphaSourceStr(tev_stage.alpha_source1, tev_stage.alpha_modifier1));
  648. op_str = ReplacePattern(op_str, "%source2", GetAlphaSourceStr(tev_stage.alpha_source2, tev_stage.alpha_modifier2));
  649. return ReplacePattern(op_str, "%source3", GetAlphaSourceStr(tev_stage.alpha_source3, tev_stage.alpha_modifier3));
  650. };
  651. stage_info += "Stage " + std::to_string(index) + ": " + GetColorCombinerStr(tev_stage) + " " + GetAlphaCombinerStr(tev_stage) + "\n";
  652. }
  653. LOG_TRACE(HW_GPU, "%s", stage_info.c_str());
  654. }
  655. } // namespace
  656. } // namespace