Alembic export: made hair/particle export optional.
[blender.git] / source / blender / alembic / intern / alembic_capi.cc
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Esteban Tovagliari, Cedric Paille, Kevin Dietrich
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 #include "../ABC_alembic.h"
24 #include <boost/foreach.hpp>
25
26 #include <Alembic/AbcMaterial/IMaterial.h>
27
28 #include "abc_archive.h"
29 #include "abc_camera.h"
30 #include "abc_curves.h"
31 #include "abc_hair.h"
32 #include "abc_mesh.h"
33 #include "abc_nurbs.h"
34 #include "abc_points.h"
35 #include "abc_transform.h"
36 #include "abc_util.h"
37
38 extern "C" {
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_cachefile_types.h"
42 #include "DNA_curve_types.h"
43 #include "DNA_modifier_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_scene_types.h"
46
47 #include "BKE_cachefile.h"
48 #include "BKE_cdderivedmesh.h"
49 #include "BKE_context.h"
50 #include "BKE_curve.h"
51 #include "BKE_depsgraph.h"
52 #include "BKE_global.h"
53 #include "BKE_library.h"
54 #include "BKE_main.h"
55 #include "BKE_scene.h"
56
57 /* SpaceType struct has a member called 'new' which obviously conflicts with C++
58  * so temporarily redefining the new keyword to make it compile. */
59 #define new extern_new
60 #include "BKE_screen.h"
61 #undef new
62
63 #include "BLI_fileops.h"
64 #include "BLI_ghash.h"
65 #include "BLI_listbase.h"
66 #include "BLI_math.h"
67 #include "BLI_path_util.h"
68 #include "BLI_string.h"
69
70 #include "WM_api.h"
71 #include "WM_types.h"
72 }
73
74 using Alembic::Abc::Int32ArraySamplePtr;
75 using Alembic::Abc::ObjectHeader;
76
77 using Alembic::AbcGeom::MetaData;
78 using Alembic::AbcGeom::P3fArraySamplePtr;
79 using Alembic::AbcGeom::kWrapExisting;
80
81 using Alembic::AbcGeom::ICamera;
82 using Alembic::AbcGeom::ICurves;
83 using Alembic::AbcGeom::ICurvesSchema;
84 using Alembic::AbcGeom::IFaceSet;
85 using Alembic::AbcGeom::ILight;
86 using Alembic::AbcGeom::INuPatch;
87 using Alembic::AbcGeom::IObject;
88 using Alembic::AbcGeom::IPoints;
89 using Alembic::AbcGeom::IPointsSchema;
90 using Alembic::AbcGeom::IPolyMesh;
91 using Alembic::AbcGeom::IPolyMeshSchema;
92 using Alembic::AbcGeom::ISampleSelector;
93 using Alembic::AbcGeom::ISubD;
94 using Alembic::AbcGeom::IV2fGeomParam;
95 using Alembic::AbcGeom::IXform;
96 using Alembic::AbcGeom::IXformSchema;
97 using Alembic::AbcGeom::N3fArraySamplePtr;
98 using Alembic::AbcGeom::XformSample;
99 using Alembic::AbcGeom::ICompoundProperty;
100 using Alembic::AbcGeom::IN3fArrayProperty;
101 using Alembic::AbcGeom::IN3fGeomParam;
102 using Alembic::AbcGeom::V3fArraySamplePtr;
103
104 using Alembic::AbcMaterial::IMaterial;
105
106 struct AbcArchiveHandle {
107         int unused;
108 };
109
110 ABC_INLINE ArchiveReader *archive_from_handle(AbcArchiveHandle *handle)
111 {
112         return reinterpret_cast<ArchiveReader *>(handle);
113 }
114
115 ABC_INLINE AbcArchiveHandle *handle_from_archive(ArchiveReader *archive)
116 {
117         return reinterpret_cast<AbcArchiveHandle *>(archive);
118 }
119
120 //#define USE_NURBS
121
122 /* NOTE: this function is similar to visit_objects below, need to keep them in
123  * sync. */
124 static bool gather_objects_paths(const IObject &object, ListBase *object_paths)
125 {
126         if (!object.valid()) {
127                 return false;
128         }
129
130
131         size_t children_claiming_this_object = 0;
132         size_t num_children = object.getNumChildren();
133
134         for (size_t i = 0; i < num_children; ++i) {
135                 bool child_claims_this_object = gather_objects_paths(object.getChild(i), object_paths);
136                 children_claiming_this_object += child_claims_this_object ? 1 : 0;
137         }
138
139         const MetaData &md = object.getMetaData();
140         bool get_path = false;
141         bool parent_is_part_of_this_object = false;
142
143         if (!object.getParent()) {
144                 /* The root itself is not an object we should import. */
145         }
146         else if (IXform::matches(md)) {
147                 if (has_property(object.getProperties(), "locator")) {
148                         get_path = true;
149                 }
150                 else {
151                         get_path = children_claiming_this_object == 0;
152                 }
153
154                 /* Transforms are never "data" for their parent. */
155                 parent_is_part_of_this_object = false;
156         }
157         else {
158                 /* These types are "data" for their parent. */
159                 get_path =
160                         IPolyMesh::matches(md) ||
161                         ISubD::matches(md) ||
162 #ifdef USE_NURBS
163                         INuPatch::matches(md) ||
164 #endif
165                         ICamera::matches(md) ||
166                         IPoints::matches(md) ||
167                         ICurves::matches(md);
168                 parent_is_part_of_this_object = get_path;
169         }
170
171         if (get_path) {
172                 void *abc_path_void = MEM_callocN(sizeof(AlembicObjectPath), "AlembicObjectPath");
173                 AlembicObjectPath *abc_path = static_cast<AlembicObjectPath *>(abc_path_void);
174
175                 BLI_strncpy(abc_path->path, object.getFullName().c_str(), PATH_MAX);
176                 BLI_addtail(object_paths, abc_path);
177         }
178
179         return parent_is_part_of_this_object;
180 }
181
182 AbcArchiveHandle *ABC_create_handle(const char *filename, ListBase *object_paths)
183 {
184         ArchiveReader *archive = new ArchiveReader(filename);
185
186         if (!archive->valid()) {
187                 delete archive;
188                 return NULL;
189         }
190
191         if (object_paths) {
192                 gather_objects_paths(archive->getTop(), object_paths);
193         }
194
195         return handle_from_archive(archive);
196 }
197
198 void ABC_free_handle(AbcArchiveHandle *handle)
199 {
200         delete archive_from_handle(handle);
201 }
202
203 int ABC_get_version()
204 {
205         return ALEMBIC_LIBRARY_VERSION;
206 }
207
208 static void find_iobject(const IObject &object, IObject &ret,
209                          const std::string &path)
210 {
211         if (!object.valid()) {
212                 return;
213         }
214
215         std::vector<std::string> tokens;
216         split(path, '/', tokens);
217
218         IObject tmp = object;
219
220         std::vector<std::string>::iterator iter;
221         for (iter = tokens.begin(); iter != tokens.end(); ++iter) {
222                 IObject child = tmp.getChild(*iter);
223                 tmp = child;
224         }
225
226         ret = tmp;
227 }
228
229 struct ExportJobData {
230         Scene *scene;
231         Main *bmain;
232
233         char filename[1024];
234         ExportSettings settings;
235
236         short *stop;
237         short *do_update;
238         float *progress;
239
240         bool was_canceled;
241 };
242
243 static void export_startjob(void *customdata, short *stop, short *do_update, float *progress)
244 {
245         ExportJobData *data = static_cast<ExportJobData *>(customdata);
246
247         data->stop = stop;
248         data->do_update = do_update;
249         data->progress = progress;
250
251         /* XXX annoying hack: needed to prevent data corruption when changing
252          * scene frame in separate threads
253          */
254         G.is_rendering = true;
255         BKE_spacedata_draw_locks(true);
256
257         G.is_break = false;
258
259         try {
260                 Scene *scene = data->scene;
261                 AbcExporter exporter(scene, data->filename, data->settings);
262
263                 const int orig_frame = CFRA;
264
265                 data->was_canceled = false;
266                 exporter(data->bmain, *data->progress, data->was_canceled);
267
268                 if (CFRA != orig_frame) {
269                         CFRA = orig_frame;
270
271                         BKE_scene_update_for_newframe(data->bmain->eval_ctx, data->bmain,
272                                                       scene, scene->lay);
273                 }
274         }
275         catch (const std::exception &e) {
276                 ABC_LOG(data->settings.logger) << "Abc Export error: " << e.what() << '\n';
277         }
278         catch (...) {
279                 ABC_LOG(data->settings.logger) << "Abc Export: unknown error...\n";
280         }
281 }
282
283 static void export_endjob(void *customdata)
284 {
285         ExportJobData *data = static_cast<ExportJobData *>(customdata);
286
287         if (data->was_canceled && BLI_exists(data->filename)) {
288                 BLI_delete(data->filename, false, false);
289         }
290
291         if (!data->settings.logger.empty()) {
292                 std::cerr << data->settings.logger;
293                 WM_report(RPT_ERROR, "Errors occured during the export, look in the console to know more...");
294         }
295
296         G.is_rendering = false;
297         BKE_spacedata_draw_locks(false);
298 }
299
300 void ABC_export(
301         Scene *scene,
302         bContext *C,
303         const char *filepath,
304         const struct AlembicExportParams *params)
305 {
306         ExportJobData *job = static_cast<ExportJobData *>(MEM_mallocN(sizeof(ExportJobData), "ExportJobData"));
307         job->scene = scene;
308         job->bmain = CTX_data_main(C);
309         BLI_strncpy(job->filename, filepath, 1024);
310
311         /* Alright, alright, alright....
312          *
313          * ExportJobData contains an ExportSettings containing a SimpleLogger.
314          *
315          * Since ExportJobData is a C-style struct dynamically allocated with
316          * MEM_mallocN (see above), its construtor is never called, therefore the
317          * ExportSettings constructor is not called which implies that the
318          * SimpleLogger one is not called either. SimpleLogger in turn does not call
319          * the constructor of its data members which ultimately means that its
320          * std::ostringstream member has a NULL pointer. To be able to properly use
321          * the stream's operator<<, the pointer needs to be set, therefore we have
322          * to properly construct everything. And this is done using the placement
323          * new operator as here below. It seems hackish, but I'm too lazy to
324          * do bigger refactor and maybe there is a better way which does not involve
325          * hardcore refactoring. */
326         new (&job->settings) ExportSettings();
327         job->settings.scene = job->scene;
328         job->settings.frame_start = params->frame_start;
329         job->settings.frame_end = params->frame_end;
330         job->settings.frame_step_xform = params->frame_step_xform;
331         job->settings.frame_step_shape = params->frame_step_shape;
332         job->settings.shutter_open = params->shutter_open;
333         job->settings.shutter_close = params->shutter_close;
334         job->settings.selected_only = params->selected_only;
335         job->settings.export_face_sets = params->face_sets;
336         job->settings.export_normals = params->normals;
337         job->settings.export_uvs = params->uvs;
338         job->settings.export_vcols = params->vcolors;
339         job->settings.export_hair = params->export_hair;
340         job->settings.export_particles = params->export_particles;
341         job->settings.apply_subdiv = params->apply_subdiv;
342         job->settings.flatten_hierarchy = params->flatten_hierarchy;
343         job->settings.visible_layers_only = params->visible_layers_only;
344         job->settings.renderable_only = params->renderable_only;
345         job->settings.use_subdiv_schema = params->use_subdiv_schema;
346         job->settings.export_ogawa = (params->compression_type == ABC_ARCHIVE_OGAWA);
347         job->settings.pack_uv = params->packuv;
348         job->settings.global_scale = params->global_scale;
349         job->settings.triangulate = params->triangulate;
350         job->settings.quad_method = params->quad_method;
351         job->settings.ngon_method = params->ngon_method;
352
353         if (job->settings.frame_start > job->settings.frame_end) {
354                 std::swap(job->settings.frame_start, job->settings.frame_end);
355         }
356
357         wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C),
358                                     CTX_wm_window(C),
359                                     job->scene,
360                                     "Alembic Export",
361                                     WM_JOB_PROGRESS,
362                                     WM_JOB_TYPE_ALEMBIC);
363
364         /* setup job */
365         WM_jobs_customdata_set(wm_job, job, MEM_freeN);
366         WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_FRAME, NC_SCENE | ND_FRAME);
367         WM_jobs_callbacks(wm_job, export_startjob, NULL, NULL, export_endjob);
368
369         WM_jobs_start(CTX_wm_manager(C), wm_job);
370 }
371
372 /* ********************** Import file ********************** */
373
374 /**
375  * Generates an AbcObjectReader for this Alembic object and its children.
376  *
377  * \param object The Alembic IObject to visit.
378  * \param readers The created AbcObjectReader * will be appended to this vector.
379  * \param settings Import settings, not used directly but passed to the
380  *                 AbcObjectReader subclass constructors.
381  * \param r_assign_as_parent Return parameter, contains a list of reader
382  *                 pointers, whose parent pointer should still be set.
383  *                 This is filled when this call to visit_object() didn't create
384  *                 a reader that should be the parent.
385  * \return A pair of boolean and reader pointer. The boolean indicates whether
386  *         this IObject claims its parent as part of the same object
387  *         (for example an IPolyMesh object would claim its parent, as the mesh
388  *         is interpreted as the object's data, and the parent IXform as its
389  *         Blender object). The pointer is the AbcObjectReader that represents
390  *         the IObject parameter.
391  *
392  * NOTE: this function is similar to gather_object_paths above, need to keep
393  * them in sync. */
394 static std::pair<bool, AbcObjectReader *> visit_object(
395         const IObject &object,
396         AbcObjectReader::ptr_vector &readers,
397         ImportSettings &settings,
398         AbcObjectReader::ptr_vector &r_assign_as_parent)
399 {
400         const std::string & full_name = object.getFullName();
401
402         if (!object.valid()) {
403                 std::cerr << "  - "
404                           << full_name
405                           << ": object is invalid, skipping it and all its children.\n";
406                 return std::make_pair(false, static_cast<AbcObjectReader *>(NULL));
407         }
408
409         /* The interpretation of data by the children determine the role of this
410          * object. This is especially important for Xform objects, as they can be
411          * either part of a Blender object or a Blender object (Empty) themselves.
412          */
413         size_t children_claiming_this_object = 0;
414         size_t num_children = object.getNumChildren();
415         AbcObjectReader::ptr_vector claiming_child_readers;
416         AbcObjectReader::ptr_vector nonclaiming_child_readers;
417         AbcObjectReader::ptr_vector assign_as_parent;
418         for (size_t i = 0; i < num_children; ++i) {
419                 const IObject ichild = object.getChild(i);
420
421                 /* TODO: When we only support C++11, use std::tie() instead. */
422                 std::pair<bool, AbcObjectReader *> child_result;
423                 child_result = visit_object(ichild, readers, settings, assign_as_parent);
424
425                 bool child_claims_this_object = child_result.first;
426                 AbcObjectReader *child_reader = child_result.second;
427
428                 if (child_reader == NULL) {
429                         BLI_assert(!child_claims_this_object);
430                 }
431                 else {
432                         if (child_claims_this_object) {
433                                 claiming_child_readers.push_back(child_reader);
434                         } else {
435                                 nonclaiming_child_readers.push_back(child_reader);
436                         }
437                 }
438
439                 children_claiming_this_object += child_claims_this_object ? 1 : 0;
440         }
441         BLI_assert(children_claiming_this_object == claiming_child_readers.size());
442
443         AbcObjectReader *reader = NULL;
444         const MetaData &md = object.getMetaData();
445         bool parent_is_part_of_this_object = false;
446
447         if (!object.getParent()) {
448                 /* The root itself is not an object we should import. */
449         }
450         else if (IXform::matches(md)) {
451                 bool create_empty;
452
453                 /* An xform can either be a Blender Object (if it contains a mesh, for
454                  * example), but it can also be an Empty. Its correct translation to
455                  * Blender's data model depends on its children. */
456
457                 /* Check whether or not this object is a Maya locator, which is
458                  * similar to empties used as parent object in Blender. */
459                 if (has_property(object.getProperties(), "locator")) {
460                         create_empty = true;
461                 }
462                 else {
463                         create_empty = claiming_child_readers.empty();
464                 }
465
466                 if (create_empty) {
467                         reader = new AbcEmptyReader(object, settings);
468                 }
469         }
470         else if (IPolyMesh::matches(md)) {
471                 reader = new AbcMeshReader(object, settings);
472                 parent_is_part_of_this_object = true;
473         }
474         else if (ISubD::matches(md)) {
475                 reader = new AbcSubDReader(object, settings);
476                 parent_is_part_of_this_object = true;
477         }
478         else if (INuPatch::matches(md)) {
479 #ifdef USE_NURBS
480                 /* TODO(kevin): importing cyclic NURBS from other software crashes
481                  * at the moment. This is due to the fact that NURBS in other
482                  * software have duplicated points which causes buffer overflows in
483                  * Blender. Need to figure out exactly how these points are
484                  * duplicated, in all cases (cyclic U, cyclic V, and cyclic UV).
485                  * Until this is fixed, disabling NURBS reading. */
486                 reader = new AbcNurbsReader(object, settings);
487                 parent_is_part_of_this_object = true;
488 #endif
489         }
490         else if (ICamera::matches(md)) {
491                 reader = new AbcCameraReader(object, settings);
492                 parent_is_part_of_this_object = true;
493         }
494         else if (IPoints::matches(md)) {
495                 reader = new AbcPointsReader(object, settings);
496                 parent_is_part_of_this_object = true;
497         }
498         else if (IMaterial::matches(md)) {
499                 /* Pass for now. */
500         }
501         else if (ILight::matches(md)) {
502                 /* Pass for now. */
503         }
504         else if (IFaceSet::matches(md)) {
505                 /* Pass, those are handled in the mesh reader. */
506         }
507         else if (ICurves::matches(md)) {
508                 reader = new AbcCurveReader(object, settings);
509                 parent_is_part_of_this_object = true;
510         }
511         else {
512                 std::cerr << "Alembic object " << full_name
513                           << " is of unsupported schema type '"
514                           << object.getMetaData().get("schemaObjTitle") << "'"
515                           << std::endl;
516         }
517
518         if (reader) {
519                 /* We have created a reader, which should imply that this object is
520                  * not claimed as part of any child Alembic object. */
521                 BLI_assert(claiming_child_readers.empty());
522
523                 readers.push_back(reader);
524                 reader->incref();
525
526                 AlembicObjectPath *abc_path = static_cast<AlembicObjectPath *>(
527                                                   MEM_callocN(sizeof(AlembicObjectPath), "AlembicObjectPath"));
528                 BLI_strncpy(abc_path->path, full_name.c_str(), PATH_MAX);
529                 BLI_addtail(&settings.cache_file->object_paths, abc_path);
530
531                 /* We can now assign this reader as parent for our children. */
532                 if (nonclaiming_child_readers.size() + assign_as_parent.size() > 0) {
533                         /* TODO: When we only support C++11, use for (a: b) instead. */
534                         BOOST_FOREACH(AbcObjectReader *child_reader, nonclaiming_child_readers) {
535                                 child_reader->parent_reader = reader;
536                         }
537                         BOOST_FOREACH(AbcObjectReader *child_reader, assign_as_parent) {
538                                 child_reader->parent_reader = reader;
539                         }
540                 }
541         }
542         else if (object.getParent()) {
543                 if (claiming_child_readers.size() > 0) {
544                         /* The first claiming child will serve just fine as parent to
545                          * our non-claiming children. Since all claiming children share
546                          * the same XForm, it doesn't really matter which one we pick. */
547                         AbcObjectReader *claiming_child = claiming_child_readers[0];
548                         BOOST_FOREACH(AbcObjectReader *child_reader, nonclaiming_child_readers) {
549                                 child_reader->parent_reader = claiming_child;
550                         }
551                         BOOST_FOREACH(AbcObjectReader *child_reader, assign_as_parent) {
552                                 child_reader->parent_reader = claiming_child;
553                         }
554                         /* Claiming children should have our parent set as their parent. */
555                         BOOST_FOREACH(AbcObjectReader *child_reader, claiming_child_readers) {
556                                 r_assign_as_parent.push_back(child_reader);
557                         }
558                 }
559                 else {
560                         /* This object isn't claimed by any child, and didn't produce
561                          * a reader. Odd situation, could be the top Alembic object, or
562                          * an unsupported Alembic schema. Delegate to our parent. */
563                         BOOST_FOREACH(AbcObjectReader *child_reader, claiming_child_readers) {
564                                 r_assign_as_parent.push_back(child_reader);
565                         }
566                         BOOST_FOREACH(AbcObjectReader *child_reader, nonclaiming_child_readers) {
567                                 r_assign_as_parent.push_back(child_reader);
568                         }
569                         BOOST_FOREACH(AbcObjectReader *child_reader, assign_as_parent) {
570                                 r_assign_as_parent.push_back(child_reader);
571                         }
572                 }
573         }
574
575         return std::make_pair(parent_is_part_of_this_object, reader);
576 }
577
578 enum {
579         ABC_NO_ERROR = 0,
580         ABC_ARCHIVE_FAIL,
581 };
582
583 struct ImportJobData {
584         Main *bmain;
585         Scene *scene;
586
587         char filename[1024];
588         ImportSettings settings;
589
590         std::vector<AbcObjectReader *> readers;
591
592         short *stop;
593         short *do_update;
594         float *progress;
595
596         char error_code;
597         bool was_cancelled;
598 };
599
600 ABC_INLINE bool is_mesh_and_strands(const IObject &object)
601 {
602         bool has_mesh = false;
603         bool has_curve = false;
604
605         for (int i = 0; i < object.getNumChildren(); ++i) {
606                 const IObject &child = object.getChild(i);
607
608                 if (!child.valid()) {
609                         continue;
610                 }
611
612                 const MetaData &md = child.getMetaData();
613
614                 if (IPolyMesh::matches(md)) {
615                         has_mesh = true;
616                 }
617                 else if (ISubD::matches(md)) {
618                         has_mesh = true;
619                 }
620                 else if (ICurves::matches(md)) {
621                         has_curve = true;
622                 }
623                 else if (IPoints::matches(md)) {
624                         has_curve = true;
625                 }
626         }
627
628         return has_mesh && has_curve;
629 }
630
631 static void import_startjob(void *user_data, short *stop, short *do_update, float *progress)
632 {
633         SCOPE_TIMER("Alembic import, objects reading and creation");
634
635         ImportJobData *data = static_cast<ImportJobData *>(user_data);
636
637         data->stop = stop;
638         data->do_update = do_update;
639         data->progress = progress;
640
641         ArchiveReader *archive = new ArchiveReader(data->filename);
642
643         if (!archive->valid()) {
644                 delete archive;
645                 data->error_code = ABC_ARCHIVE_FAIL;
646                 return;
647         }
648
649         CacheFile *cache_file = static_cast<CacheFile *>(BKE_cachefile_add(data->bmain, BLI_path_basename(data->filename)));
650
651         /* Decrement the ID ref-count because it is going to be incremented for each
652          * modifier and constraint that it will be attached to, so since currently
653          * it is not used by anyone, its use count will off by one. */
654         id_us_min(&cache_file->id);
655
656         cache_file->is_sequence = data->settings.is_sequence;
657         cache_file->scale = data->settings.scale;
658         cache_file->handle = handle_from_archive(archive);
659         BLI_strncpy(cache_file->filepath, data->filename, 1024);
660
661         data->settings.cache_file = cache_file;
662
663         *data->do_update = true;
664         *data->progress = 0.05f;
665
666         /* Parse Alembic Archive. */
667         AbcObjectReader::ptr_vector assign_as_parent;
668         visit_object(archive->getTop(), data->readers, data->settings, assign_as_parent);
669
670         /* There shouldn't be any orphans. */
671         BLI_assert(assign_as_parent.size() == 0);
672
673         if (G.is_break) {
674                 data->was_cancelled = true;
675                 return;
676         }
677
678         *data->do_update = true;
679         *data->progress = 0.1f;
680
681         /* Create objects and set scene frame range. */
682
683         const float size = static_cast<float>(data->readers.size());
684         size_t i = 0;
685
686         chrono_t min_time = std::numeric_limits<chrono_t>::max();
687         chrono_t max_time = std::numeric_limits<chrono_t>::min();
688
689         std::vector<AbcObjectReader *>::iterator iter;
690         for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
691                 AbcObjectReader *reader = *iter;
692
693                 if (reader->valid()) {
694                         reader->readObjectData(data->bmain, 0.0f);
695
696                         min_time = std::min(min_time, reader->minTime());
697                         max_time = std::max(max_time, reader->maxTime());
698                 }
699                 else {
700                         std::cerr << "Object " << reader->name() << " in Alembic file "
701                                   << data->filename << " is invalid.\n";
702                 }
703
704                 *data->progress = 0.1f + 0.3f * (++i / size);
705                 *data->do_update = true;
706
707                 if (G.is_break) {
708                         data->was_cancelled = true;
709                         return;
710                 }
711         }
712
713         if (data->settings.set_frame_range) {
714                 Scene *scene = data->scene;
715
716                 if (data->settings.is_sequence) {
717                         SFRA = data->settings.offset;
718                         EFRA = SFRA + (data->settings.sequence_len - 1);
719                         CFRA = SFRA;
720                 }
721                 else if (min_time < max_time) {
722                         SFRA = static_cast<int>(round(min_time * FPS));
723                         EFRA = static_cast<int>(round(max_time * FPS));
724                         CFRA = SFRA;
725                 }
726         }
727
728         /* Setup parenthood. */
729         for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
730                 const AbcObjectReader *reader = *iter;
731                 const AbcObjectReader *parent_reader = reader->parent_reader;
732                 Object *ob = reader->object();
733
734                 if (parent_reader == NULL) {
735                         ob->parent = NULL;
736                 }
737                 else {
738                         ob->parent = parent_reader->object();
739                 }
740         }
741
742         /* Setup transformations and constraints. */
743         i = 0;
744         for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
745                 AbcObjectReader *reader = *iter;
746                 reader->setupObjectTransform(0.0f);
747
748                 *data->progress = 0.7f + 0.3f * (++i / size);
749                 *data->do_update = true;
750
751                 if (G.is_break) {
752                         data->was_cancelled = true;
753                         return;
754                 }
755         }
756 }
757
758 static void import_endjob(void *user_data)
759 {
760         SCOPE_TIMER("Alembic import, cleanup");
761
762         ImportJobData *data = static_cast<ImportJobData *>(user_data);
763
764         std::vector<AbcObjectReader *>::iterator iter;
765
766         /* Delete objects on cancelation. */
767         if (data->was_cancelled) {
768                 for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
769                         Object *ob = (*iter)->object();
770
771                         /* It's possible that cancellation occured between the creation of
772                          * the reader and the creation of the Blender object. */
773                         if (ob == NULL) continue;
774
775                         BKE_libblock_free_us(data->bmain, ob);
776                 }
777         }
778         else {
779                 /* Add object to scene. */
780                 BKE_scene_base_deselect_all(data->scene);
781
782                 for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
783                         Object *ob = (*iter)->object();
784                         ob->lay = data->scene->lay;
785
786                         BKE_scene_base_add(data->scene, ob);
787
788                         DAG_id_tag_update_ex(data->bmain, &ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
789                 }
790
791                 DAG_relations_tag_update(data->bmain);
792         }
793
794         for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
795                 AbcObjectReader *reader = *iter;
796                 reader->decref();
797
798                 if (reader->refcount() == 0) {
799                         delete reader;
800                 }
801         }
802
803         switch (data->error_code) {
804                 default:
805                 case ABC_NO_ERROR:
806                         break;
807                 case ABC_ARCHIVE_FAIL:
808                         WM_report(RPT_ERROR, "Could not open Alembic archive for reading! See console for detail.");
809                         break;
810         }
811
812         WM_main_add_notifier(NC_SCENE | ND_FRAME, data->scene);
813 }
814
815 static void import_freejob(void *user_data)
816 {
817         ImportJobData *data = static_cast<ImportJobData *>(user_data);
818         delete data;
819 }
820
821 void ABC_import(bContext *C, const char *filepath, float scale, bool is_sequence, bool set_frame_range, int sequence_len, int offset, bool validate_meshes)
822 {
823         /* Using new here since MEM_* funcs do not call ctor to properly initialize
824          * data. */
825         ImportJobData *job = new ImportJobData();
826         job->bmain = CTX_data_main(C);
827         job->scene = CTX_data_scene(C);
828         BLI_strncpy(job->filename, filepath, 1024);
829
830         job->settings.scale = scale;
831         job->settings.is_sequence = is_sequence;
832         job->settings.set_frame_range = set_frame_range;
833         job->settings.sequence_len = sequence_len;
834         job->settings.offset = offset;
835         job->settings.validate_meshes = validate_meshes;
836         job->error_code = ABC_NO_ERROR;
837         job->was_cancelled = false;
838
839         G.is_break = false;
840
841         wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C),
842                                     CTX_wm_window(C),
843                                     job->scene,
844                                     "Alembic Import",
845                                     WM_JOB_PROGRESS,
846                                     WM_JOB_TYPE_ALEMBIC);
847
848         /* setup job */
849         WM_jobs_customdata_set(wm_job, job, import_freejob);
850         WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_FRAME, NC_SCENE | ND_FRAME);
851         WM_jobs_callbacks(wm_job, import_startjob, NULL, NULL, import_endjob);
852
853         WM_jobs_start(CTX_wm_manager(C), wm_job);
854 }
855
856 /* ************************************************************************** */
857
858 void ABC_get_transform(CacheReader *reader, float r_mat[4][4], float time, float scale)
859 {
860         if (!reader) {
861                 return;
862         }
863
864         AbcObjectReader *abc_reader = reinterpret_cast<AbcObjectReader *>(reader);
865
866         bool is_constant = false;
867         abc_reader->read_matrix(r_mat, time, scale, is_constant);
868 }
869
870 /* ************************************************************************** */
871
872 DerivedMesh *ABC_read_mesh(CacheReader *reader,
873                            Object *ob,
874                            DerivedMesh *dm,
875                            const float time,
876                            const char **err_str,
877                            int read_flag)
878 {
879         AbcObjectReader *abc_reader = reinterpret_cast<AbcObjectReader *>(reader);
880         IObject iobject = abc_reader->iobject();
881
882         if (!iobject.valid()) {
883                 *err_str = "Invalid object: verify object path";
884                 return NULL;
885         }
886
887         const ObjectHeader &header = iobject.getHeader();
888
889         if (IPolyMesh::matches(header)) {
890                 if (ob->type != OB_MESH) {
891                         *err_str = "Object type mismatch: object path points to a mesh!";
892                         return NULL;
893                 }
894
895                 return abc_reader->read_derivedmesh(dm, time, read_flag, err_str);
896         }
897         else if (ISubD::matches(header)) {
898                 if (ob->type != OB_MESH) {
899                         *err_str = "Object type mismatch: object path points to a subdivision mesh!";
900                         return NULL;
901                 }
902
903                 return abc_reader->read_derivedmesh(dm, time, read_flag, err_str);
904         }
905         else if (IPoints::matches(header)) {
906                 if (ob->type != OB_MESH) {
907                         *err_str = "Object type mismatch: object path points to a point cloud (requires a mesh object)!";
908                         return NULL;
909                 }
910
911                 return abc_reader->read_derivedmesh(dm, time, read_flag, err_str);
912         }
913         else if (ICurves::matches(header)) {
914                 if (ob->type != OB_CURVE) {
915                         *err_str = "Object type mismatch: object path points to a curve!";
916                         return NULL;
917                 }
918
919                 return abc_reader->read_derivedmesh(dm, time, read_flag, err_str);
920         }
921
922         *err_str = "Unsupported object type: verify object path"; // or poke developer
923         return NULL;
924 }
925
926 /* ************************************************************************** */
927
928 void CacheReader_free(CacheReader *reader)
929 {
930         AbcObjectReader *abc_reader = reinterpret_cast<AbcObjectReader *>(reader);
931         abc_reader->decref();
932
933         if (abc_reader->refcount() == 0) {
934                 delete abc_reader;
935         }
936 }
937
938 CacheReader *CacheReader_open_alembic_object(AbcArchiveHandle *handle, CacheReader *reader, Object *object, const char *object_path)
939 {
940         if (object_path[0] == '\0') {
941                 return reader;
942         }
943
944         ArchiveReader *archive = archive_from_handle(handle);
945
946         if (!archive || !archive->valid()) {
947                 return reader;
948         }
949
950         IObject iobject;
951         find_iobject(archive->getTop(), iobject, object_path);
952
953         if (reader) {
954                 CacheReader_free(reader);
955         }
956
957         ImportSettings settings;
958         AbcObjectReader *abc_reader = create_reader(iobject, settings);
959         abc_reader->object(object);
960         abc_reader->incref();
961
962         return reinterpret_cast<CacheReader *>(abc_reader);
963 }