main.cpp 13 KB

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