Something went wrong. Try again.
art software for the rest of us
drawing paint image sdl art
Something went wrong. Try again.
C++
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341#include "Resources.h"#include "App.h"#include <SDL3/SDL_log.h>#include <SDL3/SDL_video.h>#include <cstdlib>#include <iostream>#include <memory>#include <sys/resource.h>#include "Tools/Tool.h" #include "Version.h"#include "UserInterface/Primitives.h"#include "GPU.h"#include "AppLayers/ScreenLayer.h"
App::App(int argc, char* argv[]) { // PARAMS for (int i = 0; i < argc; i++) { std::printf("%s ", argv[i]); } std::cout << "\n"; std::printf("%s ver.%d.%d.%d (%s)\n", APP_NAME, APP_VERSION_MAJOR, APP_VERSION_MINOR, APP_VERSION_PATCH, APP_VERSION_LEVEL); execName = argv[0]; std::string projectPath = "untitled.grdn"; for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "--test") == 0) { testMode = true; std::printf("Running in test/automated mode\n"); } if (strcmp(argv[i], "--memcheck") == 0) { memCheck = true; } if (strcmp(argv[i], "--help") == 0) { std::printf("Usage: %s [options] [project]\n", argv[0]); std::printf("Options:\n"); std::printf(" --test Run in test/automated mode\n"); std::printf(" --memcheck Enable memory quota check\n"); std::printf(" --help Show this help message\n"); std::printf("Environment variables:\n"); std::printf(" GRADIEN_GPU_DEBUG Enable GPU validation layers (1 = true, 0 = false)\n"); std::printf(" GRADIEN_FRAMETIME Show frametime (1 = true, 0 = false)\n"); std::exit(0); } } bootTime = SDL_GetTicksNS(); // SDL INIT if (!SDL_Init(SDL_INIT_VIDEO)) { std::printf("SDL Initialization failed\n"); std::exit(1); }
// Hints SDL_SetHintWithPriority(SDL_HINT_PEN_TOUCH_EVENTS, "0", SDL_HINT_OVERRIDE);
Resources::Init();
window = SDL_CreateWindow("Gradien", 800, 600, SDL_WINDOW_RESIZABLE | SDL_WINDOW_VULKAN | SDL_WINDOW_HIGH_PIXEL_DENSITY);
if (!window) { std::printf("Window creation failed: %s\n", SDL_GetError()); SDL_Quit(); std::exit(1); }
if (!GPU::Init()) { const char* err = SDL_GetError(); std::printf("Graphics device creation failed: %s\n", err ? err : "Unknown Error"); std::string errorMessagegGPU = "Failed to start the app because the graphics device is not usable, Details: " + (std::string)(err ? err : "Result from SDL_GetError() unavailable") + " Device information: " + GPU::GetDetails() + " The Application will now close."; SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", errorMessagegGPU.c_str(), window); SDL_Quit(); std::exit(1); }
if (!GPU::ClaimWindow(window)) { std::printf("Window claim failed: %s\n", SDL_GetError()); SDL_Quit(); std::exit(1); }
// INPUT input = new InputHandler();
History = new HistoryManager(); AppLayer::SetHistory(History); Tool::SetHistory(History);
initLayers(); initPanels();}
void App::activateLayers(std::vector<std::shared_ptr<AppLayer>> layers) { for (auto& layer : layers) { layer->OnActivate(); }}
void App::deactivateLayers(std::vector<std::shared_ptr<AppLayer>> layers) { for (auto& layer : layers) { layer->OnDeactivate(); }}
bool App::areAllLayersActive(std::vector<std::shared_ptr<AppLayer>> layers) { for (auto& layer : layers) { if (!layer->IsActive()) { return false; } } return true;}
#include "AppLayers/CanvasLayer.h"#include "AppLayers/ToolbarLayer.h"#include "AppLayers/NotifyLayer.h"#include "AppLayers/ProjectsLayer.h"#include "AppLayers/ScreenLayer.h"#include "Screens/TitleScreen.h"#include <unistd.h>
void App::initLayers() { auto canvasLayer = std::make_shared<CanvasAppLayer>(); auto toolbarLayer = std::make_shared<ToolbarAppLayer>(); auto notifyLayer = std::make_shared<NotifyAppLayer>(); auto projectsLayer = std::make_shared<ProjectsAppLayer>(); // this can be replaced by a screenlayer auto screenLayer = std::make_shared<ScreenLayer>();
layers.push_back(notifyLayer); layers.push_back(canvasLayer); layers.push_back(toolbarLayer); layers.push_back(projectsLayer); layers.push_back(screenLayer);
projectsLayers.push_back(projectsLayer); editorLayers.push_back(canvasLayer); editorLayers.push_back(toolbarLayer);
activateLayers(projectsLayers); screenLayer->OpenScreen(std::make_unique<TitleScreen>()); screenLayer->OnActivate();
Tool::SetColor(0.0f, 0.0f, 0.0f);
input->RegisterOnDown(screenLayer); input->RegisterOnDown(canvasLayer); notifyLayer->SetMessage("Welcome to Gradien!");
}
void App::initPanels(){ panelContext = new PanelManagementContext();}
App::~App() { //TTF_Quit(); delete panelContext; UI::Primitives::ClearResources(); delete input; delete History; GPU::Shutdown(); SDL_DestroyWindow(window); SDL_Quit();}
void App::Run() {
bootTime = SDL_GetTicksNS() - bootTime; std::printf("Init in %lu ns (%.3f s)\n", bootTime, (double)(bootTime) / 1.0E9); bootTime = SDL_GetTicksNS(); int counter = 0;
const char* frametimeEnv = std::getenv("GRADIEN_FRAMETIME"); bool frametime = (frametimeEnv != nullptr && std::string(frametimeEnv) == "1"); long lastTicks = frametime ? SDL_GetTicksNS() : 0; long overlayTicks = lastTicks; long logTicks = lastTicks; long frameTimeNanos = 0; int measuredFrames = 0; int overlayFrames = 0; ScreenLayer::SetDebugVisible(frametime);
bool running = true; SDL_Event event;
while (running) { // switch layers (ts lowk sucks, TODO: figure out a better way to handle screens, we'll need this eventually) // this will be solved by screens in its update loop if (CurrentArtwork && areAllLayersActive(projectsLayers)) { History->Clear(); deactivateLayers(projectsLayers); activateLayers(editorLayers); } else if (!CurrentArtwork && areAllLayersActive(editorLayers)) { History->Clear(); deactivateLayers(editorLayers); activateLayers(projectsLayers); PanelManagementContext::CloseAll(); }
// Parse SDL Events while (SDL_PollEvent(&event)) { if (input->OnSDLEvent(event)) { continue; } switch (event.type) { case SDL_EVENT_WINDOW_RESIZED: break; case SDL_EVENT_QUIT: running = false; break; default: break; } } counter++;
SDL_GetWindowSizeInPixels(GPU::GetWindow(), &Width, &Height); if (!GPU::WaitAquireSwapchainWithCommandBuffer()) { std::printf("Swapchain aquire failed: %s\n", SDL_GetError()); SDL_Quit(); std::exit(1); }
UI::Primitives::BeginFrame();
if (input->IsKeyHeld(SDLK_LCTRL)) { if (input->IsKeyDown(SDLK_Z)) { History->Undo(); } if (input->IsKeyDown(SDLK_Y)) { History->Redo(); } if (input->IsKeyDown(SDLK_S)) { CurrentArtwork->SaveProject(); NotifyAppLayer::SetMessage("Saved!"); } }
SDL_GPUColorTargetInfo color_target_info; SDL_zero(color_target_info); color_target_info.texture = GPU::GetSwapchain(); // this should be controlled by the ui subsystem color_target_info.clear_color.r = 1.0f; color_target_info.clear_color.g = 1.0f; color_target_info.clear_color.b = 1.0f; color_target_info.clear_color.a = 1.0f; color_target_info.load_op = SDL_GPU_LOADOP_CLEAR; color_target_info.store_op = SDL_GPU_STOREOP_STORE;
GPU::BeginRendering({ &color_target_info }, nullptr);
GPU::EndRendering();
for (auto& layer : layers) { if (layer->IsActive()) { layer->OnRender(); } }
if (PanelManagementContext::GetMode() == PanelManagementMode::DEFAULT && Tool::GetActive()) { Tool::GetActive()->OnGuiRender(); }
panelContext->OnRender();
if (memCheck) { const int limitMB = 300; // mb long pages = 0; FILE* f = fopen("/proc/self/statm", "r"); if (f) { long dummy; fscanf(f, "%ld %ld", &dummy, &pages); // field 2 = resident pages fclose(f); } long int kbytes = pages * sysconf(_SC_PAGESIZE) / 1024;
if (!(counter % 36)) { // every approx quarter second std::printf("Memory usage: %ld kB (%ld MB)\n", kbytes, kbytes / 1024); if (kbytes >= (limitMB * 1024)) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "High memory usage", "Memory usage is higher than expected and may indicate memory leaks are still present, check logs and refactor until this no longer occurs.", nullptr); running = false; } } }
UI::Primitives::EndFrame();
GPU::SubmitCommandsPopCommandBuffer();
const int testFrameLimit = 143 * 3; // at least 143 fps to be considered decent, even with vsync 144 if (testMode && ((counter > testFrameLimit) || (SDL_GetTicksNS() - bootTime > 1.0E9 * 3))) { // give approx 3 seconds for input bootTime = SDL_GetTicksNS() - bootTime; std::printf("Test mode average FPS: %.2f, Duration: %.0f ms, %s\n", (double)(counter * 1.0E9) / bootTime, (double)bootTime / 1.0E6, (bootTime / 1.0E6) >= 3000 ? "Late or VSync" : "Early or Unlocked"); running = false; }
if (lastTicks != 0) { long currentTicks = SDL_GetTicksNS(); long deltaTicks = currentTicks - lastTicks; lastTicks = currentTicks; frameTimeNanos += deltaTicks; measuredFrames++; overlayFrames++;
if (currentTicks - overlayTicks >= 0.5E9) { const double elapsedSeconds = static_cast<double>(currentTicks - overlayTicks) / 1.0E9; ScreenLayer::SetFps(static_cast<double>(overlayFrames) / elapsedSeconds); overlayTicks = currentTicks; overlayFrames = 0; }
if (currentTicks - logTicks >= 1.0E9) { const double averageFrameTime = static_cast<double>(frameTimeNanos) / measuredFrames / 1.0E6; std::printf("Frame time: %.3f ms\n", averageFrameTime); logTicks = currentTicks; frameTimeNanos = 0; measuredFrames = 0; } } }
// exit if (CurrentArtwork) { CurrentArtwork->SaveProject(); }}
int App::Width = 800;int App::Height = 600;HistoryManager* App::History = nullptr;Artwork* App::CurrentArtwork = nullptr;