main.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. #include <iostream>
  2. #include <getopt.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <SDL_mixer.h>
  6. #include <SDL.h>
  7. #include <FreeImage.h>
  8. #include <sys/stat.h>
  9. #include <GL/glew.h>
  10. #include <csignal>
  11. #include <GLFW/glfw3.h>
  12. #include <libgen.h>
  13. #include "WallpaperEngine/Core/CProject.h"
  14. #include "WallpaperEngine/Render/CWallpaper.h"
  15. #include "WallpaperEngine/Render/CContext.h"
  16. #include "WallpaperEngine/Assets/CPackage.h"
  17. #include "WallpaperEngine/Assets/CDirectory.h"
  18. #include "WallpaperEngine/Assets/CCombinedContainer.h"
  19. #include "WallpaperEngine/Assets/CPackageLoadException.h"
  20. float g_Time;
  21. bool g_KeepRunning = true;
  22. using namespace WallpaperEngine::Core::Types;
  23. const char* default_paths[] = {
  24. ".steam/steam/steamapps/common/wallpaper_engine/assets",
  25. ".local/share/Steam/steamapps/common/wallpaper_engine/assets",
  26. nullptr
  27. };
  28. void print_help (const char* route)
  29. {
  30. std::cout
  31. << "Usage:" << route << " [options] background_path" << std::endl
  32. << "options:" << std::endl
  33. << " --silent\t\tMutes all the sound the wallpaper might produce" << std::endl
  34. << " --screen-root <screen name>\tDisplay as screen's background" << std::endl
  35. << " --fps <maximum-fps>\tLimits the FPS to the given number, useful to keep battery consumption low" << std::endl
  36. << " --assets-dir <path>\tFolder where the assets are stored" << std::endl;
  37. }
  38. std::string stringPathFixes(const std::string& s)
  39. {
  40. if (s.empty () == true)
  41. return s;
  42. std::string str (s);
  43. // remove single-quotes from the arguments
  44. if (str [0] == '\'' && str [str.size() - 1] == '\'')
  45. str
  46. .erase (str.size() - 1, 1)
  47. .erase (0, 1);
  48. // ensure there's a slash at the end of the path
  49. if (str [str.size() - 1] != '/')
  50. str += '/';
  51. return std::move (str);
  52. }
  53. void signalhandler(int sig)
  54. {
  55. g_KeepRunning = false;
  56. }
  57. int validatePath(const char* path, std::string& final)
  58. {
  59. char finalPath [PATH_MAX];
  60. char* pointer = realpath (path, finalPath);
  61. if (finalPath == nullptr)
  62. return errno;
  63. // ensure the path points to a folder
  64. struct stat pathinfo;
  65. if (stat (finalPath, &pathinfo) != 0)
  66. return errno;
  67. if (!S_ISDIR (pathinfo.st_mode))
  68. return ENOTDIR;
  69. final = finalPath;
  70. return 0;
  71. }
  72. int main (int argc, char* argv[])
  73. {
  74. std::vector <std::string> screens;
  75. int maximumFPS = 30;
  76. bool shouldEnableAudio = true;
  77. std::string path;
  78. std::string assetsDir;
  79. static struct option long_options [] = {
  80. {"screen-root", required_argument, 0, 'r'},
  81. {"pkg", required_argument, 0, 'p'},
  82. {"dir", required_argument, 0, 'd'},
  83. {"silent", no_argument, 0, 's'},
  84. {"help", no_argument, 0, 'h'},
  85. {"fps", required_argument, 0, 'f'},
  86. {"assets-dir", required_argument, 0, 'a'},
  87. {nullptr, 0, 0, 0}
  88. };
  89. while (true)
  90. {
  91. int c = getopt_long (argc, argv, "r:p:d:shf:a:", long_options, nullptr);
  92. if (c == -1)
  93. break;
  94. switch (c)
  95. {
  96. case 'r':
  97. screens.emplace_back (optarg);
  98. break;
  99. case 'p':
  100. case 'd':
  101. std::cerr << "--dir/--pkg is deprecated and not used anymore" << std::endl;
  102. path = stringPathFixes (optarg);
  103. break;
  104. case 's':
  105. shouldEnableAudio = false;
  106. break;
  107. case 'h':
  108. print_help (argv [0]);
  109. break;
  110. case 'f':
  111. maximumFPS = atoi (optarg);
  112. break;
  113. case 'a':
  114. assetsDir = optarg;
  115. break;
  116. }
  117. }
  118. if (path.empty () == true)
  119. {
  120. if (optind < argc && strlen (argv [optind]) > 0)
  121. {
  122. path = argv [optind];
  123. }
  124. else
  125. {
  126. print_help (argv [0]);
  127. return 0;
  128. }
  129. }
  130. int error = validatePath (path.c_str (), path);
  131. if (error == ENOTDIR)
  132. throw std::runtime_error ("The background path is not a folder");
  133. else if (error == ENAMETOOLONG)
  134. throw std::runtime_error ("Cannot get wallpaper's folder, path is too long");
  135. else if (error != 0)
  136. throw std::runtime_error ("Cannot find the specified folder");
  137. // ensure the path has a trailing slash
  138. // attach signals so if a stop is requested the X11 resources are freed and the program shutsdown gracefully
  139. std::signal(SIGINT, signalhandler);
  140. std::signal(SIGTERM, signalhandler);
  141. // first of all, initialize the window
  142. if (glfwInit () == GLFW_FALSE)
  143. {
  144. fprintf (stderr, "Failed to initialize GLFW\n");
  145. return 1;
  146. }
  147. // initialize freeimage
  148. FreeImage_Initialise (TRUE);
  149. // set some window hints (opengl version to be used)
  150. glfwWindowHint (GLFW_SAMPLES, 4);
  151. glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 2);
  152. glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 1);
  153. auto containers = new WallpaperEngine::Assets::CCombinedContainer ();
  154. // update the used path with the full one
  155. path += "/";
  156. // the background's path is required to load project.json regardless of the type of background we're using
  157. containers->add (new WallpaperEngine::Assets::CDirectory (path));
  158. // check if scene.pkg exists and add it to the list
  159. try
  160. {
  161. std::string scene_path = path + "scene.pkg";
  162. // add the package to the list
  163. containers->add (new WallpaperEngine::Assets::CPackage (scene_path));
  164. std::cout << "Detected scene.pkg file at " << scene_path << ". Adding to list of searchable paths" << std::endl;
  165. }
  166. catch (CPackageLoadException ex)
  167. {
  168. // ignore this error, the package file was not found
  169. std::cout << "No scene.pkg file found at " << path << ". Defaulting to normal folder storage" << std::endl;
  170. }
  171. catch (std::runtime_error ex)
  172. {
  173. // the package was found but there was an error loading it (wrong header or something)
  174. fprintf (stderr, "Failed to load scene.pkg file: %s\n", ex.what());
  175. return 4;
  176. }
  177. if (assetsDir == "")
  178. {
  179. char* home = getenv ("HOME");
  180. if (home == nullptr)
  181. throw std::runtime_error ("$HOME doesn't exist");
  182. std::string homepath = "";
  183. error = validatePath (home, homepath);
  184. if (error == ENOTDIR)
  185. throw std::runtime_error ("Invalid user home path");
  186. else if (error == ENAMETOOLONG)
  187. throw std::runtime_error ("Cannot get user's home folder, path is too long");
  188. else if (error != 0)
  189. throw std::runtime_error ("Cannot find the home folder for the user");
  190. for (const char** current = default_paths; *current != nullptr; current ++)
  191. {
  192. std::string tmppath = homepath + "/" + *current;
  193. error = validatePath (tmppath.c_str (), tmppath);
  194. if (error != 0)
  195. continue;
  196. assetsDir = tmppath;
  197. std::cout << "Found wallpaper engine's assets at " << assetsDir << std::endl;
  198. break;
  199. }
  200. if (assetsDir == "")
  201. {
  202. int len = strlen (argv [0]) + 1;
  203. char* copy = new char[len];
  204. strncpy (copy, argv [0], len);
  205. // path still not found, try one last thing on the current binarie's folder
  206. std::string exepath = dirname (copy);
  207. exepath += "/assets";
  208. error = validatePath (exepath.c_str (), exepath);
  209. if (error == 0)
  210. {
  211. assetsDir = exepath;
  212. std::cout << "Found assets folder alongside the binary: " << assetsDir << std::endl;
  213. }
  214. delete copy;
  215. }
  216. }
  217. else
  218. {
  219. error = validatePath (assetsDir.c_str (), assetsDir);
  220. if (error == ENOTDIR)
  221. throw std::runtime_error ("Invalid assets folder");
  222. else if (error == ENAMETOOLONG)
  223. throw std::runtime_error ("Cannot get assets folder, path is too long");
  224. else if (error != 0)
  225. throw std::runtime_error ("Cannot find the specified assets folder");
  226. std::cout << "Found wallpaper engine's assets at " << assetsDir << " based on --assets-dir parameter" << std::endl;
  227. }
  228. if (assetsDir == "")
  229. throw std::runtime_error ("Cannot determine a valid path for the wallpaper engine assets");
  230. // add containers to the list
  231. containers->add (new WallpaperEngine::Assets::CDirectory (assetsDir + "/"));
  232. // auto projection = project->getWallpaper ()->as <WallpaperEngine::Core::CScene> ()->getOrthogonalProjection ();
  233. // create the window!
  234. // TODO: DO WE NEED TO PASS MONITOR HERE OR ANYTHING?
  235. // TODO: FIGURE OUT HOW TO PUT THIS WINDOW IN THE BACKGROUND
  236. GLFWwindow* window = glfwCreateWindow (1920, 1080, "WallpaperEngine", NULL, NULL);
  237. if (window == nullptr)
  238. {
  239. fprintf (stderr, "Failed to open a GLFW window");
  240. glfwTerminate ();
  241. return 2;
  242. }
  243. glfwMakeContextCurrent (window);
  244. // TODO: FIGURE THESE OUT BASED ON THE SCREEN
  245. int windowWidth = 1920;
  246. int windowHeight = 1080;
  247. // get the real framebuffer size
  248. glfwGetFramebufferSize (window, &windowWidth, &windowHeight);
  249. // initialize glew
  250. if (glewInit () != GLEW_OK)
  251. {
  252. fprintf (stderr, "Failed to initialize GLEW");
  253. glfwTerminate ();
  254. return 3;
  255. }
  256. // parse the project.json file
  257. auto project = WallpaperEngine::Core::CProject::fromFile ("project.json", containers);
  258. // go to the right folder so the videos will play
  259. if (project->getWallpaper ()->is <WallpaperEngine::Core::CVideo> () == true)
  260. chdir (path.c_str ());
  261. // initialize custom context class
  262. WallpaperEngine::Render::CContext* context = new WallpaperEngine::Render::CContext (screens, window);
  263. // initialize mouse support
  264. context->setMouse (new CMouseInput (window));
  265. // set the default viewport
  266. context->setDefaultViewport ({0, 0, windowWidth, windowHeight});
  267. // ensure the context knows what wallpaper to render
  268. context->setWallpaper (
  269. WallpaperEngine::Render::CWallpaper::fromWallpaper (project->getWallpaper (), containers, context)
  270. );
  271. if (shouldEnableAudio == true)
  272. {
  273. int mixer_flags = MIX_INIT_MP3 | MIX_INIT_FLAC | MIX_INIT_OGG;
  274. if (SDL_Init (SDL_INIT_AUDIO) < 0 || mixer_flags != Mix_Init (mixer_flags))
  275. {
  276. // Mix_GetError is an alias for SDL_GetError, so calling it directly will yield the correct result
  277. // it doesn't matter if SDL_Init or Mix_Init failed, both report the errors through the same functions
  278. std::cerr << "Cannot initialize SDL audio system, SDL_GetError: " << SDL_GetError() << std::endl;
  279. std::cerr << "Continuing without audio support" << std::endl;
  280. shouldEnableAudio = false;
  281. }
  282. // initialize audio engine if it should be
  283. if (shouldEnableAudio)
  284. Mix_OpenAudio (22050, AUDIO_S16SYS, 2, 640);
  285. }
  286. // TODO: FIGURE OUT THE REQUIRED INPUT MODE, AS SOME WALLPAPERS USE THINGS LIKE MOUSE POSITION
  287. // glfwSetInputMode (window, GLFW_STICKY_KEYS, GL_TRUE);
  288. double startTime, endTime, minimumTime = 1.0 / maximumFPS;
  289. while (glfwWindowShouldClose (window) == 0 && g_KeepRunning == true)
  290. {
  291. // get the real framebuffer size
  292. glfwGetFramebufferSize (window, &windowWidth, &windowHeight);
  293. // set the default viewport
  294. context->setDefaultViewport ({0, 0, windowWidth, windowHeight});
  295. // calculate the current time value
  296. g_Time = (float) glfwGetTime ();
  297. // get the start time of the frame
  298. startTime = glfwGetTime ();
  299. // render the scene
  300. context->render ();
  301. // do buffer swapping
  302. glfwSwapBuffers (window);
  303. // poll for events (like closing the window)
  304. glfwPollEvents ();
  305. // get the end time of the frame
  306. endTime = glfwGetTime ();
  307. // ensure the frame time is correct to not overrun FPS
  308. if ((endTime - startTime) < minimumTime)
  309. usleep ((minimumTime - (endTime - startTime)) * CLOCKS_PER_SEC);
  310. }
  311. // free context
  312. delete context;
  313. // terminate gl
  314. glfwTerminate ();
  315. // terminate SDL
  316. SDL_Quit ();
  317. // terminate free image
  318. FreeImage_DeInitialise ();
  319. return 0;
  320. }