HLayoutParser.cpp
15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
//
// HLayoutParser.cpp
// SteveMaggieCpp
//
// Created by Katarzyna Kalinowska-Górska on 16.05.2017.
//
//
#include <stdio.h>
#include "HLayoutParser.h"
#include "HLayoutObject.h"
#include "HScalingUtils.h"
#include "HStringUtils.h"
#include "HJSONParseUtils.h"
#include "HPlainNode.h"
#include "HPlainSprite.h"
#include "HalloweenSimpleButton.h"
#include "HLevelPickerView.h"
#include "HTwoStateButton.h"
#include "HResourceUtilities.h"
class HLayoutObjectMapper
{
public:
HLayoutObject* createObjectFromClassName(std::string className, const rapidjson::Value& nodeData, std::string resFolder, std::string altResFolder)
{
HLayoutObject* newObject = NULL; //TODO TUTAJ BRAC POD UWAGE ADDITIONANODE DATA moze wziac HLayoutParsera convenient metode
std::string resourcesPath = resFolder;
if(HJSONParseUtils::checkMemberBool(nodeData, "useAlternativePath", true))
{
resourcesPath = altResFolder;
}
// resourcesPath = HResourceUtilities::getInstance().getFullPathForDownloadedFile(resourcesPath); //TODO moze to gdzies wyrzucic jednak albo chociaz dac parameter czy to robic?
if(className == "PlainNode"){
newObject = HPlainNode::create();
}
else if(className == "PlainSprite"){
std::string filePath = resourcesPath + nodeData["imagePath"].GetString();
newObject = HPlainSprite::createWithSpritePath(filePath);
}
else if(className == "SimpleButton"){
newObject = HalloweenSimpleButton::create();
} else if (className == "LevelView"){
auto levelImagePath = nodeData["levelImagePath"].GetString();
std::string levelName = nodeData.HasMember("levelName") ? nodeData["levelName"].GetString() : "";
auto path = resourcesPath + levelImagePath;
newObject = levelName.empty() ? HLevelView::create(path) : HLevelView::create(path, levelName);
}
else if (className == "LevelPickerView"){
auto levelImagePaths = HJSONParseUtils::parseStringArray(nodeData["levelImagePaths"]);
auto levelNames = nodeData.HasMember("levelNames") ? HJSONParseUtils::parseStringArray(nodeData["levelNames"]) : std::vector<std::string>();
for(auto& path : levelImagePaths){
path = resourcesPath + path;
}
newObject = HLevelPickerView::create(levelImagePaths, levelNames);
}
else if(className == "TwoStateButton"){
std::string inactiveImagePath = resourcesPath + nodeData["inactiveImagePath"].GetString();
std::string activeImagePath = resourcesPath + nodeData["activeImagePath"].GetString();
newObject = HTwoStateButton::create(inactiveImagePath, activeImagePath);
}
else // create a plain sprite
{
std::string filePath = resourcesPath + nodeData["imagePath"].GetString();
newObject = HPlainSprite::createWithSpritePath(filePath);
}
return newObject;
}
};
std::string HLayoutParser::loadJSONFromFile(const std::string& jsonFilePath)
{
std::string fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(jsonFilePath);
return cocos2d::FileUtils::getInstance()->getStringFromFile(fullPath);
}
void HLayoutParser::loadLayoutFromJSONFile(const std::string& jsonFilePath, HLayoutViewInterface* scene)
{
std::string jsonString = this->loadJSONFromFile(jsonFilePath);
return this->loadLayoutFromJSONString(jsonString, scene);
}
void HLayoutParser::loadLayoutFromDownloadedJSONFile(const std::string& jsonFilePath, HLayoutViewInterface* scene)
{
// std::string downloadedFilePath = HResourceUtilities::getInstance().getFullPathForDownloadedFile(jsonFilePath, true);
std::string jsonString = cocos2d::FileUtils::getInstance()->getStringFromFile(jsonFilePath); //this->loadJSONFromFile(downloadedFilePath + jsonFilePath);
return this->loadLayoutFromJSONString(jsonString, scene);
}
void HLayoutParser::loadLayoutFromJSONString(const std::string& jsonString, HLayoutViewInterface* scene) //TODO: invalid layout file will cause a crash, will have to fix it!!!
{
rapidjson::Document document;
document.Parse(jsonString.c_str());
this->_parsedDocument = &document;
if(document.HasMember("backgroundMusicPath")){
std::string bgMusicFilePath = document["backgroundMusicPath"].GetString();
bgMusicFilePath = HResourceUtilities::getInstance().getFullPathForDownloadedFile(bgMusicFilePath, false);
scene->setupBackgroundMusic(bgMusicFilePath);
}
const auto& sceneLayoutJSON = document["sceneLayout"];
const auto& layersJSON = sceneLayoutJSON["layers"].GetArray();
for(const auto& layerJSON : layersJSON)
{
cocos2d::Layer* newLayer = NULL;
if(layerJSON.HasMember("color")){
const auto& color = layerJSON["color"];
auto colorR = color["r"].GetInt();
auto colorG = color["g"].GetInt();
auto colorB = color["b"].GetInt();
auto colorA = color["a"].GetInt();
newLayer = cocos2d::LayerColor::create(cocos2d::Color4B(colorR, colorG, colorB, colorA));
} else {
newLayer = cocos2d::Layer::create();
}
auto sceneAsNode = dynamic_cast<cocos2d::Node*>(scene);
sceneAsNode->addChild(newLayer);
scene->addLayer(newLayer);
if(layerJSON.HasMember("name") && layerJSON["name"].IsString()){
auto layerName = std::string(layerJSON["name"].GetString());
scene->addObject(layerName, newLayer);
}
std::string objectLayoutsFolder = "";
std::string resFolder = "";
std::string altResFolder = "";
if(document.HasMember("resFolder")){
const auto& resFolderJSON = document["resFolder"];
if(resFolderJSON.HasMember("objectLayoutsPath")){
objectLayoutsFolder = resFolderJSON["objectLayoutsPath"].GetString();
}
if(resFolderJSON.HasMember("path")){
resFolder = resFolderJSON["path"].GetString();
}
if(resFolderJSON.HasMember("alternativePath")){
altResFolder = resFolderJSON["alternativePath"].GetString();
}
}
resFolder = HResourceUtilities::getInstance().getFullPathForDownloadedFile(resFolder);
altResFolder = HResourceUtilities::getInstance().getFullPathForDownloadedFile(altResFolder);
rapidjson::Value layerJSONCopy(layerJSON, this->_parsedDocument->GetAllocator());
this->parseChildObjects(scene, layerJSONCopy, newLayer, objectLayoutsFolder, resFolder, altResFolder, true);
}
this->_parsedDocument = NULL;
}
void HLayoutParser::parseChildObjects(HLayoutViewInterface* scene, rapidjson::Value& nodeData, cocos2d::Node* createdNode, std::string objectLayoutsFolder, std::string resFolder, std::string altResFolder, bool isTopLayer)
{
if(nodeData.HasMember("objects")){
auto objects = nodeData["objects"].GetArray();
for(const auto& objectJSON : objects){
rapidjson::Value objectJSONCopy(objectJSON, this->_parsedDocument->GetAllocator());
auto newObject = this->parseObject(scene, objectJSONCopy, createdNode, objectLayoutsFolder, resFolder, altResFolder, isTopLayer);
if(newObject != NULL){
this->parseChildObjects(scene, objectJSONCopy, newObject, objectLayoutsFolder, resFolder, altResFolder, false);
}
}
}
}
cocos2d::Node* HLayoutParser::parseObject(HLayoutViewInterface* scene, rapidjson::Value& nodeData, cocos2d::Node* parentNode, std::string objectLayoutsFolder, std::string resFolder, std::string altResFolder, bool isTopLayer)
{
//todo memory leaks?
cocos2d::Node* newObject = NULL;
float newObjectWidth, newObjectHeight;
// auto scale = cocos2d::Director::getInstance()->getContentScaleFactor();
if(nodeData.HasMember("loadObjectFromFile")){
std::string objectDataPath = objectLayoutsFolder + nodeData["loadObjectFromFile"].GetString();
objectDataPath = HResourceUtilities::getInstance().getFullPathForDownloadedFile(objectDataPath, true);
std::string jsonString = this->loadJSONFromFile(objectDataPath);
if(jsonString != ""){
rapidjson::Document additionalObjectJSON;
additionalObjectJSON.Parse(jsonString.c_str());
const auto& additionalObjectJsonData = additionalObjectJSON["object"];
auto& allocator = this->_parsedDocument->GetAllocator();
for (rapidjson::Value::ConstMemberIterator itr = additionalObjectJsonData.MemberBegin(); itr != additionalObjectJsonData.MemberEnd(); ++itr)
{
const char* memberName = itr->name.GetString();
const rapidjson::Value& memberValue = itr->value;
nodeData.AddMember(rapidjson::Value(memberName, allocator).Move(), rapidjson::Value(memberValue, allocator).Move(), allocator);
}
}
}
HLayoutObjectMapper mapper;
std::string type = "PlainSprite";
auto typeValue = this->getValueForKey("type", nodeData);
if(typeValue != NULL){
type = typeValue->GetString();
}
auto newObjectAsHLayoutObject = mapper.createObjectFromClassName(type, nodeData, resFolder, altResFolder);
if(newObjectAsHLayoutObject == NULL){
return NULL;
}
newObjectAsHLayoutObject->loadPropertiesFromJSON(nodeData, scene, resFolder, altResFolder);
newObjectAsHLayoutObject->prepareSize(nodeData, newObjectWidth, newObjectHeight);
newObject = dynamic_cast<cocos2d::Node*>(newObjectAsHLayoutObject);
if(newObjectAsHLayoutObject->isWidget()){
newObjectAsHLayoutObject->setOnTouchBeganCallback(CC_CALLBACK_2(HLayoutViewInterface::touchHandlerForWidget, scene));
newObjectAsHLayoutObject->setOnTouchEndedCallback(CC_CALLBACK_2(HLayoutViewInterface::touchHandlerForWidget, scene));
newObjectAsHLayoutObject->setOnTouchCancelledCallback(CC_CALLBACK_2(HLayoutViewInterface::touchHandlerForWidget, scene));
}
// float objectScale = 1;
// auto scaleFromJSON = this->getValueForKey("scale", nodeData, additionalObjectJsonData);
// if(scaleFromJSON != NULL){
// objectScale = scaleFromJSON->GetFloat();
// }
auto objectName = this->getValueForKey("name", nodeData)->GetString();
// scene->_objects.insert({objectName, newObject});
scene->addObject(objectName, newObject);
// object placement; maybe put into a separate function
// auto ignoreScalingJSON = this->getValueForKey("ignore_scaling", nodeData);
// bool ignoreScaling = false;
// if(ignoreScalingJSON != NULL){
// ignoreScaling = ignoreScalingJSON->GetBool(); //TODO ignore scaling is int
// }
float scaleToDesignSize = 1/cocos2d::Director::getInstance()->getContentScaleFactor();
float additionalPaddingW = isTopLayer /*&& !ignoreScaling */? HScalingUtils::getInstance().getScaledScreenSurplusWidth()*scaleToDesignSize / 2 : 0;
float additionalPaddingH = isTopLayer /*&& !ignoreScaling */? HScalingUtils::getInstance().getScaledScreenSurplusHeight()*scaleToDesignSize / 2 : 0;
// float scaleToDesignSize = HScalingUtils::scaleAspectFillToDesignIpadProSize();
auto objectScale = scaleToDesignSize;//scale;//(ignoreScaling ? 1 : scale)/scaleToDesignSize;
if(HScalingUtils::isSmallDevice() && (type == "TwoStateButton" || type == "SimpleButton")){//TODO ugly, should probably be somewhere in the HalloweenSimpleButton class or somewhere
objectScale = objectScale * HScalingUtils::getScaleForSmallDevice();
}
float objectXPos = 0, objectYPos = 0;
bool skipPlacement = false;
auto parentNodeWidth = parentNode->getContentSize().width;
auto parentNodeHeight = parentNode->getContentSize().height;
auto layoutMode = this->getValueForKey("layoutMode", nodeData);
std::string fillParentMode = "fillParent"; //TODO enum
if(layoutMode != NULL && fillParentMode == layoutMode->GetString()){
objectXPos = parentNodeWidth / 2; //TODO override getContentSize() everywhere
objectYPos = parentNodeHeight / 2;
newObject->setContentSize(cocos2d::Size(parentNodeWidth, parentNodeHeight));
skipPlacement = true;
}
if(!skipPlacement){
const auto& xPosJSON = this->getValueForKey("centerXPos", nodeData);
std::string xPlacementMode = this->getValueForKey("value", *xPosJSON)->GetString();
if(xPlacementMode == "center"){
objectXPos = parentNodeWidth/2;
} else if(xPlacementMode == "left"){
objectXPos = newObjectWidth/2 + additionalPaddingW;
} else if(xPlacementMode == "right"){
objectXPos = parentNodeWidth - newObjectWidth/2 - additionalPaddingW;
} else if(xPlacementMode.find("divide") != std::string::npos){
auto tokens = HStringUtils::splitString(xPlacementMode, ' ');
float divide = atof(tokens[1].c_str());
float place = atof(tokens[3].c_str());
objectXPos = parentNodeWidth*place/divide;
}
auto xPadding = this->getValueForKey("padding", *xPosJSON);
if(xPadding != NULL){
objectXPos += xPadding->GetFloat()*objectScale;
}
const auto& yPosJSON = this->getValueForKey("centerYPos", nodeData);
std::string yPlacementMode = this->getValueForKey("value", *yPosJSON)->GetString();
if(yPlacementMode == "center"){
objectYPos = parentNodeHeight/2;
} else if(yPlacementMode == "bottom"){
objectYPos = newObjectHeight/2 + additionalPaddingH;
} else if(yPlacementMode == "top"){
objectYPos = parentNodeHeight - newObjectHeight/2 - additionalPaddingH;
} else if(yPlacementMode.find("divide") != std::string::npos){
auto tokens = HStringUtils::splitString(yPlacementMode, ' ');
float divide = atof(tokens[1].c_str());
float place = atof(tokens[3].c_str());
objectYPos = parentNodeHeight*place/divide;
}
auto yPadding = this->getValueForKey("padding", *yPosJSON);
if(yPadding != NULL){
objectYPos += yPadding->GetFloat()*objectScale;
}
}
// newObject->setScale(objectScale);
newObject->setPosition(objectXPos, objectYPos);
auto stretchMode = this->getValueForKey("stretchMode", nodeData);
std::string aspectFill = "aspectFill";
if(stretchMode != NULL && aspectFill == stretchMode->GetString()){
float stretchScale = HScalingUtils::imageAspectFillGetScale(cocos2d::Size(newObjectWidth, newObjectHeight), cocos2d::Size(parentNodeWidth, parentNodeHeight));
newObject->setScale(stretchScale);
}
auto depthJSON = this->getValueForKey("depth", nodeData);
if(depthJSON != NULL){
float depth = depthJSON->GetInt();
parentNode->addChild(newObject, depth);
} else {
parentNode->addChild(newObject);
}
auto opacityJSON = this->getValueForKey("opacity", nodeData);
if (opacityJSON != NULL) {
int opacity = opacityJSON->GetInt();
newObject->setOpacity(opacity);
}
return newObject;
}
const rapidjson::Value* HLayoutParser::getValueForKey(std::string key, const rapidjson::Value& mainNodeData)
{
if(mainNodeData.HasMember(key.c_str())){
return &mainNodeData[key.c_str()];
}
return NULL;
}