main.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. #include <iostream>
  2. #include <getopt.h>
  3. #include <unistd.h>
  4. #include <SDL_mixer.h>
  5. #include <SDL.h>
  6. #include <FreeImage.h>
  7. #include <sys/stat.h>
  8. #include <GL/glew.h>
  9. #include <GL/glx.h>
  10. #include <filesystem>
  11. #include <csignal>
  12. #include <GLFW/glfw3.h>
  13. #include <X11/Xlib.h>
  14. #include <X11/Xatom.h>
  15. #include "WallpaperEngine/Core/CProject.h"
  16. #include "WallpaperEngine/Render/CWallpaper.h"
  17. #include "WallpaperEngine/Render/CContext.h"
  18. #include "WallpaperEngine/Render/CScene.h"
  19. #include "WallpaperEngine/Render/CVideo.h"
  20. #include "WallpaperEngine/Assets/CPackage.h"
  21. #include "WallpaperEngine/Assets/CDirectory.h"
  22. #include "WallpaperEngine/Assets/CCombinedContainer.h"
  23. float g_Time;
  24. using namespace WallpaperEngine::Core::Types;
  25. void print_help (const char* route)
  26. {
  27. std::cout
  28. << "Usage:" << route << " [options] background_path" << std::endl
  29. << "options:" << std::endl
  30. << " --silent\t\tMutes all the sound the wallpaper might produce" << std::endl
  31. << " --screen-root <screen name>\tDisplay as screen's background" << std::endl
  32. << " --fps <maximum-fps>\tLimits the FPS to the given number, useful to keep battery consumption low" << std::endl;
  33. }
  34. std::string stringPathFixes(const std::string& s)
  35. {
  36. if (s.empty () == true)
  37. return s;
  38. std::string str (s);
  39. // remove single-quotes from the arguments
  40. if (str [0] == '\'' && str [str.size() - 1] == '\'')
  41. str
  42. .erase (str.size() - 1, 1)
  43. .erase (0, 1);
  44. // ensure there's a slash at the end of the path
  45. if (str [str.size() - 1] != '/')
  46. str += '/';
  47. return std::move (str);
  48. }
  49. void free_display_wallpaper(int sig)
  50. {
  51. Display* display = XOpenDisplay (nullptr);
  52. Window root = DefaultRootWindow(display);
  53. // create a blank pm to reset compositors values, compositors will render as a blank X window.
  54. Pixmap pm = XCreatePixmap(display, root, 1, 1, 1);
  55. Atom prop_root = XInternAtom(display, "_XROOTPMAP_ID", False);
  56. Atom prop_esetroot = XInternAtom(display, "ESETROOT_PMAP_ID", False);
  57. XChangeProperty(display, root, prop_root, XA_PIXMAP, 32, PropModeReplace, (unsigned char *) &pm, 1);
  58. XChangeProperty(display, root, prop_esetroot, XA_PIXMAP, 32, PropModeReplace, (unsigned char *) &pm, 1);
  59. XFreePixmap(display, pm);
  60. // set background to black. Only needed if no compositors are running
  61. XSetWindowBackground(display, root, 0);
  62. // sync changes before exiting
  63. XClearWindow(display, root);
  64. XFlush(display);
  65. XCloseDisplay(display);
  66. exit(sig);
  67. }
  68. int main (int argc, char* argv[])
  69. {
  70. std::vector <std::string> screens;
  71. int maximumFPS = 30;
  72. bool shouldEnableAudio = true;
  73. std::string path;
  74. static struct option long_options [] = {
  75. {"screen-root", required_argument, 0, 'r'},
  76. {"pkg", required_argument, 0, 'p'},
  77. {"dir", required_argument, 0, 'd'},
  78. {"silent", no_argument, 0, 's'},
  79. {"help", no_argument, 0, 'h'},
  80. {"fps", required_argument, 0, 'f'},
  81. {nullptr, 0, 0, 0}
  82. };
  83. while (true)
  84. {
  85. int c = getopt_long (argc, argv, "r:p:d:shf:", long_options, nullptr);
  86. if (c == -1)
  87. break;
  88. switch (c)
  89. {
  90. case 'r':
  91. screens.emplace_back (optarg);
  92. break;
  93. case 'p':
  94. case 'd':
  95. std::cerr << "--dir/--pkg is deprecated and not used anymore" << std::endl;
  96. path = stringPathFixes (optarg);
  97. break;
  98. case 's':
  99. shouldEnableAudio = false;
  100. break;
  101. case 'h':
  102. print_help (argv [0]);
  103. break;
  104. case 'f':
  105. maximumFPS = atoi (optarg);
  106. break;
  107. default:
  108. break;
  109. }
  110. }
  111. // increment the option index (useful for when no options were found)
  112. // option_index ++;
  113. if (path.empty () == true)
  114. {
  115. if (optind < argc && strlen (argv [optind]) > 0)
  116. {
  117. path = argv [optind];
  118. }
  119. else
  120. {
  121. print_help (argv [0]);
  122. return 0;
  123. }
  124. }
  125. char* finalPath = realpath(path.c_str (), nullptr);
  126. if (finalPath == nullptr)
  127. {
  128. if (errno == ENAMETOOLONG)
  129. throw std::runtime_error ("Cannot get wallpaper's folder, path is too long");
  130. else
  131. throw std::runtime_error ("Cannot find the specified folder");
  132. }
  133. // ensure the path points to a folder
  134. struct stat pathinfo;
  135. if (stat (finalPath, &pathinfo) != 0)
  136. throw std::runtime_error ("Cannot find the specified wallpaper folder");
  137. if (!S_ISDIR (pathinfo.st_mode))
  138. throw std::runtime_error ("The specified path is not a folder");
  139. // ensure the path has a trailing slash
  140. // Attach signals for unexpected killing of program by user. We need to reset the
  141. // screen otherwise the background will remain the last frame on sigterm or sigint.
  142. if (!screens.empty())
  143. {
  144. std::signal(SIGINT, free_display_wallpaper);
  145. std::signal(SIGTERM, free_display_wallpaper);
  146. }
  147. // first of all, initialize the window
  148. if (glfwInit () == GLFW_FALSE)
  149. {
  150. fprintf (stderr, "Failed to initialize GLFW\n");
  151. return 1;
  152. }
  153. // initialize freeimage
  154. FreeImage_Initialise (TRUE);
  155. // set some window hints (opengl version to be used)
  156. glfwWindowHint (GLFW_SAMPLES, 4);
  157. glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 2);
  158. glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 1);
  159. // will hide the window if we are drawing to X
  160. if (!screens.empty())
  161. glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
  162. auto containers = new WallpaperEngine::Assets::CCombinedContainer ();
  163. // update the used path with the full one
  164. path = finalPath;
  165. path += "/";
  166. // the background's path is required to load project.json regardless of the type of background we're using
  167. containers->add (new WallpaperEngine::Assets::CDirectory (path));
  168. // check if scene.pkg exists and add it to the list
  169. try
  170. {
  171. std::string scene_path = path + "scene.pkg";
  172. // add the package to the list
  173. containers->add (new WallpaperEngine::Assets::CPackage (scene_path));
  174. std::cout << "Detected scene.pkg file at " << scene_path << ". Adding to list of searchable paths" << std::endl;
  175. }
  176. catch(std::filesystem::filesystem_error ex)
  177. {
  178. // ignore this error, the package file was not found
  179. std::cout << "No scene.pkg file found at " << path << ". Defaulting to normal folder storage" << std::endl;
  180. }
  181. catch (std::runtime_error ex)
  182. {
  183. // the package was found but there was an error loading it (wrong header or something)
  184. fprintf (stderr, "Failed to load scene.pkg file: %s\n", ex.what());
  185. return 4;
  186. }
  187. // add containers to the list
  188. containers->add (new WallpaperEngine::Assets::CDirectory ("./assets/"));
  189. // parse the project.json file
  190. auto project = WallpaperEngine::Core::CProject::fromFile ("project.json", containers);
  191. WallpaperEngine::Render::CWallpaper* wallpaper;
  192. // auto projection = project->getWallpaper ()->as <WallpaperEngine::Core::CScene> ()->getOrthogonalProjection ();
  193. // create the window!
  194. // TODO: DO WE NEED TO PASS MONITOR HERE OR ANYTHING?
  195. // TODO: FIGURE OUT HOW TO PUT THIS WINDOW IN THE BACKGROUND
  196. GLFWwindow* window = glfwCreateWindow (1920, 1080, "WallpaperEngine", NULL, NULL);
  197. if (window == nullptr)
  198. {
  199. fprintf (stderr, "Failed to open a GLFW window");
  200. glfwTerminate ();
  201. return 2;
  202. }
  203. // initialize inputs
  204. CMouseInput* mouseInput = new CMouseInput (window);
  205. glfwMakeContextCurrent (window);
  206. // TODO: FIGURE THESE OUT BASED ON THE SCREEN
  207. int windowWidth = 1920;
  208. int windowHeight = 1080;
  209. // get the real framebuffer size
  210. glfwGetFramebufferSize (window, &windowWidth, &windowHeight);
  211. // initialize glew
  212. if (glewInit () != GLEW_OK)
  213. {
  214. fprintf (stderr, "Failed to initialize GLEW");
  215. glfwTerminate ();
  216. return 3;
  217. }
  218. // initialize custom context class
  219. WallpaperEngine::Render::CContext* context = new WallpaperEngine::Render::CContext (screens);
  220. // initialize mouse support
  221. context->setMouse (mouseInput);
  222. // set the default viewport
  223. context->setDefaultViewport ({0, 0, windowWidth, windowHeight});
  224. if (project->getType () == "scene")
  225. {
  226. WallpaperEngine::Core::CScene* scene = project->getWallpaper ()->as <WallpaperEngine::Core::CScene> ();
  227. wallpaper = new WallpaperEngine::Render::CScene (scene, containers, context);
  228. }
  229. else if (project->getType () == "video")
  230. {
  231. // special steps, running a video needs a root directory change, files are not loaded from the container classes
  232. // as they're streamed from disk
  233. chdir (path.c_str ());
  234. WallpaperEngine::Core::CVideo* video = project->getWallpaper ()->as <WallpaperEngine::Core::CVideo> ();
  235. wallpaper = new WallpaperEngine::Render::CVideo (video, containers, context);
  236. }
  237. else
  238. {
  239. throw std::runtime_error ("Unsupported wallpaper type");
  240. }
  241. // ensure the context knows what wallpaper to render
  242. context->setWallpaper (wallpaper);
  243. if (shouldEnableAudio == true)
  244. {
  245. int mixer_flags = MIX_INIT_MP3 | MIX_INIT_FLAC | MIX_INIT_OGG;
  246. if (SDL_Init (SDL_INIT_AUDIO) < 0 || mixer_flags != Mix_Init (mixer_flags))
  247. {
  248. // Mix_GetError is an alias for SDL_GetError, so calling it directly will yield the correct result
  249. // it doesn't matter if SDL_Init or Mix_Init failed, both report the errors through the same functions
  250. fprintf (stderr, "Cannot initialize SDL audio system, SDL_GetError: %s", SDL_GetError ());
  251. return 2;
  252. }
  253. // initialize audio engine
  254. Mix_OpenAudio (22050, AUDIO_S16SYS, 2, 640);
  255. }
  256. // TODO: FIGURE OUT THE REQUIRED INPUT MODE, AS SOME WALLPAPERS USE THINGS LIKE MOUSE POSITION
  257. // glfwSetInputMode (window, GLFW_STICKY_KEYS, GL_TRUE);
  258. // enable depth text
  259. glEnable (GL_DEPTH_TEST);
  260. glDepthFunc (GL_LESS);
  261. // cull anything that doesn't look at the camera (might be useful to disable in the future)
  262. glDisable (GL_CULL_FACE);
  263. double minimumTime = 1.0 / maximumFPS;
  264. double startTime = 0.0;
  265. double endTime = 0.0;
  266. while (glfwWindowShouldClose (window) == 0)
  267. {
  268. // get the real framebuffer size
  269. glfwGetFramebufferSize (window, &windowWidth, &windowHeight);
  270. // set the default viewport
  271. context->setDefaultViewport ({0, 0, windowWidth, windowHeight});
  272. // calculate the current time value
  273. g_Time = (float) glfwGetTime ();
  274. // get the start time of the frame
  275. startTime = glfwGetTime ();
  276. // update our inputs first
  277. mouseInput->update ();
  278. // render the scene
  279. context->render ();
  280. // do buffer swapping
  281. glfwSwapBuffers (window);
  282. // poll for events (like closing the window)
  283. glfwPollEvents ();
  284. // get the end time of the frame
  285. endTime = glfwGetTime ();
  286. // ensure the frame time is correct to not overrun FPS
  287. if ((endTime - startTime) < minimumTime)
  288. usleep ((minimumTime - (endTime - startTime)) * CLOCKS_PER_SEC);
  289. }
  290. // terminate gl
  291. glfwTerminate ();
  292. // terminate SDL
  293. SDL_Quit ();
  294. // terminate free image
  295. FreeImage_DeInitialise ();
  296. // free paths
  297. free(finalPath);
  298. return 0;
  299. }