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