summaryrefslogtreecommitdiff
path: root/src/vk/texture.cpp
blob: c699ecca4cf9609a96eb538d7402a32d03dbdc3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/*
 * Copyright 2022-2023 Frederico de Oliveira Linhares
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "texture.hpp"

#define QOI_IMPLEMENTATION 0
#include <qoi.h>

#include "../command.hpp"
#include "../core.hpp"
#include "image.hpp"
#include "source_buffer.hpp"

namespace
{

inline void
create_vulkan_image(
  VkImage *image, VkDeviceMemory *device_memory, int width, int height,
  uint32_t mip_levels)
{
  VkExtent3D vk_extent3d{};
  vk_extent3d.width = width;
  vk_extent3d.height = height;
  vk_extent3d.depth = 1;

  VK::Image::create(
    cg_core.vk_device_with_swapchain,
    image,
    device_memory,
    VK_FORMAT_R8G8B8A8_UNORM,
    vk_extent3d,
    mip_levels,
    VK_IMAGE_TILING_OPTIMAL,
    VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
}

struct ImageBuilder
{
  VK::Texture *texture;
};

struct ImageTextureBuilder: public ImageBuilder
{
  std::string texture_path;

  ImageTextureBuilder(VK::Texture *t, std::string tp);
  ImageTextureBuilder(VK::Texture *t, const char* tp);
};

ImageTextureBuilder::ImageTextureBuilder(VK::Texture *t, std::string tp):
  texture_path{tp}
{
  this->texture = t;
}

ImageTextureBuilder::ImageTextureBuilder(VK::Texture *t, const char* tp):
  ImageTextureBuilder{t, std::string(tp)}
{
}

void
load_image(void *obj)
{
  auto self = static_cast<ImageTextureBuilder*>(obj);

  qoi_desc img_desc;
  const int num_channels = 4; // all images are converted to RGBA
  unsigned char *pixels;

  { // Load file image from file.
    void *pixels_ptr = qoi_read(self->texture_path.c_str(), &img_desc, 4);
    if(pixels_ptr == NULL) throw CommandError{"Failed to open image."};

    pixels = static_cast<unsigned char*>(pixels_ptr);
    self->texture->width = static_cast<uint32_t>(img_desc.width);
    self->texture->height = static_cast<uint32_t>(img_desc.height);
    self->texture->mip_levels = 1;

    pixels = static_cast<unsigned char*>(pixels_ptr);
  }

  // Load file image into a vulkan buffer.
  size_t image_size{static_cast<size_t>(
      img_desc.width * img_desc.height * num_channels)};
  VK::SourceBuffer source_image_buffer{
    cg_core.vk_device_with_swapchain, pixels, image_size};

  { // Create vulkan image.
    try
    {
      create_vulkan_image(
        &self->texture->image,
        &self->texture->device_memory,
        self->texture->width,
        self->texture->height,
        self->texture->mip_levels);
    }
    catch(VK::Image::Error error)
    {
      throw CommandError{error.what()};
    }
  }

  // Copy image from vulkan buffer into vulkan image.
  {
    auto queue_family{
      cg_core.vk_device_with_swapchain->get_queue_family_with_presentation()};
    auto queue{queue_family->get_queue()};
    VK::CommandPool command_pool{queue_family, 1};
    VkCommandBuffer vk_command_buffer{command_pool.command_buffers[0]};

    queue.submit_one_time_command(vk_command_buffer, [&](){
      VK::Image::move_image_state(
	vk_command_buffer, self->texture->image, VK_FORMAT_R8G8B8A8_UNORM,
	0, VK_ACCESS_TRANSFER_WRITE_BIT,
	VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
	VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);

      VkBufferImageCopy image_copy{};
      image_copy.bufferOffset = 0;
      image_copy.bufferRowLength = 0;
      image_copy.bufferImageHeight = 0;
      image_copy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
      image_copy.imageSubresource.mipLevel = 0;
      image_copy.imageSubresource.baseArrayLayer = 0;
      image_copy.imageSubresource.layerCount = 1;
      image_copy.imageOffset = {0, 0, 0};
      image_copy.imageExtent = {
        self->texture->width, self->texture->height, 1};

      vkCmdCopyBufferToImage(
	vk_command_buffer, source_image_buffer.buffer, self->texture->image,
	VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy);

      VK::Image::move_image_state(
	vk_command_buffer, self->texture->image, VK_FORMAT_R8G8B8A8_UNORM,
	VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT,
	VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
	VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
	VK_PIPELINE_STAGE_TRANSFER_BIT,
	VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
    });
  }

  // Free resources.
  QOI_FREE(pixels);
}

void
unload_image(void *obj)
{
  auto self = static_cast<ImageBuilder*>(obj);

  vkDestroyImage(
    cg_core.vk_device_with_swapchain->device, self->texture->image, nullptr);
  vkFreeMemory(
    cg_core.vk_device_with_swapchain->device, self->texture->device_memory,
    nullptr);
}

void
load_sampler(void *obj)
{
  auto self = static_cast<ImageBuilder*>(obj);

  VkSamplerCreateInfo sampler_info{};
  sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  sampler_info.pNext = nullptr;
  sampler_info.flags = 0;
  sampler_info.magFilter = VK_FILTER_LINEAR;
  sampler_info.minFilter = VK_FILTER_LINEAR;
  sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
  sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
  sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
  sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
  sampler_info.mipLodBias = 0.0f;
  sampler_info.anisotropyEnable = VK_TRUE;
  sampler_info.maxAnisotropy = 16;
  sampler_info.compareEnable = VK_FALSE;
  sampler_info.compareOp = VK_COMPARE_OP_NEVER;
  sampler_info.minLod = 0.0f;
  sampler_info.maxLod = 0.0f;
  sampler_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;
  sampler_info.unnormalizedCoordinates = VK_FALSE;

  if(vkCreateSampler(
       cg_core.vk_device_with_swapchain->device, &sampler_info, nullptr,
       &self->texture->sampler) != VK_SUCCESS)
    throw CommandError{"Failed to create texture sampler."};
}

void
unload_sampler(void *obj)
{
  auto self = static_cast<ImageBuilder*>(obj);

  vkDestroySampler(
    cg_core.vk_device_with_swapchain->device, self->texture->sampler, nullptr);
}

void
load_view(void *obj)
{
  auto self = static_cast<ImageBuilder*>(obj);

  try
  {
    VK::Image::create_view(
      cg_core.vk_device_with_swapchain, &self->texture->view,
      self->texture->image,
      VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
  }
  catch(VK::Image::Error error)
  {
    throw CommandError{error.what()};
  }
}

void
unload_view(void *obj)
{
  auto self = static_cast<ImageBuilder*>(obj);

  vkDestroyImageView(
    cg_core.vk_device_with_swapchain->device, self->texture->view, nullptr);
}

const CommandChain image_loader{
  {&load_image, &unload_image},
  {&load_sampler, &unload_sampler},
  {&load_view, &unload_view}
};

struct CharacterToDraw
{
  int pos_x;
  std::shared_ptr<VK::Character> character;

  CharacterToDraw(int x, std::shared_ptr<VK::Character> character):
    pos_x{x},
    character{character}
    {};
};

struct TextTextureBuilder: public ImageBuilder
{
  VK::Font *font;
  const char* str;
  uint32_t max_bearing_y;
  std::vector<CharacterToDraw> chars_to_draw;

  TextTextureBuilder(VK::Texture *texture, VK::Font *font, const char* str):
    font{font},
    str{str}
    {
      this->texture = texture;
    }
};

void
load_text_proportions(void *obj)
{
  auto self = static_cast<TextTextureBuilder*>(obj);

  uint32_t texture_width{0}, texture_descender{0};
  auto unicode_text{VK::Character::str_to_unicode(self->str)};

  auto first_image{self->font->character(unicode_text[0])};
  if(first_image->bearing_x < 0) texture_width = - first_image->bearing_x;

  self->max_bearing_y = 0;
  self->chars_to_draw.reserve(unicode_text.size());
  { // Calculate image size
    int max_height;
    for(auto char_code : unicode_text)
    {
      auto char_image{self->font->character(char_code)};
      uint32_t descender{char_image->height - char_image->bearing_y};
      uint32_t pos_x{texture_width + char_image->bearing_x};

      if(char_image->image != VK_NULL_HANDLE)
        self->chars_to_draw.emplace_back(pos_x, char_image);

      if(char_image->bearing_y > self->max_bearing_y)
        self->max_bearing_y = char_image->bearing_y;
      if(descender > texture_descender) texture_descender = descender;

      texture_width += char_image->advance;
    }
  }

  self->texture->width = texture_width;
  self->texture->height = self->max_bearing_y + texture_descender;
  self->texture->mip_levels = 1;
}

void
load_text_image(void *obj)
{
  auto self = static_cast<TextTextureBuilder*>(obj);

  const int NumChannels = 4;

  size_t image_size{static_cast<size_t>(
      self->texture->width * self->texture->height * NumChannels)};
  std::vector<unsigned char> pixels(image_size);
  for(auto x{0}; x < self->texture->width; x++)
  {
    for(auto y{0}; y < self->texture->height; y++)
    {
      auto image_coord = y * self->font->face->glyph->bitmap.width +
        x * NumChannels;
      pixels[image_coord] = 0; // Red
      pixels[image_coord + 1] = 0; // Green
      pixels[image_coord + 2] = 0; // Blue
      pixels[image_coord + 3] = 0; // Alpha
    }
  }
  VK::SourceBuffer source_image_buffer{
    cg_core.vk_device_with_swapchain, pixels.data(), image_size};

  { // Create vulkan image.
    try
    {
      create_vulkan_image(
        &self->texture->image,
        &self->texture->device_memory,
        self->texture->width,
        self->texture->height,
        self->texture->mip_levels);
    }
    catch(VK::Image::Error error)
    {
      throw CommandError{error.what()};
    }
  }

  { // Render text
    auto queue_family{
      cg_core.vk_device_with_swapchain->get_queue_family_with_presentation()};
    auto queue{queue_family->get_queue()};
    VK::CommandPool command_pool{queue_family, 1};
    VkCommandBuffer vk_command_buffer{command_pool.command_buffers[0]};

    queue.submit_one_time_command(vk_command_buffer, [&](){
      VK::Image::move_image_state(
	vk_command_buffer, self->texture->image, VK_FORMAT_R8G8B8A8_UNORM,
	0, VK_ACCESS_TRANSFER_WRITE_BIT,
	VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
	VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);

      VkBufferImageCopy image_copy{};
      image_copy.bufferOffset = 0;
      image_copy.bufferRowLength = 0;
      image_copy.bufferImageHeight = 0;
      image_copy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
      image_copy.imageSubresource.mipLevel = 0;
      image_copy.imageSubresource.baseArrayLayer = 0;
      image_copy.imageSubresource.layerCount = 1;
      image_copy.imageOffset = {0, 0, 0};
      image_copy.imageExtent = {self->texture->width, self->texture->height, 1};

      vkCmdCopyBufferToImage(
	vk_command_buffer, source_image_buffer.buffer, self->texture->image,
	VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy);

      for(auto &to_draw: self->chars_to_draw)
      {
        VkImageSubresourceLayers
          source_subresources{}, destination_subresources{};
        source_subresources.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
        source_subresources.mipLevel = 0;
        source_subresources.baseArrayLayer = 0;
        source_subresources.layerCount = 1;

        destination_subresources.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
        destination_subresources.mipLevel = 0;
        destination_subresources.baseArrayLayer = 0;
        destination_subresources.layerCount = 1;

        VkImageCopy image_copy{};
        image_copy.srcSubresource = source_subresources;
        image_copy.srcOffset = {0, 0, 0};
        image_copy.dstSubresource = destination_subresources;
        image_copy.dstOffset = {
          to_draw.pos_x,
          (int)(self->max_bearing_y - to_draw.character->bearing_y),
          0};
        image_copy.extent = {
          to_draw.character->width, to_draw.character->height, 1};

        vkCmdCopyImage(
          vk_command_buffer,
          to_draw.character->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
          self->texture->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
          1, &image_copy);
      }

      VK::Image::move_image_state(
	vk_command_buffer, self->texture->image, VK_FORMAT_R8G8B8A8_UNORM,
	VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT,
	VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
	VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
	VK_PIPELINE_STAGE_TRANSFER_BIT,
	VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
    });
  }
}

const CommandChain text_loader{
  {&load_text_proportions, nullptr},
  {&load_text_image, &unload_image},
  {&load_sampler, &unload_sampler},
  {&load_view, &unload_view}
};

}

namespace VK
{

Texture::Texture(Font *font, const char* str)
{
  TextTextureBuilder text_builder(this, font, str);
  text_loader.execute(&text_builder);
}

Texture::Texture(std::string texture_path)
{
  ImageTextureBuilder texture_builder(this, texture_path);
  image_loader.execute(&texture_builder);
}

Texture::Texture(const char* texture_path):
  Texture{std::string(texture_path)}
{
}

Texture::~Texture()
{
  ImageTextureBuilder texture_builder(this, "");
  image_loader.revert(&texture_builder);
}

}