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