diff --git a/CMakeLists.txt b/CMakeLists.txt index ec07e26..db9fbe8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -111,7 +111,7 @@ file(GLOB PROJECT_SRC CONFIGURE_DEPENDS set(CORE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src) file(GLOB CORE_SRC CONFIGURE_DEPENDS ${CORE_DIR}/anm2/*.cpp) -foreach(CORE_FILE log resource/strings util/file util/path util/math util/string util/time util/working_directory +foreach(CORE_FILE log resource/strings resource/image resource/audio_data util/file util/path util/math util/string util/time util/working_directory util/xml util/pack) list(APPEND CORE_SRC ${CORE_DIR}/${CORE_FILE}.cpp) endforeach() diff --git a/src/canvas.cpp b/src/canvas.cpp index bce972d..61494b8 100644 --- a/src/canvas.cpp +++ b/src/canvas.cpp @@ -205,7 +205,7 @@ namespace anm2ed } } - void Canvas::texture_render(Shader& shader, GLuint& texture, mat4 transform, vec4 tint, vec3 colorOffset, + void Canvas::texture_render(Shader& shader, GLuint texture, mat4 transform, vec4 tint, vec3 colorOffset, float* vertices, vec2 textureSize, float playbackTime) const { canvas_blend_premultiplied_set(); diff --git a/src/canvas.hpp b/src/canvas.hpp index 4d3cc0a..be0d677 100644 --- a/src/canvas.hpp +++ b/src/canvas.hpp @@ -26,8 +26,8 @@ namespace anm2ed static constexpr auto STEP = 1.0f; static constexpr auto STEP_FAST = 5.0f; static constexpr auto ZOOM_LEVEL_STEP = 1; - static constexpr std::array ZOOM_LEVELS = {1.0f, 2.0f, 5.0f, 10.0f, 15.0f, 25.0f, 33.0f, - 50.0f, 66.0f, 75.0f, 100.0f, 125.0f, 150.0f, 200.0f, + static constexpr std::array ZOOM_LEVELS = {1.0f, 2.0f, 5.0f, 10.0f, 15.0f, 25.0f, 33.0f, + 50.0f, 66.0f, 75.0f, 100.0f, 125.0f, 150.0f, 200.0f, 300.0f, 400.0f, 600.0f, 800.0f, 1200.0f, 2000.0f}; static constexpr auto GRID_SIZE_MIN = 1; static constexpr auto GRID_SIZE_MAX = 10000; @@ -60,10 +60,9 @@ namespace anm2ed void axes_render(resource::Shader&, float, glm::vec2, glm::vec4 = glm::vec4(1.0f)) const; void grid_render(resource::Shader&, float, glm::vec2, glm::ivec2 = glm::ivec2(32, 32), glm::ivec2 = {}, glm::vec4 = glm::vec4(1.0f)) const; - void texture_render(resource::Shader&, GLuint&, glm::mat4 = {1.0f}, glm::vec4 = glm::vec4(1.0f), glm::vec3 = {}, + void texture_render(resource::Shader&, GLuint, glm::mat4 = {1.0f}, glm::vec4 = glm::vec4(1.0f), glm::vec3 = {}, float* = (float*)TEXTURE_VERTICES, glm::vec2 = {}, float = 0.0f) const; - void rect_fill_render(resource::Shader&, const glm::mat4&, const glm::mat4&, - glm::vec4 = glm::vec4(1.0f)) const; + void rect_fill_render(resource::Shader&, const glm::mat4&, const glm::mat4&, glm::vec4 = glm::vec4(1.0f)) const; void rect_render(resource::Shader&, const glm::mat4&, const glm::mat4&, glm::vec4 = glm::vec4(1.0f), float dashLength = DASH_LENGTH, float dashGap = DASH_GAP, float dashOffset = DASH_OFFSET) const; float zoom_level_get(float, int) const; diff --git a/src/document.cpp b/src/document.cpp index 9de4267..f7a6524 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -157,15 +157,14 @@ namespace anm2ed::document std::erase_if(paths, [&](const auto& pair) { return !validIds.contains(pair.first); }); } - uint64_t spritesheet_hash_get(const Element& spritesheet, const resource::Texture* texture) + uint64_t spritesheet_hash_get(const Element& spritesheet, const resource::Image* texture) { std::size_t seed{}; auto hash_combine = [&](std::size_t value) { seed ^= value + HASH_COMBINE_CONSTANT + (seed << 6) + (seed >> 2); }; hash_combine(std::hash{}(texture ? texture->size.x : 0)); hash_combine(std::hash{}(texture ? texture->size.y : 0)); - hash_combine(std::hash{}(texture ? texture->channels : 0)); - hash_combine(std::hash{}(texture ? texture->filter : 0)); + hash_combine(std::hash{}(texture && texture->isLinear)); hash_combine(std::hash{}(path::to_utf8(spritesheet.path))); auto isPixels = texture && !texture->pixels.empty(); hash_combine(isPixels ? std::hash{}(std::string_view( @@ -459,13 +458,13 @@ namespace anm2ed std::erase_if(shaderFragmentPaths, is_invalid); } - resource::Texture* Document::texture_get(int id) + resource::Image* Document::texture_get(int id) { auto it = textures.find(id); return it == textures.end() ? nullptr : &it->second; } - resource::Audio* Document::sound_get(int id) + resource::AudioData* Document::sound_get(int id) { auto it = sounds.find(id); return it == sounds.end() ? nullptr : &it->second; @@ -497,10 +496,9 @@ namespace anm2ed for (int y = minPoint.y; y < maxPoint.y; ++y) for (int x = minPoint.x; x < maxPoint.x; ++x) { - auto index = ((std::size_t)y * texture->size.x + x) * resource::texture::CHANNELS; - if (index + resource::texture::CHANNELS > texture->pixels.size()) continue; - if (std::all_of(texture->pixels.begin() + index, - texture->pixels.begin() + index + resource::texture::CHANNELS, + auto index = ((std::size_t)y * texture->size.x + x) * resource::image::CHANNELS; + if (index + resource::image::CHANNELS > texture->pixels.size()) continue; + if (std::all_of(texture->pixels.begin() + index, texture->pixels.begin() + index + resource::image::CHANNELS, [](auto channel) { return channel == 0; })) continue; contentMin = glm::min(contentMin, glm::ivec2(x, y)); @@ -567,7 +565,7 @@ namespace anm2ed std::vector positions{}; if (!util::pack::rects_pack(sizes, packedSize, positions) || packedSize.x <= 0 || packedSize.y <= 0) return false; - std::vector packedPixels((std::size_t)packedSize.x * packedSize.y * resource::texture::CHANNELS, 0); + std::vector packedPixels((std::size_t)packedSize.x * packedSize.y * resource::image::CHANNELS, 0); std::unordered_map crops{}; for (int i = 0; i < (int)items.size(); ++i) { @@ -583,15 +581,14 @@ namespace anm2ed glm::any(glm::greaterThanEqual(source, texture->size)) || glm::any(glm::greaterThanEqual(target, packedSize))) continue; - std::copy_n(texture->pixels.data() + - ((std::size_t)source.y * texture->size.x + source.x) * resource::texture::CHANNELS, - resource::texture::CHANNELS, - packedPixels.data() + - ((std::size_t)target.y * packedSize.x + target.x) * resource::texture::CHANNELS); + std::copy_n( + texture->pixels.data() + ((std::size_t)source.y * texture->size.x + source.x) * resource::image::CHANNELS, + resource::image::CHANNELS, + packedPixels.data() + ((std::size_t)target.y * packedSize.x + target.x) * resource::image::CHANNELS); } } - textures[id] = resource::Texture(packedPixels.data(), packedSize); + textures[id] = resource::Image(packedPixels.data(), packedSize); for (auto& region : spritesheet->children) if (region.type == ElementType::REGION && crops.contains(region.id)) region.crop = crops.at(region.id); @@ -633,7 +630,7 @@ namespace anm2ed if (id == baseId) continue; auto texture = texture_get(id); auto offset = isAppendRight ? glm::ivec2(mergedTexture.size.x, 0) : glm::ivec2(0, mergedTexture.size.y); - mergedTexture = resource::Texture::merge_append(mergedTexture, *texture, isAppendRight); + mergedTexture = resource::Image::merge_append(mergedTexture, *texture, isAppendRight); if (!isMakeRegions) continue; location_region_add(id, offset, texture->size); @@ -973,13 +970,13 @@ namespace anm2ed if (!items) return; auto directory = directory_get(); - std::vector> loaded{}; + std::vector> loaded{}; for (auto& path : paths) { auto storagePath = path::backslash_handle(path); std::optional workingDirectory{}; if (!storagePath.is_absolute()) workingDirectory.emplace(directory); - auto texture = resource::Texture(path::case_insensitive_find(storagePath)); + auto texture = resource::Image(path::case_insensitive_find(storagePath)); if (!texture.is_valid()) { toast_log(Level::ERROR, TOAST_SPRITESHEET_INIT_FAILED, path::to_utf8(path)); diff --git a/src/document.hpp b/src/document.hpp index afff0e5..1eaebbd 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -108,8 +108,8 @@ namespace anm2ed bool texture_reload(int); bool sound_reload(int); bool shader_reload(int, std::string* = nullptr); - resource::Texture* texture_get(int); - resource::Audio* sound_get(int); + resource::Image* texture_get(int); + resource::AudioData* sound_get(int); resource::Shader* shader_get(int); bool regions_trim(int, const std::set&); bool spritesheet_pack(int, int); diff --git a/src/framebuffer.cpp b/src/framebuffer.cpp index ce6ab44..ef6b27d 100644 --- a/src/framebuffer.cpp +++ b/src/framebuffer.cpp @@ -60,7 +60,7 @@ namespace anm2ed std::vector Framebuffer::pixels_get() const { - auto count = size.x * size.y * texture::CHANNELS; + auto count = size.x * size.y * image::CHANNELS; std::vector pixels(count); glReadBuffer(GL_COLOR_ATTACHMENT0); diff --git a/src/imgui/taskbar.cpp b/src/imgui/taskbar.cpp index 8973488..21e1134 100644 --- a/src/imgui/taskbar.cpp +++ b/src/imgui/taskbar.cpp @@ -344,7 +344,7 @@ namespace anm2ed::imgui } if (auto* music = resources.music_track_if_loaded()) - if (music->is_playing() && !aboutPopup.isOpen) music->stop(); + if (resource::audio::is_playing(*music) && !aboutPopup.isOpen) resource::audio::stop(*music); overwritePopup.trigger(); diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index 5e2395a..9a5f6e5 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -31,7 +31,7 @@ using namespace anm2ed::types; using namespace anm2ed::util; using namespace anm2ed::resource; -using namespace anm2ed::resource::texture; +using namespace anm2ed::resource::image; using namespace glm; namespace anm2ed::imgui @@ -210,7 +210,7 @@ namespace anm2ed::imgui return document.sound_get(soundID) ? soundID : -1; } - bool render_audio_stream_generate(AudioStream& audioStream, std::map& sounds, + bool render_audio_stream_generate(AudioStream& audioStream, std::map& sounds, const std::vector& frameSoundIDs, int fps) { audioStream.stream.clear(); @@ -229,7 +229,7 @@ namespace anm2ed::imgui for (auto soundID : frameSoundIDs) { - if (soundID != -1 && sounds.contains(soundID)) sounds.at(soundID).play(false, mixer); + if (soundID != -1 && sounds.contains(soundID)) audio::play(sounds.at(soundID), false, mixer); sampleFrameAccumulator += framesPerStep; auto sampleFramesToGenerate = (int)std::floor(sampleFrameAccumulator); @@ -240,7 +240,7 @@ namespace anm2ed::imgui if (!MIX_Generate(mixer, frameBuffer.data(), (int)(frameBuffer.size() * sizeof(float)))) { for (auto& [_, sound] : sounds) - sound.track_detach(mixer); + audio::track_detach(sound, mixer); MIX_DestroyMixer(mixer); audioStream.stream.clear(); return false; @@ -250,7 +250,7 @@ namespace anm2ed::imgui } for (auto& [_, sound] : sounds) - sound.track_detach(mixer); + audio::track_detach(sound, mixer); MIX_DestroyMixer(mixer); return true; } @@ -269,7 +269,7 @@ namespace anm2ed::imgui auto stop_all_sounds = [&]() { for (auto& [_, sound] : document.sounds) - sound.stop(mixer); + audio::stop(sound, mixer); }; if (manager.isRecording) @@ -320,7 +320,7 @@ namespace anm2ed::imgui } else { - auto firstFrame = Texture(renderTempFrames.front()); + auto firstFrame = Image(renderTempFrames.front()); if (firstFrame.size.x <= 0 || firstFrame.size.y <= 0 || firstFrame.pixels.empty()) { toast_log(Level::ERROR, TOAST_SPRITESHEET_EMPTY); @@ -335,7 +335,7 @@ namespace anm2ed::imgui for (std::size_t index = 0; index < renderTempFrames.size(); ++index) { - auto frame = Texture(renderTempFrames[index]); + auto frame = Image(renderTempFrames[index]); auto row = (int)(index / columns); auto column = (int)(index % columns); if (row >= rows || column >= columns) break; @@ -351,7 +351,7 @@ namespace anm2ed::imgui } } - Texture spritesheetTexture(spritesheet.data(), spritesheetSize); + Image spritesheetTexture(spritesheet.data(), spritesheetSize); if (spritesheetTexture.write_png(path)) { toast_log(Level::INFO, TOAST_EXPORT_SPRITESHEET, pathString); @@ -430,7 +430,7 @@ namespace anm2ed::imgui if (!manager.isRecording && !document.sounds.empty() && isSound) { if (auto soundID = trigger_sound_id_get(document, animation, playback.time); soundID != -1) - if (auto sound = document.sound_get(soundID)) sound->play(false, mixer); + if (auto sound = document.sound_get(soundID)) audio::play(*sound, false, mixer); } auto info = element_first_get(anm2.root, ElementType::INFO); @@ -583,13 +583,13 @@ namespace anm2ed::imgui overlayTransparency = glm::clamp(overlayTransparency, 0.0f, 100.0f); ImGui::SameLine(); - radio_button_icon("##Overlay Over", &overlayDrawOrder, overlay_draw_order::OVER, resources.icons[icon::OVER].id, - orderIconSize, overlayIconTint); + radio_button_icon("##Overlay Over", &overlayDrawOrder, overlay_draw_order::OVER, + resources.icon_id_get(icon::OVER), orderIconSize, overlayIconTint); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY_OVER)); ImGui::SameLine(); radio_button_icon("##Overlay Under", &overlayDrawOrder, overlay_draw_order::UNDER, - resources.icons[icon::UNDER].id, orderIconSize, overlayIconTint); + resources.icon_id_get(icon::UNDER), orderIconSize, overlayIconTint); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY_UNDER)); } ImGui::EndChild(); @@ -886,7 +886,7 @@ namespace anm2ed::imgui vec4 color = isOnion ? vec4(sampleColor, sampleAlpha) : color::GREEN; auto icon = isAltIcons ? icon::TARGET_ALT : icon::TARGET; - texture_render(shaderTexture, resources.icons[icon].id, rootTransform, color); + texture_render(shaderTexture, resources.icon_id_get(icon), rootTransform, color); }; if (layeredOnions && root) @@ -921,7 +921,7 @@ namespace anm2ed::imgui reference.groupType == groupType && reference.groupId == group.id; vec4 color = isOnion ? vec4(sampleColor, sampleAlpha) : isSelected ? color::RED : ROOT_COLOR; auto icon = isAltIcons ? icon::TARGET_ALT : icon::TARGET; - texture_render(shaderTexture, resources.icons[icon].id, rootTransform, color); + texture_render(shaderTexture, resources.icon_id_get(icon), rootTransform, color); }; if (auto layerAnimations = child_first_get(*animation, ElementType::LAYER_ANIMATIONS)) @@ -1005,8 +1005,8 @@ namespace anm2ed::imgui auto customShader = sampleDocument.shader_get(frame.shaderId); auto& layerShader = customShader ? *customShader : shaderTexture; - texture_render(layerShader, texture.id, layerTransform, frameTint, frameColorOffset, vertices.data(), - vec2(texture.size), sampleTime); + texture_render(layerShader, resource::texture::id_get(texture), layerTransform, frameTint, + frameColorOffset, vertices.data(), vec2(texture.size), sampleTime); auto color = isOnion ? vec4(sampleColor, 1.0f - sampleAlpha) : is_layer_animation_selected(sampleDocument, id) ? SELECTED_LAYER_BORDER_COLOR @@ -1021,7 +1021,7 @@ namespace anm2ed::imgui math::percent_to_unit(frame.shear)); auto pivotTransform = itemTransform * pivotModel; - texture_render(shaderTexture, resources.icons[icon::PIVOT].id, pivotTransform, color); + texture_render(shaderTexture, resources.icon_id_get(icon::PIVOT), pivotTransform, color); } }; @@ -1093,7 +1093,7 @@ namespace anm2ed::imgui group_transform_for_time(*nullAnimations, nullAnimation, sampleTime, sampleTransform); auto nullTransform = itemTransform * nullModel; - texture_render(shaderTexture, resources.icons[icon].id, nullTransform, color); + texture_render(shaderTexture, resources.icon_id_get(icon), nullTransform, color); if (isShowRect) { @@ -1182,7 +1182,7 @@ namespace anm2ed::imgui if (isRenderPreviewOverridden) pixels_unpremultiply_alpha(pixels); auto framePath = renderTempDirectory / render_frame_filename(settings.renderFormat, renderFrameIndex, settings.renderType); - if (Texture::write_pixels_png(framePath, size, pixels.data())) + if (Image::write_pixels_png(framePath, size, pixels.data())) { renderTempFrames.push_back(framePath); ++renderFrameIndex; diff --git a/src/imgui/window/regions.cpp b/src/imgui/window/regions.cpp index 880722b..7e30862 100644 --- a/src/imgui/window/regions.cpp +++ b/src/imgui/window/regions.cpp @@ -77,21 +77,21 @@ namespace anm2ed::imgui .isValid = true}; } - bool region_pixels_get(const Element& region, const Texture& texture, std::vector& pixels, ivec2& size) + bool region_pixels_get(const Element& region, const Image& texture, std::vector& pixels, ivec2& size) { auto minPoint = ivec2(glm::min(region.crop, region.crop + region.size)); size = ivec2(glm::max(region.crop, region.crop + region.size)) - minPoint; if (size.x <= 0 || size.y <= 0 || texture.size.x <= 0 || texture.size.y <= 0 || texture.pixels.empty()) return false; - pixels.assign((size_t)size.x * size.y * texture::CHANNELS, 0); + pixels.assign((size_t)size.x * size.y * image::CHANNELS, 0); for (int y = 0; y < size.y; y++) for (int x = 0; x < size.x; x++) { auto source = minPoint + ivec2(x, y); if (source.x < 0 || source.y < 0 || source.x >= texture.size.x || source.y >= texture.size.y) continue; - std::copy_n(texture.pixels.data() + ((size_t)source.y * texture.size.x + source.x) * texture::CHANNELS, - texture::CHANNELS, pixels.data() + ((size_t)y * size.x + x) * texture::CHANNELS); + std::copy_n(texture.pixels.data() + ((size_t)source.y * texture.size.x + source.x) * image::CHANNELS, + image::CHANNELS, pixels.data() + ((size_t)y * size.x + x) * image::CHANNELS); } return true; } @@ -124,7 +124,7 @@ namespace anm2ed::imgui pathString = path::to_utf8(outputPath); WorkingDirectory workingDirectory(document.directory_get()); path::ensure_directory(outputPath.parent_path()); - if (!Texture::write_pixels_png(outputPath, exportSize, pixels.data())) + if (!Image::write_pixels_png(outputPath, exportSize, pixels.data())) { toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, sourceRegion.name, pathString); return false; @@ -150,7 +150,7 @@ namespace anm2ed::imgui exported.children.push_back(exportedRegion); spritesheets->children.push_back(exported); - document.textures[exported.id] = Texture(pixels.data(), exportSize); + document.textures[exported.id] = Image(pixels.data(), exportSize); document.texturePaths[exported.id] = exported.path; document.spritesheet.reference = exported.id; document.spritesheet.selection = {exported.id}; @@ -338,7 +338,7 @@ namespace anm2ed::imgui if (ImGui::BeginChild("##Export Region Child", child_size_get(REGION_POPUP_ROWS), ImGuiChildFlags_Borders)) { - if (ImGui::ImageButton("##Export Region Path Set", resources.icons[icon::FOLDER].id, icon_size_get()) && + if (ImGui::ImageButton("##Export Region Path Set", resources.icon_id_get(icon::FOLDER), icon_size_get()) && window.dialog) window.dialog->file_save(Dialog::REGION_EXPORT_PATH_SET, settings.exportRegionPath); ImGui::SameLine(); diff --git a/src/imgui/window/shaders.cpp b/src/imgui/window/shaders.cpp index 643564f..f30b9d0 100644 --- a/src/imgui/window/shaders.cpp +++ b/src/imgui/window/shaders.cpp @@ -97,8 +97,8 @@ namespace anm2ed::imgui auto isDefault = shaderPath.empty(); auto displayPath = isDefault ? path::from_utf8(localize.get(BASIC_DEFAULT)) : shaderPath; - if (ImGui::ImageButton(std::format("##{} Path Set", localize.get(label)).c_str(), resources.icons[icon::FOLDER].id, - icon_size_get())) + if (ImGui::ImageButton(std::format("##{} Path Set", localize.get(label)).c_str(), + resources.icon_id_get(icon::FOLDER), icon_size_get())) { if (shader) { @@ -432,7 +432,8 @@ namespace anm2ed::imgui ImGui::SetCursorPos(cursorPos); auto imageSize = ImVec2(shaderChildSize.y, shaderChildSize.y); - ImGui::ImageWithBg(shaderIcon.id, imageSize, ImVec2(), ImVec2(1, 1), ImVec4(), tintColor); + ImGui::ImageWithBg(resource::texture::id_get(shaderIcon), imageSize, ImVec2(), ImVec2(1, 1), ImVec4(), + tintColor); ImGui::SetCursorPos(ImVec2(shaderChildSize.y + style.ItemSpacing.x, shaderChildSize.y - shaderChildSize.y / 2 - ImGui::GetTextLineHeight() / 2)); diff --git a/src/imgui/window/sounds.cpp b/src/imgui/window/sounds.cpp index ad6ee9d..8b5dd98 100644 --- a/src/imgui/window/sounds.cpp +++ b/src/imgui/window/sounds.cpp @@ -41,7 +41,8 @@ namespace anm2ed::imgui }; window.row_select = [](Window&, Document& document, int id) { - if (auto audio = document.sound_get(id); audio && ImGui::IsItemClicked(ImGuiMouseButton_Left)) audio->play(); + if (auto audio = document.sound_get(id); audio && ImGui::IsItemClicked(ImGuiMouseButton_Left)) + resource::audio::play(*audio); }; window.card_image_get = [](Document& document, Resources& resources, const Element& sound) { @@ -73,7 +74,7 @@ namespace anm2ed::imgui }; window.play = [](Window&, Manager&, Settings&, Document& document, Clipboard&) { - if (auto audio = document.sound_get(*document.sound.selection.begin())) audio->play(); + if (auto audio = document.sound_get(*document.sound.selection.begin())) resource::audio::play(*audio); }; window.open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { diff --git a/src/imgui/window/spritesheet_editor.cpp b/src/imgui/window/spritesheet_editor.cpp index 5f62823..ffe34d5 100644 --- a/src/imgui/window/spritesheet_editor.cpp +++ b/src/imgui/window/spritesheet_editor.cpp @@ -170,7 +170,7 @@ namespace anm2ed::imgui auto spritesheetTransform = transform * spritesheetModel; if (baseTexture && baseTexture->is_valid()) - texture_render(shaderTexture, baseTexture->id, spritesheetTransform); + texture_render(shaderTexture, resource::texture::id_get(*baseTexture), spritesheetTransform); if (isGrid) grid_render(shaderGrid, zoom, pan, gridSize, gridOffset, gridColor); @@ -223,7 +223,7 @@ namespace anm2ed::imgui auto pivotTransform = transform * math::quad_model_get(PIVOT_SIZE, region.crop + region.pivot, PIVOT_SIZE * 0.5f); - texture_render(shaderTexture, resources.icons[icon::PIVOT].id, pivotTransform, color::WHITE); + texture_render(shaderTexture, resources.icon_id_get(icon::PIVOT), pivotTransform, color::WHITE); } if (highlightedRegionId != -1) @@ -234,7 +234,7 @@ namespace anm2ed::imgui auto pivotTransform = transform * math::quad_model_get(PIVOT_SIZE, region->crop + region->pivot, PIVOT_SIZE * 0.5f); - texture_render(shaderTexture, resources.icons[icon::PIVOT].id, pivotTransform, PIVOT_COLOR); + texture_render(shaderTexture, resources.icon_id_get(icon::PIVOT), pivotTransform, PIVOT_COLOR); } } @@ -247,7 +247,7 @@ namespace anm2ed::imgui auto pivotTransform = transform * math::quad_model_get(PIVOT_SIZE, frame->crop + frame->pivot, PIVOT_SIZE * 0.5f); - texture_render(shaderTexture, resources.icons[icon::PIVOT].id, pivotTransform, PIVOT_COLOR); + texture_render(shaderTexture, resources.icon_id_get(icon::PIVOT), pivotTransform, PIVOT_COLOR); } } diff --git a/src/imgui/window/timeline/frames.cpp b/src/imgui/window/timeline/frames.cpp index e6db6d4..cf52a22 100644 --- a/src/imgui/window/timeline/frames.cpp +++ b/src/imgui/window/timeline/frames.cpp @@ -327,13 +327,13 @@ namespace anm2ed::imgui if (length > 0) { ImGui::SetCursorPos(ImVec2(cursorPos.x + frameSize.x * floorf(playback.time), cursorPos.y)); - ImGui::Image(resources.icons[icon::PLAYHEAD].id, frameSize); + ImGui::Image(resources.icon_id_get(icon::PLAYHEAD), frameSize); auto playheadMin = ImGui::GetItemRectMin(); auto playheadMax = ImGui::GetItemRectMax(); playheadLineCenterX = (playheadMin.x + playheadMax.x) * 0.5f; playheadLineTopY = playheadMax.y; isPlayheadLineSet = true; - overlay_icon(resources.icons[icon::PLAYHEAD].id, playheadIconTint, true); + overlay_icon(resources.icon_id_get(icon::PLAYHEAD), playheadIconTint, true); } } else if (animation) @@ -596,8 +596,8 @@ namespace anm2ed::imgui auto iconPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), cursorPos.y + (frameSize.y / 2) - (icon_size_get().y / 2)); ImGui::SetCursorPos(iconPos); - ImGui::Image(resources.icons[icon].id, icon_size_get()); - overlay_icon(resources.icons[icon].id, iconTintDefault, false); + ImGui::Image(resources.icon_id_get(icon), icon_size_get()); + overlay_icon(resources.icon_id_get(icon), iconTintDefault, false); if (type != TRIGGER) frameTime += frame.duration; diff --git a/src/imgui/window/timeline/tracks.cpp b/src/imgui/window/timeline/tracks.cpp index e4ae9a0..bb25fb4 100644 --- a/src/imgui/window/timeline/tracks.cpp +++ b/src/imgui/window/timeline/tracks.cpp @@ -115,10 +115,10 @@ namespace anm2ed::imgui ImGui::SetCursorPos(cursorPos); auto folderIcon = group->isExpanded ? icon::FOLDER_OPEN : icon::FOLDER; - ImGui::Image(resources.icons[folderIcon].id, icon_size_get()); + ImGui::Image(resources.icon_id_get(folderIcon), icon_size_get()); auto iconMin = ImGui::GetItemRectMin(); auto iconMax = ImGui::GetItemRectMax(); - overlay_icon(resources.icons[folderIcon].id, itemIconTint, false); + overlay_icon(resources.icon_id_get(folderIcon), itemIconTint, false); ImGui::SameLine(); ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); @@ -134,7 +134,7 @@ namespace anm2ed::imgui ImGui::SetCursorPos(ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); int visibleIcon = isGroupVisible ? icon::VISIBLE : icon::INVISIBLE; - if (ImGui::ImageButton("##Group Visible Toggle", resources.icons[visibleIcon].id, icon_size_get())) + if (ImGui::ImageButton("##Group Visible Toggle", resources.icon_id_get(visibleIcon), icon_size_get())) { auto targetAnimationIndex = reference.animationIndex; auto targetType = type; @@ -154,7 +154,7 @@ namespace anm2ed::imgui } auto visibleButtonMin = ImGui::GetItemRectMin(); auto visibleButtonMax = ImGui::GetItemRectMax(); - overlay_icon(resources.icons[visibleIcon].id, itemIconTint, false); + overlay_icon(resources.icon_id_get(visibleIcon), itemIconTint, false); ImGui::SetItemTooltip("%s", isGroupVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); ImGui::PopStyleVar(2); @@ -380,8 +380,8 @@ namespace anm2ed::imgui contentCursorPos.x += (float)row.depth * ImGui::GetTextLineHeightWithSpacing(); ImGui::SetCursorPos(contentCursorPos); - ImGui::Image(resources.icons[icon].id, icon_size_get()); - overlay_icon(resources.icons[icon].id, iconTintCurrent, false); + ImGui::Image(resources.icon_id_get(icon), icon_size_get()); + overlay_icon(resources.icon_id_get(icon), iconTintCurrent, false); ImGui::SameLine(); if (isReferenced) ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); @@ -398,7 +398,7 @@ namespace anm2ed::imgui ImGui::SetCursorPos(ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); int visibleIcon = isItemVisible ? icon::VISIBLE : icon::INVISIBLE; - if (ImGui::ImageButton("##Visible Toggle", resources.icons[visibleIcon].id, icon_size_get())) + if (ImGui::ImageButton("##Visible Toggle", resources.icon_id_get(visibleIcon), icon_size_get())) { auto animationIndex = reference.animationIndex; auto targetType = type; @@ -414,7 +414,7 @@ namespace anm2ed::imgui item->isVisible = !item->isVisible; }); } - overlay_icon(resources.icons[visibleIcon].id, iconTintCurrent, false); + overlay_icon(resources.icon_id_get(visibleIcon), iconTintCurrent, false); ImGui::SetItemTooltip("%s", isItemVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); @@ -427,7 +427,7 @@ namespace anm2ed::imgui ImGui::SetCursorPos( ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - if (ImGui::ImageButton("##Rect Toggle", resources.icons[rectIcon].id, icon_size_get())) + if (ImGui::ImageButton("##Rect Toggle", resources.icon_id_get(rectIcon), icon_size_get())) { auto nullID = id; edit_command_push(EDIT_TOGGLE_NULL_RECT, Document::FRAMES, @@ -439,7 +439,7 @@ namespace anm2ed::imgui null->isShowRect = !null->isShowRect; }); } - overlay_icon(resources.icons[rectIcon].id, iconTintCurrent, false); + overlay_icon(resources.icon_id_get(rectIcon), iconTintCurrent, false); ImGui::SetItemTooltip("%s", isShowRect ? localize.get(TOOLTIP_NULL_RECT_SHOWN) : localize.get(TOOLTIP_NULL_RECT_HIDDEN)); } @@ -461,9 +461,9 @@ namespace anm2ed::imgui auto& isShowUnused = settings.timelineIsShowUnused; auto unusedIcon = isShowUnused ? icon::SHOW_UNUSED : icon::HIDE_UNUSED; - if (ImGui::ImageButton("##Unused Toggle", resources.icons[unusedIcon].id, icon_size_get())) + if (ImGui::ImageButton("##Unused Toggle", resources.icon_id_get(unusedIcon), icon_size_get())) isShowUnused = !isShowUnused; - overlay_icon(resources.icons[unusedIcon].id, iconTintCurrent, false); + overlay_icon(resources.icon_id_get(unusedIcon), iconTintCurrent, false); ImGui::SetItemTooltip("%s", isShowUnused ? localize.get(TOOLTIP_UNUSED_ITEMS_SHOWN) : localize.get(TOOLTIP_UNUSED_ITEMS_HIDDEN)); @@ -472,9 +472,9 @@ namespace anm2ed::imgui ImGui::SetCursorPos( ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - if (ImGui::ImageButton("##Layers Toggle", resources.icons[layersIcon].id, icon_size_get())) + if (ImGui::ImageButton("##Layers Toggle", resources.icon_id_get(layersIcon), icon_size_get())) showLayersOnly = !showLayersOnly; - overlay_icon(resources.icons[layersIcon].id, iconTintCurrent, false); + overlay_icon(resources.icon_id_get(layersIcon), iconTintCurrent, false); ImGui::SetItemTooltip("%s", showLayersOnly ? localize.get(TOOLTIP_ONLY_LAYERS_VISIBLE) : localize.get(TOOLTIP_ALL_ITEMS_VISIBLE)); ImGui::PopStyleVar(2); diff --git a/src/imgui/window/tools.cpp b/src/imgui/window/tools.cpp index 1628265..7c45ee9 100644 --- a/src/imgui/window/tools.cpp +++ b/src/imgui/window/tools.cpp @@ -73,8 +73,8 @@ namespace anm2ed::imgui { if (i == tool::UNDO) ImGui::BeginDisabled(!document.is_able_to_undo()); if (i == tool::REDO) ImGui::BeginDisabled(!document.is_able_to_redo()); - if (ImGui::ImageButton(labelText, resources.icons[info.icon].id, to_imvec2(size), ImVec2(0, 0), ImVec2(1, 1), - ImVec4(0, 0, 0, 0), iconTint)) + if (ImGui::ImageButton(labelText, resources.icon_id_get(info.icon), to_imvec2(size), ImVec2(0, 0), + ImVec2(1, 1), ImVec4(0, 0, 0, 0), iconTint)) tool_use((tool::Type)i); if (i == tool::UNDO) ImGui::EndDisabled(); if (i == tool::REDO) ImGui::EndDisabled(); diff --git a/src/imgui/window/window.cpp b/src/imgui/window/window.cpp index 06e65f8..0f34e5e 100644 --- a/src/imgui/window/window.cpp +++ b/src/imgui/window/window.cpp @@ -457,8 +457,8 @@ namespace anm2ed::imgui auto noScrollFlags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); if (ImGui::BeginChild("##Tooltip Image Child", to_imvec2(previewSize), childFlags, noScrollFlags)) - ImGui::ImageWithBg(image.texture->id, to_imvec2(previewSize), to_imvec2(image.uvMin), to_imvec2(image.uvMax), - ImVec4(), image.isValid ? CARD_TINT_VALID : CARD_TINT_INVALID); + ImGui::ImageWithBg(resource::texture::id_get(*image.texture), to_imvec2(previewSize), to_imvec2(image.uvMin), + to_imvec2(image.uvMax), ImVec4(), image.isValid ? CARD_TINT_VALID : CARD_TINT_INVALID); ImGui::EndChild(); ImGui::PopStyleVar(); @@ -540,8 +540,8 @@ namespace anm2ed::imgui else imageSize.y = imageSize.x / aspectRatio; ImGui::SetCursorPos(cursorPos); - ImGui::ImageWithBg(image.texture->id, imageSize, to_imvec2(image.uvMin), to_imvec2(image.uvMax), ImVec4(), - tint); + ImGui::ImageWithBg(resource::texture::id_get(*image.texture), imageSize, to_imvec2(image.uvMin), + to_imvec2(image.uvMax), ImVec4(), tint); ImGui::SetCursorPos( ImVec2(cardSize.y + style.ItemSpacing.x, cardSize.y - cardSize.y / 2 - ImGui::GetTextLineHeight() / 2)); diff --git a/src/imgui/window/window.hpp b/src/imgui/window/window.hpp index 1999644..d5483f6 100644 --- a/src/imgui/window/window.hpp +++ b/src/imgui/window/window.hpp @@ -66,7 +66,7 @@ namespace anm2ed::imgui struct WindowCardImage { - resource::Texture* texture{}; + resource::Image* texture{}; glm::vec2 size{}; glm::vec2 uvMin{}; glm::vec2 uvMax{1.0f}; diff --git a/src/imgui/wizard/about.cpp b/src/imgui/wizard/about.cpp index f2efd23..0006f04 100644 --- a/src/imgui/wizard/about.cpp +++ b/src/imgui/wizard/about.cpp @@ -153,7 +153,7 @@ namespace anm2ed::imgui::wizard if (auto spritesheets = state.anm2.element_get(ElementType::SPRITESHEETS)) for (auto& spritesheet : spritesheets->children) if (spritesheet.type == ElementType::SPRITESHEET) - state.textures[spritesheet.id] = Texture(info.png, info.pngSize); + state.textures[spritesheet.id] = resource::Image(info.png, info.pngSize); auto animation = friend_animation_get(state); if (!animation) @@ -216,8 +216,8 @@ namespace anm2ed::imgui::wizard auto tint = frame.tint * rootFrame.tint; auto colorOffset = frame.colorOffset + rootFrame.colorOffset; - state.canvas->texture_render(resources.shaders[shader::TEXTURE], texture.id, transform, tint, colorOffset, - uvVertices.data()); + state.canvas->texture_render(resources.shaders[shader::TEXTURE], resource::texture::id_get(texture), transform, + tint, colorOffset, uvVertices.data()); } void friend_canvas_draw(About::FriendState& state, Resources& resources, ImVec2 displaySize) @@ -332,7 +332,7 @@ namespace anm2ed::imgui::wizard void About::reset(Resources& resources) { - resources.music_track().play(true); + resource::audio::play(resources.music_track(), true); creditsState = {}; creditsState.spawnTimer = CREDIT_DELAY; diff --git a/src/imgui/wizard/about.hpp b/src/imgui/wizard/about.hpp index 2599c51..b477387 100644 --- a/src/imgui/wizard/about.hpp +++ b/src/imgui/wizard/about.hpp @@ -38,7 +38,7 @@ namespace anm2ed::imgui::wizard { Anm2 anm2{}; std::unique_ptr canvas{}; - std::unordered_map textures{}; + std::unordered_map textures{}; glm::vec4 rect{-1.0f}; float time{}; float fps{30.0f}; diff --git a/src/imgui/wizard/generate_animation_from_grid.cpp b/src/imgui/wizard/generate_animation_from_grid.cpp index d49b6e2..c61fb48 100644 --- a/src/imgui/wizard/generate_animation_from_grid.cpp +++ b/src/imgui/wizard/generate_animation_from_grid.cpp @@ -108,7 +108,8 @@ namespace anm2ed::imgui::wizard math::percent_to_unit(frame.shear)); auto vertices = math::uv_vertices_get(uvMin, uvMax); - texture_render(shaderTexture, sourceTexture->id, transform, frame.tint, frame.colorOffset, vertices.data()); + texture_render(shaderTexture, resource::texture::id_get(*sourceTexture), transform, frame.tint, + frame.colorOffset, vertices.data()); } } } diff --git a/src/imgui/wizard/render_animation.cpp b/src/imgui/wizard/render_animation.cpp index 83ac4ef..4f2d56f 100644 --- a/src/imgui/wizard/render_animation.cpp +++ b/src/imgui/wizard/render_animation.cpp @@ -134,7 +134,7 @@ namespace anm2ed::imgui::wizard break; } - if (ImGui::ImageButton("##FFmpeg Path Set", resources.icons[icon::FOLDER].id, icon_size_get())) + if (ImGui::ImageButton("##FFmpeg Path Set", resources.icon_id_get(icon::FOLDER), icon_size_get())) dialog.file_open(Dialog::FFMPEG_PATH_SET); ImGui::SameLine(); input_text_path(localize.get(LABEL_FFMPEG_PATH), &ffmpegPath); @@ -146,7 +146,7 @@ namespace anm2ed::imgui::wizard dialog.reset(); } - if (ImGui::ImageButton("##Path Set", resources.icons[icon::FOLDER].id, icon_size_get())) + if (ImGui::ImageButton("##Path Set", resources.icon_id_get(icon::FOLDER), icon_size_get())) { if (dialogType == Dialog::PNG_DIRECTORY_SET) dialog.folder_open(dialogType); diff --git a/src/loader.cpp b/src/loader.cpp index 7faa8c6..85fbefe 100644 --- a/src/loader.cpp +++ b/src/loader.cpp @@ -317,7 +317,7 @@ namespace anm2ed if (ImGui::GetCurrentContext()) { settings.save(settings_path(), ImGui::SaveIniSettingsToMemory(nullptr)); - resource::Texture::garbage_collect(); + resource::texture::garbage_collect(); ImGui_ImplSDL3_Shutdown(); ImGui_ImplOpenGL3_Shutdown(); diff --git a/src/resource/audio.cpp b/src/resource/audio.cpp index 98e5405..2f12c91 100644 --- a/src/resource/audio.cpp +++ b/src/resource/audio.cpp @@ -1,188 +1,75 @@ #include "audio.hpp" -#include -#include +#include -#include "file.hpp" - -using namespace anm2ed::util; - -namespace anm2ed::resource +namespace anm2ed::resource::audio { - MIX_Mixer* Audio::mixer_get() + struct Entry + { + MIX_Audio* audio{}; + MIX_Track* track{}; + }; + + std::unordered_map entries{}; + + MIX_Mixer* mixer_get() { static auto mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, nullptr); return mixer; } - Audio::Audio(const std::filesystem::path& path) + Entry* entry_get(const AudioData& data) { - if (path.empty()) return; - - File file(path, "rb"); - if (!file) return; - - if (std::fseek(file.get(), 0, SEEK_END) != 0) return; - auto size = std::ftell(file.get()); - if (size <= 0) - { - return; - } - std::rewind(file.get()); - - data.resize(static_cast(size)); - auto read = std::fread(data.data(), 1, data.size(), file.get()); - if (read == 0) - { - data.clear(); - return; - } - data.resize(read); - - SDL_IOStream* io = SDL_IOFromConstMem(data.data(), data.size()); - if (!io) - data.clear(); - else - { - internal = MIX_LoadAudio_IO(mixer_get(), io, true, true); - if (!internal) data.clear(); - } + if (!data.is_valid()) return nullptr; + auto [it, isNew] = entries.try_emplace(data.uid); + if (isNew) + if (auto io = SDL_IOFromConstMem(data.bytes.data(), data.bytes.size())) + it->second.audio = MIX_LoadAudio_IO(mixer_get(), io, true, true); + return it->second.audio ? &it->second : nullptr; } - Audio::Audio(const unsigned char* memory, size_t size) + // The playing track, when it belongs to mixer (or any mixer, when none is given). + MIX_Track* track_get(const AudioData& data, MIX_Mixer* mixer) { - if (!memory || size == 0) return; - data.assign(memory, memory + size); - - SDL_IOStream* io = SDL_IOFromConstMem(data.data(), data.size()); - if (!io) - data.clear(); - else - { - internal = MIX_LoadAudio_IO(mixer_get(), io, true, true); - if (!internal) data.clear(); - } + auto it = entries.find(data.uid); + if (it == entries.end() || !it->second.track) return nullptr; + return !mixer || MIX_GetTrackMixer(it->second.track) == mixer ? it->second.track : nullptr; } - void Audio::unload() + void play(const AudioData& data, bool isLoop, MIX_Mixer* mixer) { - if (track) - { - MIX_DestroyTrack(track); - track = nullptr; - } - if (internal) - { - MIX_DestroyAudio(internal); - internal = nullptr; - } - } - - void Audio::play(bool loop, MIX_Mixer* mixer) - { - if (!internal) return; + auto entry = entry_get(data); auto targetMixer = mixer ? mixer : mixer_get(); - if (!targetMixer) return; + if (!entry || !targetMixer) return; - if (track && MIX_GetTrackMixer(track) != targetMixer) - { - MIX_DestroyTrack(track); - track = nullptr; - } + if (entry->track && MIX_GetTrackMixer(entry->track) != targetMixer) track_detach(data); + if (!entry->track) entry->track = MIX_CreateTrack(targetMixer); + if (!entry->track) return; - if (!track) - { - track = MIX_CreateTrack(targetMixer); - if (!track) return; - } - - MIX_SetTrackAudio(track, internal); - - SDL_PropertiesID options = 0; - if (loop) - { - options = SDL_CreateProperties(); - if (options) SDL_SetNumberProperty(options, MIX_PROP_PLAY_LOOPS_NUMBER, -1); - } - - MIX_PlayTrack(track, options); + MIX_SetTrackAudio(entry->track, entry->audio); + SDL_PropertiesID options = isLoop ? SDL_CreateProperties() : 0; + if (options) SDL_SetNumberProperty(options, MIX_PROP_PLAY_LOOPS_NUMBER, -1); + MIX_PlayTrack(entry->track, options); if (options) SDL_DestroyProperties(options); } - void Audio::stop(MIX_Mixer* mixer) + void stop(const AudioData& data, MIX_Mixer* mixer) { - if (!track) return; - if (mixer && MIX_GetTrackMixer(track) != mixer) return; - MIX_StopTrack(track, 0); + if (auto track = track_get(data, mixer)) MIX_StopTrack(track, 0); } - void Audio::track_detach(MIX_Mixer* mixer) + void track_detach(const AudioData& data, MIX_Mixer* mixer) { - if (!track) return; - if (mixer && MIX_GetTrackMixer(track) != mixer) return; + if (!track_get(data, mixer)) return; + auto& track = entries[data.uid].track; MIX_DestroyTrack(track); track = nullptr; } - bool Audio::is_playing() const { return track && MIX_TrackPlaying(track); } - - Audio::Audio(const Audio& other) + bool is_playing(const AudioData& data) { - if (other.data.empty()) return; - - data = other.data; - SDL_IOStream* io = SDL_IOFromConstMem(data.data(), data.size()); - if (!io) - data.clear(); - else - { - internal = MIX_LoadAudio_IO(mixer_get(), io, true, true); - if (!internal) data.clear(); - } + auto track = track_get(data, nullptr); + return track && MIX_TrackPlaying(track); } - - Audio::Audio(Audio&& other) noexcept - { - internal = std::exchange(other.internal, nullptr); - track = std::exchange(other.track, nullptr); - data = std::move(other.data); - } - - Audio& Audio::operator=(Audio&& other) noexcept - { - if (this != &other) - { - unload(); - internal = std::exchange(other.internal, nullptr); - track = std::exchange(other.track, nullptr); - data = std::move(other.data); - } - return *this; - } - - Audio& Audio::operator=(const Audio& other) - { - if (this != &other) - { - unload(); - data.clear(); - if (!other.data.empty()) - { - data = other.data; - SDL_IOStream* io = SDL_IOFromConstMem(data.data(), data.size()); - if (!io) - data.clear(); - else - { - internal = MIX_LoadAudio_IO(mixer_get(), io, true, true); - if (!internal) data.clear(); - } - } - } - return *this; - } - - Audio::~Audio() { unload(); } - bool Audio::is_valid() { return internal; } } diff --git a/src/resource/audio.hpp b/src/resource/audio.hpp index f93773e..44dc206 100644 --- a/src/resource/audio.hpp +++ b/src/resource/audio.hpp @@ -1,34 +1,14 @@ #pragma once #include -#include -#include -#include -namespace anm2ed::resource +#include "audio_data.hpp" + +// Playback of AudioData; decoded audio and tracks are cached per AudioData uid. +namespace anm2ed::resource::audio { - class Audio - { - MIX_Audio* internal{nullptr}; - MIX_Track* track{nullptr}; - std::vector data{}; - MIX_Mixer* mixer_get(); - void unload(); - - public: - Audio(const unsigned char*, size_t); - Audio(const std::filesystem::path&); - ~Audio(); - Audio() = default; - Audio(const Audio&); - Audio(Audio&&) noexcept; - Audio& operator=(const Audio&); - Audio& operator=(Audio&&) noexcept; - - bool is_valid(); - void play(bool loop = false, MIX_Mixer* = nullptr); - void stop(MIX_Mixer* = nullptr); - void track_detach(MIX_Mixer* = nullptr); - bool is_playing() const; - }; + void play(const AudioData&, bool = false, MIX_Mixer* = nullptr); + void stop(const AudioData&, MIX_Mixer* = nullptr); + void track_detach(const AudioData&, MIX_Mixer* = nullptr); + bool is_playing(const AudioData&); } diff --git a/src/resource/audio_data.cpp b/src/resource/audio_data.cpp new file mode 100644 index 0000000..20ec6a8 --- /dev/null +++ b/src/resource/audio_data.cpp @@ -0,0 +1,25 @@ +#include "audio_data.hpp" + +#include +#include + +#include "uid.hpp" + +namespace anm2ed::resource +{ + AudioData::AudioData(const unsigned char* memory, size_t size) + { + if (!memory || size == 0) return; + bytes.assign(memory, memory + size); + uid = util::uid_next(); + } + + AudioData::AudioData(const std::filesystem::path& path) + { + std::ifstream file(path, std::ios::binary); + std::vector data{std::istreambuf_iterator(file), {}}; + *this = AudioData(data.data(), data.size()); + } + + bool AudioData::is_valid() const { return !bytes.empty(); } +} diff --git a/src/resource/audio_data.hpp b/src/resource/audio_data.hpp new file mode 100644 index 0000000..1865d89 --- /dev/null +++ b/src/resource/audio_data.hpp @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include +#include + +namespace anm2ed::resource +{ + // Encoded audio file bytes. uid identifies the bytes so playback state can be cached by it. + struct AudioData + { + std::vector bytes{}; + std::uint64_t uid{}; + + AudioData() = default; + AudioData(const unsigned char*, size_t); + AudioData(const std::filesystem::path&); + + bool is_valid() const; + }; +} diff --git a/src/resource/image.cpp b/src/resource/image.cpp new file mode 100644 index 0000000..70ecfee --- /dev/null +++ b/src/resource/image.cpp @@ -0,0 +1,184 @@ +#include "image.hpp" + +#include +#include +#include +#include +#include + +#if defined(__clang__) || defined(__GNUC__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wmissing-field-initializers" + #pragma GCC diagnostic ignored "-Wunused-function" +#endif + +#define STBI_ONLY_PNG +#define STB_IMAGE_IMPLEMENTATION +#include +#define STB_IMAGE_WRITE_IMPLEMENTATION +#include + +#if defined(__clang__) || defined(__GNUC__) + #pragma GCC diagnostic pop +#endif + +#include "file.hpp" +#include "math.hpp" +#include "uid.hpp" + +using namespace anm2ed::resource::image; +using namespace anm2ed::util::math; +using namespace anm2ed::util; +using namespace glm; + +namespace anm2ed::resource +{ + bool Image::is_valid() const { return !pixels.empty(); } + + size_t Image::pixel_size_get() const { return size.x * size.y * CHANNELS; } + + Image::Image(const uint8_t* data, ivec2 size, bool isLinear) : isLinear(isLinear) + { + if (!data || size.x <= 0 || size.y <= 0) return; + this->size = size; + pixels.assign(data, data + pixel_size_get()); + uid = uid_next(); + } + + Image::Image(const unsigned char* pngData, size_t pngSize) + { + if (!pngData || pngSize == 0) return; + + auto sizeInt = static_cast(pngSize); + if (sizeInt <= 0) return; + + if (auto data = stbi_load_from_memory(pngData, sizeInt, &size.x, &size.y, nullptr, CHANNELS); data) + { + *this = Image(data, size); + stbi_image_free((void*)data); + } + } + + Image::Image(const std::filesystem::path& pngPath) + { + File file(pngPath, "rb"); + if (auto handle = file.get()) + { + if (auto data = stbi_load_from_file(handle, &size.x, &size.y, nullptr, CHANNELS); data) + { + *this = Image(data, size); + stbi_image_free((void*)data); + } + } + } + + bool Image::write_png(const std::filesystem::path& path) const + { + return write_pixels_png(path, size, pixels.empty() ? nullptr : pixels.data()); + } + + bool Image::write_pixels_png(const std::filesystem::path& path, ivec2 size, const uint8_t* data) + { + if (!data || size.x <= 0 || size.y <= 0) return false; + + File file(path, "wb"); + if (auto handle = file.get()) + { + auto write_func = [](void* context, void* bytes, int count) + { fwrite(bytes, 1, count, static_cast(context)); }; + return stbi_write_png_to_func(write_func, handle, size.x, size.y, CHANNELS, data, size.x * CHANNELS) != 0; + } + return false; + } + + Image Image::merge_append(const Image& base, const Image& append, bool isAppendRight) + { + if (base.size.x <= 0 || base.size.y <= 0) return append; + if (append.size.x <= 0 || append.size.y <= 0) return base; + if (base.pixels.empty()) return append; + if (append.pixels.empty()) return base; + + auto resultSize = isAppendRight ? ivec2(base.size.x + append.size.x, std::max(base.size.y, append.size.y)) + : ivec2(std::max(base.size.x, append.size.x), base.size.y + append.size.y); + auto resultPixelsSize = (size_t)resultSize.x * (size_t)resultSize.y * CHANNELS; + std::vector resultPixels(resultPixelsSize, 0); + + auto blit = [&](const Image& texture, ivec2 offset) + { + for (int y = 0; y < texture.size.y; y++) + { + auto src = (size_t)y * (size_t)texture.size.x * CHANNELS; + auto dst = ((size_t)(offset.y + y) * (size_t)resultSize.x + (size_t)offset.x) * CHANNELS; + std::memcpy(resultPixels.data() + dst, texture.pixels.data() + src, (size_t)texture.size.x * CHANNELS); + } + }; + + blit(base, {0, 0}); + blit(append, isAppendRight ? ivec2(base.size.x, 0) : ivec2(0, base.size.y)); + + return Image(resultPixels.data(), resultSize); + } + + vec4 Image::pixel_read(vec2 position) const + { + if (pixels.size() < CHANNELS || size.x <= 0 || size.y <= 0) return vec4(0.0f); + + int x = glm::clamp((int)(position.x), 0, size.x - 1); + int y = glm::clamp((int)(position.y), 0, size.y - 1); + + auto index = ((size_t)(y) * (size_t)(size.x) + (size_t)(x)) * CHANNELS; + if (index + CHANNELS > pixels.size()) return vec4(0.0f); + + vec4 color{uint8_to_float(pixels[index + 0]), uint8_to_float(pixels[index + 1]), uint8_to_float(pixels[index + 2]), + uint8_to_float(pixels[index + 3])}; + + if (color.a <= 0.0f) color = vec4(0.0f); + return color; + } + + void Image::pixel_set(ivec2 position, vec4 color) + { + if (position.x < 0 || position.y < 0 || position.x >= size.x || position.y >= size.y) return; + + uint8 rgba8[4] = {(uint8)float_to_uint8(color.r), (uint8)float_to_uint8(color.g), (uint8)float_to_uint8(color.b), + (uint8)float_to_uint8(color.a)}; + + if (pixels.size() != pixel_size_get()) return; + size_t idx = (position.y * size.x + position.x) * CHANNELS; + memcpy(&pixels[idx], rgba8, 4); + uid = uid_next(); + } + + void Image::pixel_line(ivec2 start, ivec2 end, vec4 color) + { + auto plot = [&](ivec2 pos) { pixel_set(pos, color); }; + + int x0 = start.x; + int y0 = start.y; + int x1 = end.x; + int y1 = end.y; + + int dx = std::abs(x1 - x0); + int dy = -std::abs(y1 - y0); + int sx = x0 < x1 ? 1 : -1; + int sy = y0 < y1 ? 1 : -1; + int err = dx + dy; + + while (true) + { + plot({x0, y0}); + if (x0 == x1 && y0 == y1) break; + int e2 = 2 * err; + if (e2 >= dy) + { + err += dy; + x0 += sx; + } + if (e2 <= dx) + { + err += dx; + y0 += sy; + } + } + } +} diff --git a/src/resource/image.hpp b/src/resource/image.hpp new file mode 100644 index 0000000..52c9ffe --- /dev/null +++ b/src/resource/image.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace anm2ed::resource::image +{ + constexpr auto CHANNELS = 4; +} + +namespace anm2ed::resource +{ + // CPU-side RGBA pixels. uid changes whenever the pixels do, so GPU copies can be cached by it. + class Image + { + public: + glm::ivec2 size{}; + std::vector pixels{}; + bool isLinear{}; + std::uint64_t uid{}; + + Image() = default; + Image(const uint8_t*, glm::ivec2, bool = false); + Image(const unsigned char*, size_t); + Image(const std::filesystem::path&); + + bool is_valid() const; + size_t pixel_size_get() const; + bool write_png(const std::filesystem::path&) const; + static bool write_pixels_png(const std::filesystem::path&, glm::ivec2, const uint8_t*); + static Image merge_append(const Image&, const Image&, bool); + glm::vec4 pixel_read(glm::vec2) const; + void pixel_set(glm::ivec2, glm::vec4); + void pixel_line(glm::ivec2, glm::ivec2, glm::vec4); + }; +} diff --git a/src/resource/texture.cpp b/src/resource/texture.cpp index 55033f3..a6e673b 100644 --- a/src/resource/texture.cpp +++ b/src/resource/texture.cpp @@ -1,294 +1,60 @@ #include "texture.hpp" -#include -#include -#include #include #include +#include #include -#if defined(__clang__) || defined(__GNUC__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wmissing-field-initializers" - #pragma GCC diagnostic ignored "-Wunused-function" -#endif - -#define STBI_ONLY_PNG -#define STB_IMAGE_IMPLEMENTATION -#include -#define STB_IMAGE_WRITE_IMPLEMENTATION -#include - -#if defined(__clang__) || defined(__GNUC__) - #pragma GCC diagnostic pop -#endif - -#include "file.hpp" -#include "math.hpp" - -using namespace anm2ed::resource::texture; -using namespace anm2ed::util::math; -using namespace anm2ed::util; -using namespace glm; - namespace anm2ed::resource::texture { - std::vector retiredTextureIds{}; -} - -namespace anm2ed::resource -{ - bool Texture::is_valid() const { return id != 0; } - - size_t Texture::pixel_size_get() const { return size.x * size.y * CHANNELS; } - - void Texture::release() + struct Entry { - if (!is_valid()) return; - texture::retiredTextureIds.push_back(id); - id = 0; - } + GLuint id{}; + bool isUsed{}; + }; - void Texture::upload(const uint8_t* data) + std::unordered_map entries{}; + + GLuint id_get(const Image& image) { - if (!data || size.x <= 0 || size.y <= 0) return; + if (!image.is_valid()) return 0; - if (!is_valid()) glGenTextures(1, &id); - - pixels.assign(data, data + pixel_size_get()); - - glBindTexture(GL_TEXTURE_2D, id); + auto [it, isNew] = entries.try_emplace(image.uid); + auto& entry = it->second; + entry.isUsed = true; + if (!isNew) return entry.id; + auto filter = image.isLinear ? GL_LINEAR : GL_NEAREST; + glGenTextures(1, &entry.id); + glBindTexture(GL_TEXTURE_2D, entry.id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size.x, size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data()); - + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.size.x, image.size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, + image.pixels.data()); glBindTexture(GL_TEXTURE_2D, 0); + return entry.id; } - Texture::Texture() = default; - - Texture::~Texture() { release(); } - - Texture::Texture(const Texture& other) { *this = other; } - - Texture::Texture(Texture&& other) { *this = std::move(other); } - - Texture& Texture::operator=(const Texture& other) + void garbage_collect() { - if (this != &other) - { - release(); - size = other.size; - filter = other.filter; - channels = other.channels; - pixels = other.pixels; - upload(pixels.data()); - } - return *this; + std::erase_if(entries, + [](auto& pair) + { + auto& entry = pair.second; + if (!entry.isUsed) glDeleteTextures(1, &entry.id); + return !std::exchange(entry.isUsed, false); + }); } - Texture& Texture::operator=(Texture&& other) + Image svg_load(const char* data, size_t length, glm::ivec2 size) { - if (this != &other) - { - release(); - id = other.id; - size = other.size; - filter = other.filter; - channels = other.channels; - pixels = std::move(other.pixels); - other.id = 0; - } - return *this; - } - - void Texture::garbage_collect() - { - if (texture::retiredTextureIds.empty()) return; - glDeleteTextures((GLsizei)texture::retiredTextureIds.size(), texture::retiredTextureIds.data()); - texture::retiredTextureIds.clear(); - } - - Texture::Texture(const char* svgData, size_t svgDataLength, ivec2 svgSize) - { - if (!svgData) return; - - const std::unique_ptr document = lunasvg::Document::loadFromData(svgData, svgDataLength); - if (!document) return; - - const lunasvg::Bitmap bitmap = document->renderToBitmap(svgSize.x, svgSize.y, 0); - if (bitmap.width() == 0 || bitmap.height() == 0) return; - - size = svgSize; - filter = GL_LINEAR; - upload(bitmap.data()); - } - - Texture::Texture(const uint8_t* data, ivec2 size) - { - this->size = size; - upload(data); - } - - Texture::Texture(const unsigned char* pngData, size_t pngSize) - { - if (!pngData || pngSize == 0) return; - - auto sizeInt = static_cast(pngSize); - if (sizeInt <= 0) return; - - if (auto data = stbi_load_from_memory(pngData, sizeInt, &size.x, &size.y, nullptr, CHANNELS); data) - { - upload(data); - stbi_image_free((void*)data); - } - } - - Texture::Texture(const std::filesystem::path& pngPath) - { - File file(pngPath, "rb"); - if (auto handle = file.get()) - { - if (auto data = stbi_load_from_file(handle, &size.x, &size.y, nullptr, CHANNELS); data) - { - upload(data); - stbi_image_free((void*)data); - } - } - } - - bool Texture::write_png(const std::filesystem::path& path) - { - if (pixels.empty()) return false; - - File file(path, "wb"); - if (auto handle = file.get()) - { - auto write_func = [](void* context, void* data, int size) { fwrite(data, 1, size, static_cast(context)); }; - - auto result = - stbi_write_png_to_func(write_func, handle, size.x, size.y, CHANNELS, this->pixels.data(), size.x * CHANNELS); - return result != 0; - } - return false; - } - - bool Texture::write_pixels_png(const std::filesystem::path& path, ivec2 size, const uint8_t* data) - { - if (!data || size.x <= 0 || size.y <= 0) return false; - - File file(path, "wb"); - if (auto handle = file.get()) - { - auto write_func = [](void* context, void* bytes, int count) - { fwrite(bytes, 1, count, static_cast(context)); }; - return stbi_write_png_to_func(write_func, handle, size.x, size.y, CHANNELS, data, size.x * CHANNELS) != 0; - } - return false; - } - - Texture Texture::merge_append(const Texture& base, const Texture& append, bool isAppendRight) - { - if (base.size.x <= 0 || base.size.y <= 0) return append; - if (append.size.x <= 0 || append.size.y <= 0) return base; - if (base.pixels.empty()) return append; - if (append.pixels.empty()) return base; - - auto resultSize = - isAppendRight ? ivec2(base.size.x + append.size.x, std::max(base.size.y, append.size.y)) - : ivec2(std::max(base.size.x, append.size.x), base.size.y + append.size.y); - auto resultPixelsSize = (size_t)resultSize.x * (size_t)resultSize.y * CHANNELS; - std::vector resultPixels(resultPixelsSize, 0); - - auto blit = [&](const Texture& texture, ivec2 offset) - { - for (int y = 0; y < texture.size.y; y++) - { - auto src = (size_t)y * (size_t)texture.size.x * CHANNELS; - auto dst = ((size_t)(offset.y + y) * (size_t)resultSize.x + (size_t)offset.x) * CHANNELS; - std::memcpy(resultPixels.data() + dst, texture.pixels.data() + src, (size_t)texture.size.x * CHANNELS); - } - }; - - blit(base, {0, 0}); - blit(append, isAppendRight ? ivec2(base.size.x, 0) : ivec2(0, base.size.y)); - - return Texture(resultPixels.data(), resultSize); - } - - vec4 Texture::pixel_read(vec2 position) const - { - if (pixels.size() < CHANNELS || size.x <= 0 || size.y <= 0) return vec4(0.0f); - - int x = glm::clamp((int)(position.x), 0, size.x - 1); - int y = glm::clamp((int)(position.y), 0, size.y - 1); - - auto index = ((size_t)(y) * (size_t)(size.x) + (size_t)(x)) * CHANNELS; - if (index + CHANNELS > pixels.size()) return vec4(0.0f); - - vec4 color{uint8_to_float(pixels[index + 0]), uint8_to_float(pixels[index + 1]), uint8_to_float(pixels[index + 2]), - uint8_to_float(pixels[index + 3])}; - - if (color.a <= 0.0f) color = vec4(0.0f); - return color; - } - - void Texture::pixel_set(ivec2 position, vec4 color) - { - if (position.x < 0 || position.y < 0 || position.x >= size.x || position.y >= size.y) return; - - uint8 rgba8[4] = {(uint8)float_to_uint8(color.r), (uint8)float_to_uint8(color.g), (uint8)float_to_uint8(color.b), - (uint8)float_to_uint8(color.a)}; - - if (is_valid()) - { - glBindTexture(GL_TEXTURE_2D, id); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glTexSubImage2D(GL_TEXTURE_2D, 0, position.x, position.y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, rgba8); - glBindTexture(GL_TEXTURE_2D, 0); - } - - if (pixels.size() == pixel_size_get()) - { - size_t idx = (position.y * size.x + position.x) * CHANNELS; - memcpy(&pixels[idx], rgba8, 4); - } - } - - void Texture::pixel_line(ivec2 start, ivec2 end, vec4 color) - { - auto plot = [&](ivec2 pos) { pixel_set(pos, color); }; - - int x0 = start.x; - int y0 = start.y; - int x1 = end.x; - int y1 = end.y; - - int dx = std::abs(x1 - x0); - int dy = -std::abs(y1 - y0); - int sx = x0 < x1 ? 1 : -1; - int sy = y0 < y1 ? 1 : -1; - int err = dx + dy; - - while (true) - { - plot({x0, y0}); - if (x0 == x1 && y0 == y1) break; - int e2 = 2 * err; - if (e2 >= dy) - { - err += dy; - x0 += sx; - } - if (e2 <= dx) - { - err += dx; - y0 += sy; - } - } + auto document = data ? lunasvg::Document::loadFromData(data, length) : nullptr; + if (!document) return {}; + auto bitmap = document->renderToBitmap(size.x, size.y, 0); + if (bitmap.width() == 0 || bitmap.height() == 0) return {}; + return Image(bitmap.data(), size, true); } } diff --git a/src/resource/texture.hpp b/src/resource/texture.hpp index 4bf9a2c..db98763 100644 --- a/src/resource/texture.hpp +++ b/src/resource/texture.hpp @@ -1,50 +1,13 @@ #pragma once -#include -#include -#include - #include -#include +#include "image.hpp" + +// GPU copies of Images, uploaded on first use and evicted when a frame passes without them being drawn. namespace anm2ed::resource::texture { - constexpr auto CHANNELS = 4; -} - -namespace anm2ed::resource -{ - class Texture - { - public: - GLuint id{}; - glm::ivec2 size{}; - GLint filter = GL_NEAREST; - int channels{}; - std::vector pixels{}; - - bool is_valid() const; - size_t pixel_size_get() const; - void release(); - void upload(); - void upload(const uint8_t*); - glm::vec4 pixel_read(glm::vec2) const; - - Texture(); - ~Texture(); - Texture(const Texture&); - Texture(Texture&&); - Texture& operator=(const Texture&); - Texture& operator=(Texture&&); - Texture(const uint8_t*, glm::ivec2); - Texture(const unsigned char*, size_t); - Texture(const char*, size_t, glm::ivec2); - Texture(const std::filesystem::path&); - bool write_png(const std::filesystem::path&); - static void garbage_collect(); - static bool write_pixels_png(const std::filesystem::path&, glm::ivec2, const uint8_t*); - static Texture merge_append(const Texture&, const Texture&, bool); - void pixel_set(glm::ivec2, glm::vec4); - void pixel_line(glm::ivec2, glm::ivec2, glm::vec4); - }; + GLuint id_get(const Image&); + void garbage_collect(); + Image svg_load(const char*, size_t, glm::ivec2); } diff --git a/src/resources.cpp b/src/resources.cpp index 58e5bfe..525aac0 100644 --- a/src/resources.cpp +++ b/src/resources.cpp @@ -43,21 +43,23 @@ namespace anm2ed } for (auto [i, iconInfo] : std::views::enumerate(icon::ICONS)) - icons[i] = Texture(iconInfo.data, iconInfo.length, iconInfo.size); + icons[i] = texture::svg_load(iconInfo.data, iconInfo.length, iconInfo.size); for (auto [i, shaderInfo] : std::views::enumerate(shader::SHADERS)) shaders[i] = Shader(shaderInfo.vertex, shaderInfo.fragment); }; - resource::Audio& Resources::music_track() + GLuint Resources::icon_id_get(int icon) { return texture::id_get(icons[icon]); } + + resource::AudioData& Resources::music_track() { if (!isMusicLoaded) { - music = Audio(music::ABOUT, std::size(music::ABOUT)); + music = AudioData(music::ABOUT, std::size(music::ABOUT)); isMusicLoaded = true; } return music; } - resource::Audio* Resources::music_track_if_loaded() { return isMusicLoaded ? &music : nullptr; } + resource::AudioData* Resources::music_track_if_loaded() { return isMusicLoaded ? &music : nullptr; } } diff --git a/src/resources.hpp b/src/resources.hpp index 8e9b20f..a9ae0d2 100644 --- a/src/resources.hpp +++ b/src/resources.hpp @@ -14,13 +14,14 @@ namespace anm2ed { public: resource::Font fonts[resource::font::COUNT]{}; - resource::Texture icons[resource::icon::COUNT]{}; + resource::Image icons[resource::icon::COUNT]{}; resource::Shader shaders[resource::shader::COUNT]{}; - resource::Audio music{}; + resource::AudioData music{}; Resources(); - resource::Audio& music_track(); - resource::Audio* music_track_if_loaded(); + GLuint icon_id_get(int); + resource::AudioData& music_track(); + resource::AudioData* music_track_if_loaded(); private: bool isMusicLoaded{false}; diff --git a/src/snapshots.cpp b/src/snapshots.cpp index 3e6f7d5..f298ef5 100644 --- a/src/snapshots.cpp +++ b/src/snapshots.cpp @@ -26,15 +26,15 @@ namespace anm2ed::snapshots left.references == right.references; } - bool is_texture_equal(const resource::Texture& left, const resource::Texture& right) + bool is_texture_equal(const resource::Image& left, const resource::Image& right) { - return left.size == right.size && left.filter == right.filter && left.channels == right.channels && - left.pixels == right.pixels; + return left.uid == right.uid || + (left.size == right.size && left.isLinear == right.isLinear && left.pixels == right.pixels); } - bool is_audio_equal(const resource::Audio& left, const resource::Audio& right) + bool is_audio_equal(const resource::AudioData& left, const resource::AudioData& right) { - return const_cast(left).is_valid() == const_cast(right).is_valid(); + return left.is_valid() == right.is_valid(); } template @@ -61,12 +61,12 @@ namespace anm2ed::snapshots bool is_value_equal(const Storage& left, const Storage& right) { return is_storage_equal(left, right); } - bool is_value_equal(const std::map& left, const std::map& right) + bool is_value_equal(const std::map& left, const std::map& right) { return is_map_equal(left, right, is_texture_equal); } - bool is_value_equal(const std::map& left, const std::map& right) + bool is_value_equal(const std::map& left, const std::map& right) { return is_map_equal(left, right, is_audio_equal); } diff --git a/src/snapshots.hpp b/src/snapshots.hpp index 8892927..1d0b002 100644 --- a/src/snapshots.hpp +++ b/src/snapshots.hpp @@ -7,10 +7,10 @@ #include #include "anm2/anm2.hpp" -#include "audio.hpp" +#include "audio_data.hpp" +#include "image.hpp" #include "playback.hpp" #include "storage.hpp" -#include "texture.hpp" namespace anm2ed::snapshots { @@ -63,8 +63,8 @@ namespace anm2ed Storage shader{}; Storage sound{}; Storage spritesheet{}; - std::map textures{}; - std::map sounds{}; + std::map textures{}; + std::map sounds{}; Anm2 anm2{}; Reference reference{}; std::set groupReferences{}; @@ -72,8 +72,8 @@ namespace anm2ed std::string message = snapshots::ACTION; }; - using SnapshotTextureMap = std::map; - using SnapshotSoundMap = std::map; + using SnapshotTextureMap = std::map; + using SnapshotSoundMap = std::map; #define SNAPSHOT_STEP_STATE_FIELDS \ X(Playback, playback) \ diff --git a/src/state.cpp b/src/state.cpp index 461d0fa..3e2712a 100644 --- a/src/state.cpp +++ b/src/state.cpp @@ -208,7 +208,7 @@ namespace anm2ed ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); SDL_GL_SwapWindow(window); - resource::Texture::garbage_collect(); + resource::texture::garbage_collect(); SDL_GL_SetSwapInterval(settings.isVsync); } diff --git a/src/util/uid.hpp b/src/util/uid.hpp new file mode 100644 index 0000000..1c18cc7 --- /dev/null +++ b/src/util/uid.hpp @@ -0,0 +1,14 @@ +#pragma once + +#include +#include + +namespace anm2ed::util +{ + // Process-unique, never reused; 0 means "none". + inline std::uint64_t uid_next() + { + static std::atomic next{1}; + return next++; + } +} diff --git a/tests/assets.cpp b/tests/assets.cpp new file mode 100644 index 0000000..eb7dbf8 --- /dev/null +++ b/tests/assets.cpp @@ -0,0 +1,41 @@ +#include "common.hpp" + +#include "audio_data.hpp" +#include "image.hpp" + +using namespace anm2ed; +using namespace anm2ed::resource; + +TEST_CASE("Image png round trip and uid tracking") +{ + const std::vector pixels{255, 0, 0, 255, 0, 255, 0, 128, 0, 0, 255, 0, 10, 20, 30, 40}; + Image image(pixels.data(), {2, 2}); + REQUIRE(image.is_valid()); + + auto path = std::filesystem::temp_directory_path() / "anm2ed_test_image.png"; + REQUIRE(image.write_png(path)); + Image loaded(path); + std::filesystem::remove(path); + CHECK(loaded.size == image.size); + CHECK(loaded.pixels == image.pixels); + CHECK(loaded.uid != image.uid); + + auto copy = image; + CHECK(copy.uid == image.uid); + copy.pixel_set({1, 1}, {1.0f, 1.0f, 1.0f, 1.0f}); + CHECK(copy.uid != image.uid); + CHECK(copy.pixel_read({1, 1}) == glm::vec4(1.0f)); + + auto merged = Image::merge_append(image, loaded, true); + CHECK(merged.size == glm::ivec2(4, 2)); + CHECK(merged.pixel_read({2, 0}) == image.pixel_read({0, 0})); +} + +TEST_CASE("AudioData holds file bytes") +{ + const unsigned char bytes[] = {'R', 'I', 'F', 'F'}; + AudioData audio(bytes, sizeof(bytes)); + CHECK(audio.is_valid()); + CHECK(audio.uid != 0); + CHECK_FALSE(AudioData(std::filesystem::path("missing.wav")).is_valid()); +}