aboutsummaryrefslogtreecommitdiffstats
path: root/yage/core/spritesheet.cpp
diff options
context:
space:
mode:
authorYann Herklotz <ymherklotz@gmail.com>2017-10-31 22:11:18 +0000
committerYann Herklotz <ymherklotz@gmail.com>2017-10-31 22:11:18 +0000
commitf776df6076725d14679b31168e3ede53c966182e (patch)
treeb843d7ef0d0722a1b3571ee09aa1345d19c60e7f /yage/core/spritesheet.cpp
parent1bb0ef8960c71ef505a351702bec54c01ba15e22 (diff)
downloadYAGE-f776df6076725d14679b31168e3ede53c966182e.tar.gz
YAGE-f776df6076725d14679b31168e3ede53c966182e.zip
renaming base folder
Diffstat (limited to 'yage/core/spritesheet.cpp')
-rw-r--r--yage/core/spritesheet.cpp85
1 files changed, 85 insertions, 0 deletions
diff --git a/yage/core/spritesheet.cpp b/yage/core/spritesheet.cpp
new file mode 100644
index 00000000..5c3499cc
--- /dev/null
+++ b/yage/core/spritesheet.cpp
@@ -0,0 +1,85 @@
+/* ----------------------------------------------------------------------------
+ * spritesheet.cpp
+ *
+ * Copyright (c) 2017 Yann Herklotz Grave <ymherklotz@gmail.com>
+ * MIT License, see LICENSE file for more details.
+ * ----------------------------------------------------------------------------
+ */
+
+/** @file
+ */
+
+#include "spritesheet.h"
+
+#include <cassert>
+#include <fstream>
+#include <sstream>
+#include <stdexcept>
+
+#include <rapidjson/document.h>
+#include <yage/base/imageloader.h>
+
+using namespace std;
+using namespace rapidjson;
+using namespace yage::details;
+
+namespace yage
+{
+
+SpriteSheet::SpriteSheet(string pngFileName, string jsonFileName)
+{
+ int jsonWidth, jsonHeight;
+ fileLocations_ =
+ parseJson(jsonWidth, jsonHeight, fileContent(jsonFileName));
+ texture_ = ImageLoader::loadPng(pngFileName);
+
+ if (texture_.width != jsonWidth)
+ throw runtime_error("JSON width does not match texture width");
+ if (texture_.height != jsonHeight)
+ throw runtime_error("JSON height does not match texture height");
+}
+
+string SpriteSheet::fileContent(string jsonFileName) const
+{
+ ifstream inputFile(jsonFileName);
+
+ stringstream stream;
+ stream << inputFile.rdbuf();
+
+ return stream.str();
+}
+
+SpriteMap SpriteSheet::parseJson(int &width, int &height,
+ string jsonContent) const
+{
+ SpriteMap spriteMap;
+ Document jsonAtlas;
+ jsonAtlas.Parse(jsonContent.c_str());
+
+ width = jsonAtlas["width"].GetInt();
+ height = jsonAtlas["height"].GetInt();
+
+ for (auto &texture : jsonAtlas["sprites"].GetObject()) {
+ Coordinate coord;
+ for (auto &value : texture.value.GetObject()) {
+ string keyName{value.value.GetString()};
+ int keyValue{value.value.GetInt()};
+ if (keyName == "x") {
+ coord.x = keyValue;
+ } else if (keyName == "y") {
+ coord.y = keyValue;
+ } else if (keyName == "width") {
+ coord.width = keyValue;
+ } else if (keyName == "height") {
+ coord.height = keyValue;
+ } else {
+ throw runtime_error("JSON key incorrect: " + keyName);
+ }
+ }
+ spriteMap[texture.name.GetString()] = coord;
+ }
+
+ return spriteMap;
+}
+
+} // namespace yage