rendering_device_vulkan.h 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. /*************************************************************************/
  2. /* rendering_device_vulkan.h */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #ifndef RENDERING_DEVICE_VULKAN_H
  31. #define RENDERING_DEVICE_VULKAN_H
  32. #include "core/oa_hash_map.h"
  33. #include "core/os/thread_safe.h"
  34. #include "core/rid_owner.h"
  35. #include "servers/rendering/rendering_device.h"
  36. #ifdef DEBUG_ENABLED
  37. #ifndef _DEBUG
  38. #define _DEBUG
  39. #endif
  40. #endif
  41. #include "vk_mem_alloc.h"
  42. #include <vulkan/vulkan.h>
  43. //todo:
  44. //compute
  45. //push constants
  46. //views of texture slices
  47. class VulkanContext;
  48. class RenderingDeviceVulkan : public RenderingDevice {
  49. _THREAD_SAFE_CLASS_
  50. // Miscellaneous tables that map
  51. // our enums to enums used
  52. // by vulkan.
  53. VkPhysicalDeviceLimits limits;
  54. static const VkFormat vulkan_formats[DATA_FORMAT_MAX];
  55. static const char *named_formats[DATA_FORMAT_MAX];
  56. static const VkCompareOp compare_operators[COMPARE_OP_MAX];
  57. static const VkStencilOp stencil_operations[STENCIL_OP_MAX];
  58. static const VkSampleCountFlagBits rasterization_sample_count[TEXTURE_SAMPLES_MAX];
  59. static const VkLogicOp logic_operations[RenderingDevice::LOGIC_OP_MAX];
  60. static const VkBlendFactor blend_factors[RenderingDevice::BLEND_FACTOR_MAX];
  61. static const VkBlendOp blend_operations[RenderingDevice::BLEND_OP_MAX];
  62. static const VkSamplerAddressMode address_modes[SAMPLER_REPEAT_MODE_MAX];
  63. static const VkBorderColor sampler_border_colors[SAMPLER_BORDER_COLOR_MAX];
  64. static const VkImageType vulkan_image_type[TEXTURE_TYPE_MAX];
  65. // Functions used for format
  66. // validation, and ensures the
  67. // user passes valid data.
  68. static int get_format_vertex_size(DataFormat p_format);
  69. static uint32_t get_image_format_pixel_size(DataFormat p_format);
  70. static void get_compressed_image_format_block_dimensions(DataFormat p_format, uint32_t &r_w, uint32_t &r_h);
  71. uint32_t get_compressed_image_format_block_byte_size(DataFormat p_format);
  72. static uint32_t get_compressed_image_format_pixel_rshift(DataFormat p_format);
  73. static uint32_t get_image_format_required_size(DataFormat p_format, uint32_t p_width, uint32_t p_height, uint32_t p_depth, uint32_t p_mipmaps, uint32_t *r_blockw = nullptr, uint32_t *r_blockh = nullptr, uint32_t *r_depth = nullptr);
  74. static uint32_t get_image_required_mipmaps(uint32_t p_width, uint32_t p_height, uint32_t p_depth);
  75. static bool format_has_stencil(DataFormat p_format);
  76. /***************************/
  77. /**** ID INFRASTRUCTURE ****/
  78. /***************************/
  79. enum IDType {
  80. ID_TYPE_FRAMEBUFFER_FORMAT,
  81. ID_TYPE_VERTEX_FORMAT,
  82. ID_TYPE_DRAW_LIST,
  83. ID_TYPE_SPLIT_DRAW_LIST,
  84. ID_TYPE_COMPUTE_LIST,
  85. ID_TYPE_MAX,
  86. ID_BASE_SHIFT = 58 //5 bits for ID types
  87. };
  88. VkDevice device;
  89. Map<RID, Set<RID>> dependency_map; //IDs to IDs that depend on it
  90. Map<RID, Set<RID>> reverse_dependency_map; //same as above, but in reverse
  91. void _add_dependency(RID p_id, RID p_depends_on);
  92. void _free_dependencies(RID p_id);
  93. /*****************/
  94. /**** TEXTURE ****/
  95. /*****************/
  96. // In Vulkan, the concept of textures does not exist,
  97. // intead there is the image (the memory prety much,
  98. // the view (how the memory is interpreted) and the
  99. // sampler (how it's sampled from the shader).
  100. //
  101. // Texture here includes the first two stages, but
  102. // It's possible to create textures sharing the image
  103. // but with different views. The main use case for this
  104. // is textures that can be read as both SRGB/Linear,
  105. // or slices of a texture (a mipmap, a layer, a 3D slice)
  106. // for a framebuffer to render into it.
  107. struct Texture {
  108. VkImage image;
  109. VmaAllocation allocation;
  110. VmaAllocationInfo allocation_info;
  111. VkImageView view;
  112. TextureType type;
  113. DataFormat format;
  114. TextureSamples samples;
  115. uint32_t width;
  116. uint32_t height;
  117. uint32_t depth;
  118. uint32_t layers;
  119. uint32_t mipmaps;
  120. uint32_t usage_flags;
  121. uint32_t base_mipmap;
  122. uint32_t base_layer;
  123. Vector<DataFormat> allowed_shared_formats;
  124. VkImageLayout layout;
  125. uint32_t read_aspect_mask;
  126. uint32_t barrier_aspect_mask;
  127. bool bound; //bound to framebffer
  128. RID owner;
  129. };
  130. RID_Owner<Texture, true> texture_owner;
  131. uint32_t texture_upload_region_size_px;
  132. Vector<uint8_t> _texture_get_data_from_image(Texture *tex, VkImage p_image, VmaAllocation p_allocation, uint32_t p_layer, bool p_2d = false);
  133. /*****************/
  134. /**** SAMPLER ****/
  135. /*****************/
  136. RID_Owner<VkSampler> sampler_owner;
  137. /***************************/
  138. /**** BUFFER MANAGEMENT ****/
  139. /***************************/
  140. // These are temporary buffers on CPU memory that hold
  141. // the information until the CPU fetches it and places it
  142. // either on GPU buffers, or images (textures). It ensures
  143. // updates are properly synchronized with whathever the
  144. // GPU is doing.
  145. //
  146. // The logic here is as follows, only 3 of these
  147. // blocks are created at the beginning (one per frame)
  148. // they can each belong to a frame (assigned to current when
  149. // used) and they can only be reused after the same frame is
  150. // recycled.
  151. //
  152. // When CPU requires to allocate more than what is available,
  153. // more of these buffers are created. If a limit is reached,
  154. // then a fence will ensure will wait for blocks allocated
  155. // in previous frames are processed. If that fails, then
  156. // another fence will ensure everything pending for the current
  157. // frame is processed (effectively stalling).
  158. //
  159. // See the comments in the code to understand better how it works.
  160. struct StagingBufferBlock {
  161. VkBuffer buffer;
  162. VmaAllocation allocation;
  163. uint64_t frame_used;
  164. uint32_t fill_amount;
  165. };
  166. Vector<StagingBufferBlock> staging_buffer_blocks;
  167. int staging_buffer_current;
  168. uint32_t staging_buffer_block_size;
  169. uint64_t staging_buffer_max_size;
  170. bool staging_buffer_used;
  171. Error _staging_buffer_allocate(uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, bool p_can_segment = true, bool p_on_draw_command_buffer = false);
  172. Error _insert_staging_block();
  173. struct Buffer {
  174. uint32_t size;
  175. VkBuffer buffer;
  176. VmaAllocation allocation;
  177. VkDescriptorBufferInfo buffer_info; //used for binding
  178. Buffer() {
  179. size = 0;
  180. buffer = VK_NULL_HANDLE;
  181. allocation = nullptr;
  182. }
  183. };
  184. Error _buffer_allocate(Buffer *p_buffer, uint32_t p_size, uint32_t p_usage, VmaMemoryUsage p_mapping);
  185. Error _buffer_free(Buffer *p_buffer);
  186. Error _buffer_update(Buffer *p_buffer, size_t p_offset, const uint8_t *p_data, size_t p_data_size, bool p_use_draw_command_buffer = false, uint32_t p_required_align = 32);
  187. void _full_barrier(bool p_sync_with_draw);
  188. void _memory_barrier(VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_sccess, bool p_sync_with_draw);
  189. void _buffer_memory_barrier(VkBuffer buffer, uint64_t p_from, uint64_t p_size, VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_sccess, bool p_sync_with_draw);
  190. /*********************/
  191. /**** FRAMEBUFFER ****/
  192. /*********************/
  193. // In Vulkan, framebuffers work similar to how they
  194. // do in OpenGL, with the exception that
  195. // the "format" (vkRenderPass) is not dynamic
  196. // and must be more or less the same as the one
  197. // used for the render pipelines.
  198. struct FramebufferFormatKey {
  199. Vector<AttachmentFormat> attachments;
  200. bool operator<(const FramebufferFormatKey &p_key) const {
  201. int as = attachments.size();
  202. int bs = p_key.attachments.size();
  203. if (as != bs) {
  204. return as < bs;
  205. }
  206. const AttachmentFormat *af_a = attachments.ptr();
  207. const AttachmentFormat *af_b = p_key.attachments.ptr();
  208. for (int i = 0; i < as; i++) {
  209. const AttachmentFormat &a = af_a[i];
  210. const AttachmentFormat &b = af_b[i];
  211. if (a.format != b.format) {
  212. return a.format < b.format;
  213. }
  214. if (a.samples != b.samples) {
  215. return a.samples < b.samples;
  216. }
  217. if (a.usage_flags != b.usage_flags) {
  218. return a.usage_flags < b.usage_flags;
  219. }
  220. }
  221. return false; //equal
  222. }
  223. };
  224. VkRenderPass _render_pass_create(const Vector<AttachmentFormat> &p_format, InitialAction p_initial_action, FinalAction p_final_action, InitialAction p_initial_depth_action, FinalAction p_final_depthcolor_action, int *r_color_attachment_count = nullptr);
  225. // This is a cache and it's never freed, it ensures
  226. // IDs for a given format are always unique.
  227. Map<FramebufferFormatKey, FramebufferFormatID> framebuffer_format_cache;
  228. struct FramebufferFormat {
  229. const Map<FramebufferFormatKey, FramebufferFormatID>::Element *E;
  230. VkRenderPass render_pass; //here for constructing shaders, never used, see section (7.2. Render Pass Compatibility from Vulkan spec)
  231. int color_attachments; //used for pipeline validation
  232. TextureSamples samples;
  233. };
  234. Map<FramebufferFormatID, FramebufferFormat> framebuffer_formats;
  235. struct Framebuffer {
  236. FramebufferFormatID format_id;
  237. struct VersionKey {
  238. InitialAction initial_color_action;
  239. FinalAction final_color_action;
  240. InitialAction initial_depth_action;
  241. FinalAction final_depth_action;
  242. bool operator<(const VersionKey &p_key) const {
  243. if (initial_color_action == p_key.initial_color_action) {
  244. if (final_color_action == p_key.final_color_action) {
  245. if (initial_depth_action == p_key.initial_depth_action) {
  246. return final_depth_action < p_key.final_depth_action;
  247. } else {
  248. return initial_depth_action < p_key.initial_depth_action;
  249. }
  250. } else {
  251. return final_color_action < p_key.final_color_action;
  252. }
  253. } else {
  254. return initial_color_action < p_key.initial_color_action;
  255. }
  256. }
  257. };
  258. uint32_t storage_mask;
  259. Vector<RID> texture_ids;
  260. struct Version {
  261. VkFramebuffer framebuffer;
  262. VkRenderPass render_pass; //this one is owned
  263. };
  264. Map<VersionKey, Version> framebuffers;
  265. Size2 size;
  266. };
  267. RID_Owner<Framebuffer, true> framebuffer_owner;
  268. /***********************/
  269. /**** VERTEX BUFFER ****/
  270. /***********************/
  271. // Vertex buffers in Vulkan are similar to how
  272. // they work in OpenGL, except that instead of
  273. // an attribtue index, there is a buffer binding
  274. // index (for binding the buffers in real-time)
  275. // and a location index (what is used in the shader).
  276. //
  277. // This mapping is done here internally, and it's not
  278. // exposed.
  279. RID_Owner<Buffer, true> vertex_buffer_owner;
  280. struct VertexDescriptionKey {
  281. Vector<VertexAttribute> vertex_formats;
  282. bool operator==(const VertexDescriptionKey &p_key) const {
  283. int vdc = vertex_formats.size();
  284. int vdck = p_key.vertex_formats.size();
  285. if (vdc != vdck) {
  286. return false;
  287. } else {
  288. const VertexAttribute *a_ptr = vertex_formats.ptr();
  289. const VertexAttribute *b_ptr = p_key.vertex_formats.ptr();
  290. for (int i = 0; i < vdc; i++) {
  291. const VertexAttribute &a = a_ptr[i];
  292. const VertexAttribute &b = b_ptr[i];
  293. if (a.location != b.location) {
  294. return false;
  295. }
  296. if (a.offset != b.offset) {
  297. return false;
  298. }
  299. if (a.format != b.format) {
  300. return false;
  301. }
  302. if (a.stride != b.stride) {
  303. return false;
  304. }
  305. if (a.frequency != b.frequency) {
  306. return false;
  307. }
  308. }
  309. return true; //they are equal
  310. }
  311. }
  312. uint32_t hash() const {
  313. int vdc = vertex_formats.size();
  314. uint32_t h = hash_djb2_one_32(vdc);
  315. const VertexAttribute *ptr = vertex_formats.ptr();
  316. for (int i = 0; i < vdc; i++) {
  317. const VertexAttribute &vd = ptr[i];
  318. h = hash_djb2_one_32(vd.location, h);
  319. h = hash_djb2_one_32(vd.offset, h);
  320. h = hash_djb2_one_32(vd.format, h);
  321. h = hash_djb2_one_32(vd.stride, h);
  322. h = hash_djb2_one_32(vd.frequency, h);
  323. }
  324. return h;
  325. }
  326. };
  327. struct VertexDescriptionHash {
  328. static _FORCE_INLINE_ uint32_t hash(const VertexDescriptionKey &p_key) {
  329. return p_key.hash();
  330. }
  331. };
  332. // This is a cache and it's never freed, it ensures that
  333. // ID used for a specific format always remain the same.
  334. HashMap<VertexDescriptionKey, VertexFormatID, VertexDescriptionHash> vertex_format_cache;
  335. struct VertexDescriptionCache {
  336. Vector<VertexAttribute> vertex_formats;
  337. VkVertexInputBindingDescription *bindings;
  338. VkVertexInputAttributeDescription *attributes;
  339. VkPipelineVertexInputStateCreateInfo create_info;
  340. };
  341. Map<VertexFormatID, VertexDescriptionCache> vertex_formats;
  342. struct VertexArray {
  343. RID buffer;
  344. VertexFormatID description;
  345. int vertex_count;
  346. uint32_t max_instances_allowed;
  347. Vector<VkBuffer> buffers; //not owned, just referenced
  348. Vector<VkDeviceSize> offsets;
  349. };
  350. RID_Owner<VertexArray, true> vertex_array_owner;
  351. struct IndexBuffer : public Buffer {
  352. uint32_t max_index; //used for validation
  353. uint32_t index_count;
  354. VkIndexType index_type;
  355. bool supports_restart_indices;
  356. };
  357. RID_Owner<IndexBuffer, true> index_buffer_owner;
  358. struct IndexArray {
  359. uint32_t max_index; //remember the maximum index here too, for validation
  360. VkBuffer buffer; //not owned, inherited from index buffer
  361. uint32_t offset;
  362. uint32_t indices;
  363. VkIndexType index_type;
  364. bool supports_restart_indices;
  365. };
  366. RID_Owner<IndexArray, true> index_array_owner;
  367. /****************/
  368. /**** SHADER ****/
  369. /****************/
  370. // Vulkan specifies a really complex behavior for the application
  371. // in order to tell when descriptor sets need to be re-bound (or not).
  372. // "When binding a descriptor set (see Descriptor Set Binding) to set
  373. // number N, if the previously bound descriptor sets for sets zero
  374. // through N-1 were all bound using compatible pipeline layouts,
  375. // then performing this binding does not disturb any of the lower numbered sets.
  376. // If, additionally, the previous bound descriptor set for set N was
  377. // bound using a pipeline layout compatible for set N, then the bindings
  378. // in sets numbered greater than N are also not disturbed."
  379. // As a result, we need to figure out quickly when something is no longer "compatible".
  380. // in order to avoid costly rebinds.
  381. enum {
  382. MAX_UNIFORM_SETS = 16
  383. };
  384. struct UniformInfo {
  385. UniformType type;
  386. int binding;
  387. uint32_t stages;
  388. int length; //size of arrays (in total elements), or ubos (in bytes * total elements)
  389. bool operator!=(const UniformInfo &p_info) const {
  390. return (binding != p_info.binding || type != p_info.type || stages != p_info.stages || length != p_info.length);
  391. }
  392. bool operator<(const UniformInfo &p_info) const {
  393. if (binding != p_info.binding) {
  394. return binding < p_info.binding;
  395. }
  396. if (type != p_info.type) {
  397. return type < p_info.type;
  398. }
  399. if (stages != p_info.stages) {
  400. return stages < p_info.stages;
  401. }
  402. return length < p_info.length;
  403. }
  404. };
  405. struct UniformSetFormat {
  406. Vector<UniformInfo> uniform_info;
  407. bool operator<(const UniformSetFormat &p_format) const {
  408. uint32_t size = uniform_info.size();
  409. uint32_t psize = p_format.uniform_info.size();
  410. if (size != psize) {
  411. return size < psize;
  412. }
  413. const UniformInfo *infoptr = uniform_info.ptr();
  414. const UniformInfo *pinfoptr = p_format.uniform_info.ptr();
  415. for (uint32_t i = 0; i < size; i++) {
  416. if (infoptr[i] != pinfoptr[i]) {
  417. return infoptr[i] < pinfoptr[i];
  418. }
  419. }
  420. return false;
  421. }
  422. };
  423. // Always grows, never shrinks, ensuring unique IDs, but we assume
  424. // the amount of formats will never be a problem, as the amount of shaders
  425. // in a game is limited.
  426. Map<UniformSetFormat, uint32_t> uniform_set_format_cache;
  427. // Shaders in Vulkan are just pretty much
  428. // precompiled blocks of SPIR-V bytecode. They
  429. // are most likely not really compiled to host
  430. // assembly until a pipeline is created.
  431. //
  432. // When supplying the shaders, this implementation
  433. // will use the reflection abilities of glslang to
  434. // understand and cache everything required to
  435. // create and use the descriptor sets (Vulkan's
  436. // biggest pain).
  437. //
  438. // Additionally, hashes are created for every set
  439. // to do quick validation and ensuring the user
  440. // does not submit something invalid.
  441. struct Shader {
  442. struct Set {
  443. Vector<UniformInfo> uniform_info;
  444. VkDescriptorSetLayout descriptor_set_layout;
  445. };
  446. uint32_t vertex_input_mask; //inputs used, this is mostly for validation
  447. int fragment_outputs;
  448. struct PushConstant {
  449. uint32_t push_constant_size;
  450. uint32_t push_constants_vk_stage;
  451. };
  452. PushConstant push_constant;
  453. bool is_compute = false;
  454. int max_output;
  455. Vector<Set> sets;
  456. Vector<uint32_t> set_formats;
  457. Vector<VkPipelineShaderStageCreateInfo> pipeline_stages;
  458. VkPipelineLayout pipeline_layout;
  459. };
  460. String _shader_uniform_debug(RID p_shader, int p_set = -1);
  461. RID_Owner<Shader, true> shader_owner;
  462. /******************/
  463. /**** UNIFORMS ****/
  464. /******************/
  465. // Descriptor sets require allocation from a pool.
  466. // The documentation on how to use pools properly
  467. // is scarce, and the documentation is strange.
  468. //
  469. // Basically, you can mix and match pools as you
  470. // like, but you'll run into fragmentation issues.
  471. // Because of this, the recommended approach is to
  472. // create a a pool for every descriptor set type,
  473. // as this prevents fragmentation.
  474. //
  475. // This is implemented here as a having a list of
  476. // pools (each can contain up to 64 sets) for each
  477. // set layout. The amount of sets for each type
  478. // is used as the key.
  479. enum {
  480. MAX_DESCRIPTOR_POOL_ELEMENT = 65535
  481. };
  482. struct DescriptorPoolKey {
  483. union {
  484. struct {
  485. uint16_t uniform_type[UNIFORM_TYPE_MAX]; //using 16 bits because, for sending arrays, each element is a pool set.
  486. };
  487. struct {
  488. uint64_t key1;
  489. uint64_t key2;
  490. uint64_t key3;
  491. };
  492. };
  493. bool operator<(const DescriptorPoolKey &p_key) const {
  494. if (key1 != p_key.key1) {
  495. return key1 < p_key.key1;
  496. }
  497. if (key2 != p_key.key2) {
  498. return key2 < p_key.key2;
  499. }
  500. return key3 < p_key.key3;
  501. }
  502. DescriptorPoolKey() {
  503. key1 = 0;
  504. key2 = 0;
  505. key3 = 0;
  506. }
  507. };
  508. struct DescriptorPool {
  509. VkDescriptorPool pool;
  510. uint32_t usage;
  511. };
  512. Map<DescriptorPoolKey, Set<DescriptorPool *>> descriptor_pools;
  513. uint32_t max_descriptors_per_pool;
  514. DescriptorPool *_descriptor_pool_allocate(const DescriptorPoolKey &p_key);
  515. void _descriptor_pool_free(const DescriptorPoolKey &p_key, DescriptorPool *p_pool);
  516. RID_Owner<Buffer, true> uniform_buffer_owner;
  517. RID_Owner<Buffer, true> storage_buffer_owner;
  518. //texture buffer needs a view
  519. struct TextureBuffer {
  520. Buffer buffer;
  521. VkBufferView view;
  522. };
  523. RID_Owner<TextureBuffer, true> texture_buffer_owner;
  524. // This structure contains the descriptor set. They _need_ to be allocated
  525. // for a shader (and will be erased when this shader is erased), but should
  526. // work for other shaders as long as the hash matches. This covers using
  527. // them in shader variants.
  528. //
  529. // Keep also in mind that you can share buffers between descriptor sets, so
  530. // the above restriction is not too serious.
  531. struct UniformSet {
  532. uint32_t format;
  533. RID shader_id;
  534. uint32_t shader_set;
  535. DescriptorPool *pool;
  536. DescriptorPoolKey pool_key;
  537. VkDescriptorSet descriptor_set;
  538. //VkPipelineLayout pipeline_layout; //not owned, inherited from shader
  539. Vector<RID> attachable_textures; //used for validation
  540. Vector<Texture *> mutable_sampled_textures; //used for layout change
  541. Vector<Texture *> mutable_storage_textures; //used for layout change
  542. };
  543. RID_Owner<UniformSet, true> uniform_set_owner;
  544. /*******************/
  545. /**** PIPELINES ****/
  546. /*******************/
  547. // Render pipeline contains ALL the
  548. // information required for drawing.
  549. // This includes all the rasterizer state
  550. // as well as shader used, framebuffer format,
  551. // etc.
  552. // While the pipeline is just a single object
  553. // (VkPipeline) a lot of values are also saved
  554. // here to do validation (vulkan does none by
  555. // default) and warn the user if something
  556. // was not supplied as intended.
  557. struct RenderPipeline {
  558. //Cached values for validation
  559. #ifdef DEBUG_ENABLED
  560. struct Validation {
  561. FramebufferFormatID framebuffer_format;
  562. uint32_t dynamic_state;
  563. VertexFormatID vertex_format;
  564. bool uses_restart_indices;
  565. uint32_t primitive_minimum;
  566. uint32_t primitive_divisor;
  567. } validation;
  568. #endif
  569. //Actual pipeline
  570. RID shader;
  571. Vector<uint32_t> set_formats;
  572. VkPipelineLayout pipeline_layout; // not owned, needed for push constants
  573. VkPipeline pipeline;
  574. uint32_t push_constant_size;
  575. uint32_t push_constant_stages;
  576. };
  577. RID_Owner<RenderPipeline, true> render_pipeline_owner;
  578. struct ComputePipeline {
  579. RID shader;
  580. Vector<uint32_t> set_formats;
  581. VkPipelineLayout pipeline_layout; // not owned, needed for push constants
  582. VkPipeline pipeline;
  583. uint32_t push_constant_size;
  584. uint32_t push_constant_stages;
  585. };
  586. RID_Owner<ComputePipeline, true> compute_pipeline_owner;
  587. /*******************/
  588. /**** DRAW LIST ****/
  589. /*******************/
  590. // Draw list contains both the command buffer
  591. // used for drawing as well as a LOT of
  592. // information used for validation. This
  593. // validation is cheap so most of it can
  594. // also run in release builds.
  595. // When using split command lists, this is
  596. // implemented internally using secondary command
  597. // buffers. As they can be created in threads,
  598. // each needs it's own command pool.
  599. struct SplitDrawListAllocator {
  600. VkCommandPool command_pool;
  601. Vector<VkCommandBuffer> command_buffers; //one for each frame
  602. };
  603. Vector<SplitDrawListAllocator> split_draw_list_allocators;
  604. struct DrawList {
  605. VkCommandBuffer command_buffer; //if persistent, this is owned, otherwise it's shared with the ringbuffer
  606. Rect2i viewport;
  607. struct SetState {
  608. uint32_t pipeline_expected_format;
  609. uint32_t uniform_set_format;
  610. VkDescriptorSet descriptor_set;
  611. RID uniform_set;
  612. bool bound;
  613. SetState() {
  614. bound = false;
  615. pipeline_expected_format = 0;
  616. uniform_set_format = 0;
  617. descriptor_set = VK_NULL_HANDLE;
  618. }
  619. };
  620. struct State {
  621. SetState sets[MAX_UNIFORM_SETS];
  622. uint32_t set_count;
  623. RID pipeline;
  624. RID pipeline_shader;
  625. VkPipelineLayout pipeline_layout;
  626. RID vertex_array;
  627. RID index_array;
  628. uint32_t pipeline_push_constant_stages;
  629. State() {
  630. set_count = 0;
  631. pipeline_layout = VK_NULL_HANDLE;
  632. pipeline_push_constant_stages = 0;
  633. }
  634. } state;
  635. #ifdef DEBUG_ENABLED
  636. struct Validation {
  637. bool active; //means command buffer was not closes, so you can keep adding things
  638. FramebufferFormatID framebuffer_format;
  639. //actual render pass values
  640. uint32_t dynamic_state;
  641. VertexFormatID vertex_format; //INVALID_ID if not set
  642. uint32_t vertex_array_size; //0 if not set
  643. uint32_t vertex_max_instances_allowed;
  644. bool index_buffer_uses_restart_indices;
  645. uint32_t index_array_size; //0 if index buffer not set
  646. uint32_t index_array_max_index;
  647. uint32_t index_array_offset;
  648. Vector<uint32_t> set_formats;
  649. Vector<bool> set_bound;
  650. Vector<RID> set_rids;
  651. //last pipeline set values
  652. bool pipeline_active;
  653. uint32_t pipeline_dynamic_state;
  654. VertexFormatID pipeline_vertex_format;
  655. RID pipeline_shader;
  656. uint32_t invalid_set_from;
  657. bool pipeline_uses_restart_indices;
  658. uint32_t pipeline_primitive_divisor;
  659. uint32_t pipeline_primitive_minimum;
  660. Vector<uint32_t> pipeline_set_formats;
  661. uint32_t pipeline_push_constant_size;
  662. bool pipeline_push_constant_suppplied;
  663. Validation() {
  664. active = true;
  665. dynamic_state = 0;
  666. vertex_format = INVALID_ID;
  667. vertex_array_size = 0;
  668. vertex_max_instances_allowed = 0xFFFFFFFF;
  669. framebuffer_format = INVALID_ID;
  670. index_array_size = 0; //not sent
  671. index_array_max_index = 0; //not set
  672. index_buffer_uses_restart_indices = false;
  673. invalid_set_from = 0;
  674. //pipeline state initalize
  675. pipeline_active = false;
  676. pipeline_dynamic_state = 0;
  677. pipeline_vertex_format = INVALID_ID;
  678. pipeline_uses_restart_indices = false;
  679. pipeline_push_constant_size = 0;
  680. pipeline_push_constant_suppplied = false;
  681. }
  682. } validation;
  683. #else
  684. struct Validation {
  685. uint32_t vertex_array_size; //0 if not set
  686. uint32_t index_array_size; //0 if index buffer not set
  687. uint32_t index_array_offset;
  688. Validation() {
  689. vertex_array_size = 0;
  690. index_array_size = 0; //not sent
  691. }
  692. } validation;
  693. #endif
  694. };
  695. DrawList *draw_list; //one for regular draw lists, multiple for split.
  696. uint32_t draw_list_count;
  697. bool draw_list_split;
  698. Vector<RID> draw_list_bound_textures;
  699. bool draw_list_unbind_color_textures;
  700. bool draw_list_unbind_depth_textures;
  701. void _draw_list_insert_clear_region(DrawList *draw_list, Framebuffer *framebuffer, Point2i viewport_offset, Point2i viewport_size, bool p_clear_color, const Vector<Color> &p_clear_colors, bool p_clear_depth, float p_depth, uint32_t p_stencil);
  702. Error _draw_list_setup_framebuffer(Framebuffer *p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, VkFramebuffer *r_framebuffer, VkRenderPass *r_render_pass);
  703. Error _draw_list_render_pass_begin(Framebuffer *framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_colors, float p_clear_depth, uint32_t p_clear_stencil, Point2i viewport_offset, Point2i viewport_size, VkFramebuffer vkframebuffer, VkRenderPass render_pass, VkCommandBuffer command_buffer, VkSubpassContents subpass_contents);
  704. _FORCE_INLINE_ DrawList *_get_draw_list_ptr(DrawListID p_id);
  705. /**********************/
  706. /**** COMPUTE LIST ****/
  707. /**********************/
  708. struct ComputeList {
  709. VkCommandBuffer command_buffer; //if persistent, this is owned, otherwise it's shared with the ringbuffer
  710. struct SetState {
  711. uint32_t pipeline_expected_format;
  712. uint32_t uniform_set_format;
  713. VkDescriptorSet descriptor_set;
  714. RID uniform_set;
  715. bool bound;
  716. SetState() {
  717. bound = false;
  718. pipeline_expected_format = 0;
  719. uniform_set_format = 0;
  720. descriptor_set = VK_NULL_HANDLE;
  721. }
  722. };
  723. struct State {
  724. Set<Texture *> textures_to_sampled_layout;
  725. SetState sets[MAX_UNIFORM_SETS];
  726. uint32_t set_count;
  727. RID pipeline;
  728. RID pipeline_shader;
  729. VkPipelineLayout pipeline_layout;
  730. uint32_t pipeline_push_constant_stages;
  731. State() {
  732. set_count = 0;
  733. pipeline_layout = VK_NULL_HANDLE;
  734. pipeline_push_constant_stages = 0;
  735. }
  736. } state;
  737. #ifdef DEBUG_ENABLED
  738. struct Validation {
  739. bool active; //means command buffer was not closes, so you can keep adding things
  740. Vector<uint32_t> set_formats;
  741. Vector<bool> set_bound;
  742. Vector<RID> set_rids;
  743. //last pipeline set values
  744. bool pipeline_active;
  745. RID pipeline_shader;
  746. uint32_t invalid_set_from;
  747. Vector<uint32_t> pipeline_set_formats;
  748. uint32_t pipeline_push_constant_size;
  749. bool pipeline_push_constant_suppplied;
  750. Validation() {
  751. active = true;
  752. invalid_set_from = 0;
  753. //pipeline state initalize
  754. pipeline_active = false;
  755. pipeline_push_constant_size = 0;
  756. pipeline_push_constant_suppplied = false;
  757. }
  758. } validation;
  759. #endif
  760. };
  761. ComputeList *compute_list;
  762. /**************************/
  763. /**** FRAME MANAGEMENT ****/
  764. /**************************/
  765. // This is the frame structure. There are normally
  766. // 3 of these (used for triple buffering), or 2
  767. // (double buffering). They are cycled constantly.
  768. //
  769. // It contains two command buffers, one that is
  770. // used internally for setting up (creating stuff)
  771. // and another used mostly for drawing.
  772. //
  773. // They also contains a list of things that need
  774. // to be disposed of when deleted, which can't
  775. // happen immediately due to the asynchronous
  776. // nature of the GPU. They will get deleted
  777. // when the frame is cycled.
  778. struct Frame {
  779. //list in usage order, from last to free to first to free
  780. List<Buffer> buffers_to_dispose_of;
  781. List<Texture> textures_to_dispose_of;
  782. List<Framebuffer> framebuffers_to_dispose_of;
  783. List<VkSampler> samplers_to_dispose_of;
  784. List<Shader> shaders_to_dispose_of;
  785. List<VkBufferView> buffer_views_to_dispose_of;
  786. List<UniformSet> uniform_sets_to_dispose_of;
  787. List<RenderPipeline> render_pipelines_to_dispose_of;
  788. List<ComputePipeline> compute_pipelines_to_dispose_of;
  789. VkCommandPool command_pool;
  790. VkCommandBuffer setup_command_buffer; //used at the begining of every frame for set-up
  791. VkCommandBuffer draw_command_buffer; //used at the begining of every frame for set-up
  792. struct Timestamp {
  793. String description;
  794. uint64_t value;
  795. };
  796. VkQueryPool timestamp_pool;
  797. String *timestamp_names;
  798. uint64_t *timestamp_cpu_values;
  799. uint32_t timestamp_count;
  800. String *timestamp_result_names;
  801. uint64_t *timestamp_cpu_result_values;
  802. uint64_t *timestamp_result_values;
  803. uint32_t timestamp_result_count;
  804. uint64_t index;
  805. };
  806. uint32_t max_timestamp_query_elements;
  807. Frame *frames; //frames available, for main device they are cycled (usually 3), for local devices only 1
  808. int frame; //current frame
  809. int frame_count; //total amount of frames
  810. uint64_t frames_drawn;
  811. RID local_device;
  812. bool local_device_processing = false;
  813. void _free_pending_resources(int p_frame);
  814. VmaAllocator allocator;
  815. VulkanContext *context;
  816. void _free_internal(RID p_id);
  817. void _flush(bool p_current_frame);
  818. bool screen_prepared;
  819. template <class T>
  820. void _free_rids(T &p_owner, const char *p_type);
  821. void _finalize_command_bufers();
  822. void _begin_frame();
  823. public:
  824. virtual RID texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector<Vector<uint8_t>> &p_data = Vector<Vector<uint8_t>>());
  825. virtual RID texture_create_shared(const TextureView &p_view, RID p_with_texture);
  826. virtual RID texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, TextureSliceType p_slice_type = TEXTURE_SLICE_2D);
  827. virtual Error texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, bool p_sync_with_draw = false);
  828. virtual Vector<uint8_t> texture_get_data(RID p_texture, uint32_t p_layer);
  829. virtual bool texture_is_format_supported_for_usage(DataFormat p_format, uint32_t p_usage) const;
  830. virtual bool texture_is_shared(RID p_texture);
  831. virtual bool texture_is_valid(RID p_texture);
  832. virtual Error texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer, bool p_sync_with_draw = false);
  833. virtual Error texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers, bool p_sync_with_draw = false);
  834. virtual Error texture_resolve_multisample(RID p_from_texture, RID p_to_texture, bool p_sync_with_draw = false);
  835. /*********************/
  836. /**** FRAMEBUFFER ****/
  837. /*********************/
  838. virtual FramebufferFormatID framebuffer_format_create(const Vector<AttachmentFormat> &p_format);
  839. virtual TextureSamples framebuffer_format_get_texture_samples(FramebufferFormatID p_format);
  840. virtual RID framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check = INVALID_ID);
  841. virtual FramebufferFormatID framebuffer_get_format(RID p_framebuffer);
  842. /*****************/
  843. /**** SAMPLER ****/
  844. /*****************/
  845. virtual RID sampler_create(const SamplerState &p_state);
  846. /**********************/
  847. /**** VERTEX ARRAY ****/
  848. /**********************/
  849. virtual RID vertex_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  850. // Internally reference counted, this ID is warranted to be unique for the same description, but needs to be freed as many times as it was allocated
  851. virtual VertexFormatID vertex_format_create(const Vector<VertexAttribute> &p_vertex_formats);
  852. virtual RID vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers);
  853. virtual RID index_buffer_create(uint32_t p_size_indices, IndexBufferFormat p_format, const Vector<uint8_t> &p_data = Vector<uint8_t>(), bool p_use_restart_indices = false);
  854. virtual RID index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count);
  855. /****************/
  856. /**** SHADER ****/
  857. /****************/
  858. virtual RID shader_create(const Vector<ShaderStageData> &p_stages);
  859. virtual uint32_t shader_get_vertex_input_attribute_mask(RID p_shader);
  860. /*****************/
  861. /**** UNIFORM ****/
  862. /*****************/
  863. virtual RID uniform_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  864. virtual RID storage_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  865. virtual RID texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  866. virtual RID uniform_set_create(const Vector<Uniform> &p_uniforms, RID p_shader, uint32_t p_shader_set);
  867. virtual bool uniform_set_is_valid(RID p_uniform_set);
  868. virtual Error buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, bool p_sync_with_draw = false); //works for any buffer
  869. virtual Vector<uint8_t> buffer_get_data(RID p_buffer);
  870. /*************************/
  871. /**** RENDER PIPELINE ****/
  872. /*************************/
  873. virtual RID render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, int p_dynamic_state_flags = 0);
  874. virtual bool render_pipeline_is_valid(RID p_pipeline);
  875. /**************************/
  876. /**** COMPUTE PIPELINE ****/
  877. /**************************/
  878. virtual RID compute_pipeline_create(RID p_shader);
  879. virtual bool compute_pipeline_is_valid(RID p_pipeline);
  880. /****************/
  881. /**** SCREEN ****/
  882. /****************/
  883. virtual int screen_get_width(DisplayServer::WindowID p_screen = 0) const;
  884. virtual int screen_get_height(DisplayServer::WindowID p_screen = 0) const;
  885. virtual FramebufferFormatID screen_get_framebuffer_format() const;
  886. /********************/
  887. /**** DRAW LISTS ****/
  888. /********************/
  889. virtual DrawListID draw_list_begin_for_screen(DisplayServer::WindowID p_screen = 0, const Color &p_clear_color = Color());
  890. virtual DrawListID draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values = Vector<Color>(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2());
  891. virtual Error draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values = Vector<Color>(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2());
  892. virtual void draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline);
  893. virtual void draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index);
  894. virtual void draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array);
  895. virtual void draw_list_bind_index_array(DrawListID p_list, RID p_index_array);
  896. virtual void draw_list_set_line_width(DrawListID p_list, float p_width);
  897. virtual void draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size);
  898. virtual void draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances = 1, uint32_t p_procedural_vertices = 0);
  899. virtual void draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect);
  900. virtual void draw_list_disable_scissor(DrawListID p_list);
  901. virtual void draw_list_end();
  902. /***********************/
  903. /**** COMPUTE LISTS ****/
  904. /***********************/
  905. virtual ComputeListID compute_list_begin();
  906. virtual void compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline);
  907. virtual void compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index);
  908. virtual void compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size);
  909. virtual void compute_list_add_barrier(ComputeListID p_list);
  910. virtual void compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups);
  911. virtual void compute_list_end();
  912. /**************/
  913. /**** FREE ****/
  914. /**************/
  915. virtual void free(RID p_id);
  916. /****************/
  917. /**** Timing ****/
  918. /****************/
  919. virtual void capture_timestamp(const String &p_name, bool p_sync_to_draw);
  920. virtual uint32_t get_captured_timestamps_count() const;
  921. virtual uint64_t get_captured_timestamps_frame() const;
  922. virtual uint64_t get_captured_timestamp_gpu_time(uint32_t p_index) const;
  923. virtual uint64_t get_captured_timestamp_cpu_time(uint32_t p_index) const;
  924. virtual String get_captured_timestamp_name(uint32_t p_index) const;
  925. /****************/
  926. /**** Limits ****/
  927. /****************/
  928. virtual int limit_get(Limit p_limit);
  929. virtual void prepare_screen_for_drawing();
  930. void initialize(VulkanContext *p_context, bool p_local_device = false);
  931. void finalize();
  932. virtual void swap_buffers(); //for main device
  933. virtual void submit(); //for local device
  934. virtual void sync(); //for local device
  935. virtual uint32_t get_frame_delay() const;
  936. virtual RenderingDevice *create_local_device();
  937. virtual uint64_t get_memory_usage() const;
  938. RenderingDeviceVulkan();
  939. ~RenderingDeviceVulkan();
  940. };
  941. #endif // RENDERING_DEVICE_VULKAN_H