AnnJsonLevel.cpp
Go to the documentation of this file.
1 
2 #include <AnnJsonLevel.hpp>
3 #include <json.hpp>
4 
5 #include <fstream>
6 #include "Annwvyn.h"
7 
8 //Chaiscript also exposes a json class took from "simple json".
9 //But the interface of "JSON for modern C++" is nicer to use
10 using json_t = nlohmann::json;
11 
12 namespace Annwvyn
13 {
14  //Our little pimpl
16  {
18  };
19 
20  //Type conversion are defined by overloading from_json and to_json
21  void from_json(const json_t& j, AnnVect3& v)
22  {
23  v.x = j[0];
24  v.y = j[1];
25  v.z = j[2];
26  }
27 
28  void from_json(const json_t& j, AnnQuaternion& q)
29  {
30  q.x = j[0];
31  q.y = j[1];
32  q.z = j[2];
33  q.w = j[3];
34  }
35 
36  struct phyParam
37  {
39  float mass;
41  };
42 
44  {
45  if(str == "static")
46  return staticShape;
47  if(str == "convex")
48  return convexShape;
49  if(str == "box")
50  return boxShape;
51  if(str == "cylinder")
52  return cylinderShape;
53  if(str == "capsule")
54  return capsuleShape;
55  if(str == "sphere")
56  return sphereShape;
57  return error;
58  }
59 
60  void from_json(const json_t& j, phyParam& p)
61  {
62  p.mass = j["mass"];
63  p.type = stringToShape(j["shape"]);
64  p.colideWithPlayer = j["playerColide"];
65  }
66 
67  void from_json(const json_t& j, AnnGameObjectPtr& obj)
68  {
69  auto GameObjectManager = AnnGetGameObjectManager();
70  obj = GameObjectManager->createGameObject(j["mesh"], j["name"]);
71  if(!obj) throw AnnNullGameObjectError();
72 
73  obj->setPosition(j["position"]);
74  obj->setOrientation(j["orientation"]);
75  obj->setScale(j["scale"]);
76 
77  if(j["hasPhysics"])
78  {
79  phyParam param = j["physics"];
80  if(param.type == error) throw AnnInvalidPhysicalShapeError(obj->getName());
81  obj->setupPhysics(param.mass, param.type, param.colideWithPlayer);
82  }
83 
84  if(!j["scripts"].is_null())
85  {
86  for(auto& jsonScript : j["scripts"])
87  obj->attachScript(jsonScript);
88  }
89  }
90 
92  {
93  if(s == "directional") return AnnLightObject::ANN_LIGHT_DIRECTIONAL;
94  if(s == "spot") return AnnLightObject::ANN_LIGHT_SPOTLIGHT;
95  if(s == "point") return AnnLightObject::ANN_LIGHT_POINT;
96 
98  }
99 
101  {
102  auto GameObjectManager = AnnGetGameObjectManager();
103  l = GameObjectManager->createLightObject(j["name"]);
104 
105  auto type = lightTypeFromString(j["type"]);
107  l->setType(type);
108 
109  l->setPower(j["power"]);
110  if(j.find("position") != std::end(j))
111  l->setPosition(j["position"]);
112  if(j.find("direction") != std::end(j))
113  l->setDirection(j["direction"]);
114  }
115 
116  struct resLocParam
117  {
121  };
122 
123  void declareResource(const resLocParam& res)
124  {
125  auto resourceManager = AnnGetResourceManager();
126  if(res.type == "Zip")
127  resourceManager->addZipLocation(res.path, res.group);
128  }
129 
130  void from_json(const json_t& j, resLocParam& p)
131  {
132  if(!j["group"].is_null())
133  p.group = j["group"];
134  else
136 
137  p.path = j["path"];
138  p.type = j["type"];
139  }
140 }
141 using namespace Annwvyn;
142 
143 AnnJsonLevel::AnnJsonLevel(std::string path, const bool preload) :
144  constructLevel(),
145  preloadResources(preload)
146 {
147  jsonFile = std::make_unique<AnnJson>();
148  auto& json = jsonFile->j;
149 
150  //Read full content of the pointed file
151  const std::string file {
152  [&] {
153  std::ifstream fileStream(path);
154  if(fileStream)
155  return std::string(std::istreambuf_iterator<char>(fileStream),
157  return std::string {};
158  }()
159  };
160 
161  //If it wasn't possible to open the file or anything happened while reading chars
162  if(file.empty())
163  throw AnnInitializationError(ANN_ERR_INFILE, "Could not load content of JSON level file " + path);
164 
165  //Load JSON
166  json = json_t::parse(file);
167 
168  processJson();
169 }
170 
171 AnnJsonLevel::AnnJsonLevel(bool, std::string jsonCode, const bool preload) :
172  constructLevel(),
173  preloadResources(preload)
174 {
175  jsonFile = std::make_unique<AnnJson>();
176  auto& json = jsonFile->j;
177  json = json_t::parse(jsonCode);
178  processJson();
179 }
180 
182 {
183 }
184 
186 {
187  auto& json = jsonFile->j;
188 
189  for(auto& jsonGameObject : json["content"])
190  levelContent.push_back(jsonGameObject);
191 
192  for(auto& jsonLight : json["lighting"])
193  levelLighting.push_back(jsonLight);
194 
195  auto player = AnnGetPlayer();
196  player->setPosition(json["player"]["startPosition"]);
197  player->setOrientation(json["player"]["startOrientation"].get<AnnQuaternion>());
198  AnnDebug() << "Player position reset";
199  AnnDebug() << player->getPosition();
200  AnnDebug() << player->getOrientation();
201 }
202 
204 {
205 }
206 
208 {
209  auto& json = jsonFile->j;
210  AnnDebug() << "got json:\n"
211  << json;
212  name = json["name"].get<std::string>();
213  AnnDebug() << "name is " << name;
214 
215  if(!json["resources"].is_null())
216  AnnDebug() << "Defined " << json["resources"].size() << " resources";
217  for(const resLocParam resource : json["resources"])
218  {
219  declareResource(resource);
220  auto resourceManager = AnnGetResourceManager();
221  if(preloadResources && resource.group != resourceManager->getDefaultResourceGroupName())
222  {
223  resourceManager->loadGroup(resource.group);
224  }
225  }
226 }
phyShapeType type
void declareResource(const resLocParam &res)
Directional lights simulate parallel light beams from a distant source, hence have direction but no p...
phyShapeType stringToShape(const std::string &str)
Spotlights simulate a cone of light from a source so require position and direction, plus extra values for falloff.
A 3D Vector.
Definition: AnnVect3.hpp:16
AnnLightObject::LightTypes lightTypeFromString(const std::string &s)
T end(T... args)
#define constructLevel()
Definition: AnnLevel.hpp:19
Namespace containing the totality of Annwvyn components.
Definition: AnnGetter.cpp:8
void runLogic() override
Run logic, actually empty here.
LightTypes
Defines the type of light.
Exception regarding engine utilisation. See message.
AnnGameObjectManagerPtr AnnGetGameObjectManager()
Get the game-object manager.
Definition: AnnGetter.cpp:22
phyShapeType
Definition: AnnTypes.h:43
virtual ~AnnJsonLevel()
Dtor.
static const char * getDefaultResourceGroupName()
Return the default resource group name.
AnnJsonOpaquePtr jsonFile
Pimpl.
void processJson()
Do initial processing on JSON.
nlohmann::json json_t
#define ANN_ERR_INFILE
Represent a Quaternion.
Open an output stream to the engine log.
Definition: AnnLogger.hpp:23
void from_json(const json_t &j, AnnVect3 &v)
Exception regarding collision shape creation.
Main Annwvyn include file (to be used by client application)
Point light sources give off light equally in all directions, so require only position not direction...
void load() override
Load method. This goes through the loaded JSON and create the object for you.
const bool preloadResources
If set to false, resource group will not be initialized.
AnnResourceManagerPtr AnnGetResourceManager()
Get the resource manager.
Definition: AnnGetter.cpp:18
AnnJsonLevel(std::string path, bool preload=true)
Construct a JSON level from a file.
Exception regarding an AnnGameObject that was null when it wasnt.
AnnPlayerBodyPtr AnnGetPlayer()
Get the player object.
Definition: AnnGetter.cpp:17