SessionIOJSON.cxx 13.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
//=========================================================================
//  Copyright (c) Kitware, Inc.
//  All rights reserved.
//  See LICENSE.txt for details.
//
//  This software is distributed WITHOUT ANY WARRANTY; without even
//  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
//  PURPOSE.  See the above copyright notice for more information.
//=========================================================================
10
#include "smtk/model/SessionIOJSON.h"
11

12
13
14
15
16
17
#include "smtk/attribute/FileItem.h"
#include "smtk/attribute/IntItem.h"
#include "smtk/common/UUID.h"
#include "smtk/io/ExportJSON.h"
#include "smtk/io/ExportJSON.txx"
#include "smtk/io/ImportJSON.h"
18
#include "smtk/model/Manager.h"
19
#include "smtk/model/Operator.h"
20

21
#include "boost/filesystem.hpp"
22
23
#include "cJSON.h"

24
25
using namespace boost::filesystem;

26
27
28
namespace smtk {
  namespace model {

29
30
31
32
33
34
/**\brief Decode information from \a sessionRec for the given \a modelMgr.
  *
  * Subclasses should return 1 on success and 0 on failure.
  */
int SessionIOJSON::importJSON(ManagerPtr modelMgr,
                              const SessionPtr& session,
35
36
                              cJSON* sessionRec,
                              bool loadNativeModels)
37
38
39
{
  smtk::common::UUIDs models =
    modelMgr->entitiesMatchingFlags(smtk::model::MODEL_ENTITY);
40
41
42
43
44

  cJSON* modelsObj = cJSON_GetObjectItem(sessionRec, "models");
  if (!modelsObj)
    {
    smtkInfoMacro(modelMgr->log(), "Expecting a \"models\" entry!");
45
    return 0;
46
    }
47
48
  
  std::map<smtk::common::UUID, std::string> existingURLs;
49
  cJSON* modelentry;
50
  // import all native models model entites, should only have meta info
51
  for (modelentry = modelsObj->child; modelentry; modelentry = modelentry->next)
52
    {
53
54
55
    if (!modelentry->string || !modelentry->string[0])
      continue;

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
    smtk::common::UUID modelid = smtk::common::UUID(modelentry->string);
    if (modelid.isNull())
      {
      smtkInfoMacro(modelMgr->log(), "Invalid model uuid, skipping!");
      continue;
      }
    // import native model if the model does not exist;
    // NOTE: what should we do if it already exists? erase then re-load
    // the original model from file (stored in string property "url")?
    // Else, just import meta info
    if(models.find(modelid) == models.end())
      {
      // find the model entry, and get the native model file name if it exists,
      // by looking at "output_native_url" property
      for (cJSON* curChild = modelentry->child; curChild; curChild = curChild->next)
        {
        if (!curChild->string || !curChild->string[0])
          {
          continue;
          }
        // find the model id in dictionary
        if (smtk::common::UUID(curChild->string) != modelid)
          {
          continue;
          }
        // failed to load properties is still OK
        smtk::io::ImportJSON::ofManagerStringProperties(modelid, curChild, modelMgr);
        break;
        }

86
      if(loadNativeModels)
87
        {
88
89
90
91
92
        std::string nativemodelfile;
        std::string nativefilekey = modelMgr->hasStringProperty(modelid, "output_native_url") ?
                                    "output_native_url" :
                                    (modelMgr->hasStringProperty(modelid, "url") ? "url" : "");
        if (!nativefilekey.empty())
93
          {
94
95
96
97
98
          smtk::model::StringList const& nprop(modelMgr->stringProperty(modelid, nativefilekey));
          if (!nprop.empty())
            {
            nativemodelfile = nprop[0];
            }
99
100
          }

101
102
103
104
105
        if(!nativemodelfile.empty())
          {
          // failed to load native model is still ok
          this->loadNativeModel(modelMgr, session, nativemodelfile);
          }
106
107
        }
      }
108
109
110
111
112
113
114
115
    else if(modelMgr->hasStringProperty(modelid, "url"))
      {
      smtk::model::StringList const& nprop(modelMgr->stringProperty(modelid, "url"));
      if (!nprop.empty())
        {
        existingURLs[modelid] = nprop[0];
        }
      }
116
117
118
    }
  int status = this->loadModelsRecord(modelMgr, sessionRec);
  status &= this->loadMeshesRecord(modelMgr, sessionRec);
119
120
121
122
123
124
  // recover "url" property for models already loaded
  std::map<smtk::common::UUID, std::string>::const_iterator mit;
  for(mit = existingURLs.begin(); mit != existingURLs.end(); ++mit)
    {
    modelMgr->setStringProperty(mit->first, "url", mit->second);
    }
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
  return status;
}

/**\brief Parse models info from \a sessionRec for the given \a modelMgr.
  *
  * Subclasses should return 1 on success and 0 on failure.
  */
int SessionIOJSON::loadModelsRecord(ManagerPtr modelMgr,
                                    cJSON* sessionRec)
{
  cJSON* modelsObj = cJSON_GetObjectItem(sessionRec, "models");
  if (!modelsObj)
    {
    // It's okay if we don't have "models" entry. Could be a record that
    // did not come from SessionIOJSON;
    smtkInfoMacro(modelMgr->log(), "Expecting a \"models\" entry!");
    return 1;
    }

  int status = 1;
  cJSON* modelentry;
  // import all native models model entites, should only have meta info
  for (modelentry = modelsObj->child; modelentry; modelentry = modelentry->next)
    {
    if (!modelentry->string || !modelentry->string[0])
      continue;
151

152
153
154
155
156
157
    smtk::common::UUID modelid = smtk::common::UUID(modelentry->string);
    if (modelid.isNull())
      {
      smtkInfoMacro(modelMgr->log(), "Invalid model uuid, skipping!");
      continue;
      }
158
159
160
161
162
163
164
    // model meta info 
    status &= smtk::io::ImportJSON::ofManager(modelentry, modelMgr);
    }

  return status;
}

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/**\brief Parse meshes info from \a sessionRec for the given \a modelMgr.
  *
  * Subclasses should return 1 on success and 0 on failure.
  */
int SessionIOJSON::loadMeshesRecord(ManagerPtr modelMgr,
                                    cJSON* sessionRec)
{
  cJSON* meshesObj = cJSON_GetObjectItem(sessionRec, "mesh_collections");
  if (!meshesObj)
    {
    // It's okay if we don't have "mesh_collections" entry. Could be a record that
    // did not come from SessionIOJSON;
    smtkInfoMacro(modelMgr->log(), "Expecting a \"mesh_collections\" entry!");
    return 1;
    }
  return smtk::io::ImportJSON::ofMeshesOfModel(sessionRec, modelMgr, true);
}

183
184
185
186
/**\brief Encode information into \a sessionRec for the given \a modelMgr.
  *
  * Subclasses should return 1 on success and 0 on failure.
  */
187
188
189
190
int SessionIOJSON::exportJSON(ManagerPtr modelMgr,
                              const SessionPtr& session,
                              cJSON* sessionRec,
                              bool writeNativeModels)
191
192
{
  (void)modelMgr;
193
  (void)session;
194
  (void)sessionRec;
195
  (void)writeNativeModels;
196
197
198
199
200
201
202
  return 1;
}

/**\brief Encode information into \a sessionRec for the given \a modelId of the \a modelMgr.
  *
  * Subclasses should return 1 on success and 0 on failure.
  */
203
204
205
int SessionIOJSON::exportJSON(ManagerPtr modelMgr,
                              const SessionPtr& session,
                              const smtk::common::UUIDs& modelIds,
206
207
                              cJSON* sessionRec,
                              bool writeNativeModels)
208
{
209
  if(writeNativeModels)
210
    {
211
212
213
    // we will write each model seperately
    smtk::common::UUIDs::const_iterator modit;
    for(modit = modelIds.begin(); modit != modelIds.end(); ++modit)
214
      {
215
216
217
218
219
220
      smtk::model::Model model(modelMgr, *modit);
      std::string outNativeFile = this->getOutputFileNameForNativeModel(modelMgr, session, model);
      if(this->writeNativeModel(modelMgr, session, model, outNativeFile))
        {
        modelMgr->setStringProperty(*modit, "output_native_url", outNativeFile);
        }
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
    }

  this->addModelsRecord(modelMgr, modelIds, sessionRec);
  this->addMeshesRecord(modelMgr, modelIds, sessionRec);
  return 1;
}

/**\brief Add records for \a modelIds to its parent \a sessionRec.
  *
  * This will add a "models" record to \a sessionRec, and all models
  * will be added as children of "models"
  */
void SessionIOJSON::addModelsRecord(const ManagerPtr& modelMgr,
                                    const smtk::common::UUIDs& modelIds,
                                    cJSON* sessionRec)
{
  smtk::model::Models models;
  smtk::model::EntityRef::EntityRefsFromUUIDs(models, modelMgr, modelIds);
  this->addModelsRecord(modelMgr, models, sessionRec);
}

void SessionIOJSON::addModelsRecord(const ManagerPtr& modelMgr,
                                    const smtk::model::Models& inModels,
                                    cJSON* sessionRec)

{
  cJSON* jmodels = cJSON_CreateObject();
  cJSON_AddItemToObject(sessionRec, "models", jmodels);
250

251
252
253
254
255
  // add record for each model
  smtk::model::Models::const_iterator modit;
  for(modit = inModels.begin(); modit != inModels.end(); ++modit)
    {
    //smtk::model::Model model(modelMgr, *modit);
256
257
258
259
    cJSON* jmodel = cJSON_CreateObject();

    // Write out all entities of the model, only the meta data
    smtk::model::Models currentmodels;
260
    currentmodels.push_back(*modit);
261
262
    smtk::io::ExportJSON::forEntities(jmodel, currentmodels,
                                      smtk::model::ITERATE_MODELS,
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
                                      static_cast<smtk::io::JSONFlags>(
                                        smtk::io::JSON_ENTITIES | smtk::io::JSON_PROPERTIES));

    cJSON_AddItemToObject(jmodels, modit->entity().toString().c_str(), jmodel);
    }
}

/**\brief Add records for meshes of \a modelIds to its parent \a sessionRec.
  *
  * This will add a "mesh_collections" record to \a sessionRec, and all meshes
  * will be added as children of "mesh_collections"
  */
void SessionIOJSON::addMeshesRecord(const ManagerPtr& modelMgr,
                                    const smtk::common::UUIDs& modelIds,
                                    cJSON* sessionRec)
{
  smtk::model::Models models;
  smtk::model::EntityRef::EntityRefsFromUUIDs(models, modelMgr, modelIds);
  this->addMeshesRecord(modelMgr, models, sessionRec);
}
283

284
285
286
287
288
289
290
291
292
void SessionIOJSON::addMeshesRecord(const ManagerPtr& modelMgr,
                                    const smtk::model::Models& inModels,
                                    cJSON* sessionRec)

{
  // add record for each model
  smtk::model::Models::const_iterator modit;
  for(modit = inModels.begin(); modit != inModels.end(); ++modit)
    {
293
294
    // Write out related mesh collections.
    // When writing a single collection, all its MeshSets will also be written out.
295
    smtk::io::ExportJSON::forModelMeshes(modit->entity(), sessionRec, modelMgr);
296
297
298
299
300
301
302
303
304
305
    }
}

/**\brief Create and write to a file (\a outNativeFile) for the given \a model.
  *
  * Return 1 on success and 0 on failure.
  */
int SessionIOJSON::writeNativeModel(smtk::model::ManagerPtr modelMgr,
                              const smtk::model::SessionPtr& sess,
                              const smtk::model::Model& model,
306
                              const std::string& outNativeFile)
307
308
309
310
311
312
313
314
{
  // if this is not a valid session, return;
  if(!sess)
    {
    smtkInfoMacro(modelMgr->log(), "Expecting a valid session!");
    return 0;
    }

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
  smtk::model::OperatorPtr writeOp = sess->op("write");
  if (!writeOp)
    {
    smtkInfoMacro(modelMgr->log(), "Failed to create a write operator to write the model for native kernel!");
    return 0;
    }
  writeOp->specification()->findFile("filename")->setValue(outNativeFile);
  writeOp->specification()->associateEntity(model);

  smtk::model::OperatorResult opresult = writeOp->operate();
  if (opresult->findInt("outcome")->value() !=
      smtk::model::OPERATION_SUCCEEDED)
    {
    smtkInfoMacro(modelMgr->log(), "Failed to write the model for native kernel!");
    return 0;
    }

  return 1;
}

/**\brief Get or construct a filename for saving the native model.
  *
  * Return a full file path.
  */
std::string SessionIOJSON::getOutputFileNameForNativeModel(
  smtk::model::ManagerPtr modelMgr,
  const smtk::model::SessionPtr& sess,
  const smtk::model::Model& model) const
{
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
  std::string smtkfilepath, smtkfilename, origfilename, origfileext;
  if (modelMgr->hasStringProperty(model.entity(), "smtk_url"))
    {
    smtk::model::StringList const& nprop(modelMgr->stringProperty(model.entity(), "smtk_url"));
    if (!nprop.empty())
      {
      smtkfilepath = path(nprop[0]).parent_path().string();
      smtkfilename = path(nprop[0]).stem().string();
      }
    }

  if (modelMgr->hasStringProperty(model.entity(), "url"))
    {
    smtk::model::StringList const& nprop(modelMgr->stringProperty(model.entity(), "url"));
    if (!nprop.empty())
      {
      origfilename = path(nprop[0]).stem().string();
      origfileext = path(nprop[0]).extension().string();
      }
    }
  if (smtkfilename.empty() && !origfilename.empty())
    smtkfilename = origfilename;

  if (smtkfilename.empty())
    smtkfilename = sess->name();

  std::ostringstream outfilename;
  outfilename << smtkfilename << "_native" << origfileext;
372
  return (path(smtkfilepath) / path(outfilename.str())).string();
373

374
375
}

376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/**\brief Load the native model given the filename (\a inNativeFile).
  *
  * Return 1 on success and 0 on failure.
  */
int SessionIOJSON::loadNativeModel(smtk::model::ManagerPtr modelMgr,
                              const smtk::model::SessionPtr& sess,
                              const std::string& inNativeFile)
{
  // if this is not a valid session, return;
  if(!sess)
    {
    smtkInfoMacro(modelMgr->log(), "Expecting a valid session!");
    return 0;
    }

  if (!inNativeFile.empty())
    {
    smtk::model::OperatorPtr readOp = sess->op("read");
    if (!readOp)
      {
      smtkInfoMacro(modelMgr->log(), "Failed to create a read operator to read the model for native kernel!");
      return 0;
      }
    readOp->specification()->findFile("filename")->setValue(inNativeFile);
    smtk::model::OperatorResult opresult = readOp->operate();
    if (opresult->findInt("outcome")->value() !=
        smtk::model::OPERATION_SUCCEEDED)
      {
      smtkInfoMacro(modelMgr->log(), "Failed to read the model for native kernel!");
      return 0;
      }
    return 1;
    }

  return 0;
}

413
414
  } // namespace model
} // namespace smtk