Merge branch 'master' into blender2.8
[blender.git] / source / blender / alembic / intern / abc_exporter.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_exporter.h"
24
25 #include <cmath>
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 "DNA_camera_types.h"
39 #include "DNA_curve_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_modifier_types.h"
42 #include "DNA_object_types.h"
43 #include "DNA_scene_types.h"
44 #include "DNA_space_types.h"  /* for FILE_MAX */
45
46 #include "BLI_string.h"
47
48 #ifdef WIN32
49 /* needed for MSCV because of snprintf from BLI_string */
50 #  include "BLI_winstuff.h"
51 #endif
52
53 #include "BKE_anim.h"
54 #include "BKE_global.h"
55 #include "BKE_idprop.h"
56 #include "BKE_main.h"
57 #include "BKE_modifier.h"
58 #include "BKE_particle.h"
59 #include "BKE_scene.h"
60 }
61
62 using Alembic::Abc::TimeSamplingPtr;
63 using Alembic::Abc::OBox3dProperty;
64
65 /* ************************************************************************** */
66
67 ExportSettings::ExportSettings()
68     : scene(NULL)
69         , logger()
70     , selected_only(false)
71     , visible_layers_only(false)
72     , renderable_only(false)
73     , frame_start(1)
74     , frame_end(1)
75     , frame_step_xform(1)
76     , frame_step_shape(1)
77     , shutter_open(0.0)
78     , shutter_close(1.0)
79     , global_scale(1.0f)
80     , flatten_hierarchy(false)
81     , export_normals(false)
82     , export_uvs(false)
83     , export_vcols(false)
84     , export_face_sets(false)
85     , export_vweigths(false)
86     , apply_subdiv(false)
87     , use_subdiv_schema(false)
88     , export_child_hairs(true)
89     , export_ogawa(true)
90     , pack_uv(false)
91     , triangulate(false)
92     , quad_method(0)
93     , ngon_method(0)
94     , do_convert_axis(false)
95 {}
96
97 static bool object_is_smoke_sim(Object *ob)
98 {
99         ModifierData *md = modifiers_findByType(ob, eModifierType_Smoke);
100
101         if (md) {
102                 SmokeModifierData *smd = reinterpret_cast<SmokeModifierData *>(md);
103                 return (smd->type == MOD_SMOKE_TYPE_DOMAIN);
104         }
105
106         return false;
107 }
108
109 static bool object_is_shape(Object *ob)
110 {
111         switch (ob->type) {
112                 case OB_MESH:
113                         if (object_is_smoke_sim(ob)) {
114                                 return false;
115                         }
116
117                         return true;
118                 case OB_CURVE:
119                 case OB_SURF:
120                 case OB_CAMERA:
121                         return true;
122                 default:
123                         return false;
124         }
125 }
126
127
128 /**
129  * Returns whether this object should be exported into the Alembic file.
130  *
131  * @param settings export settings, used for options like 'selected only'.
132  * @param ob the object's base in question.
133  * @param is_duplicated normally false; true when the object is instanced
134  *                      into the scene by a dupli-object (e.g. part of a
135  *                      dupligroup). This ignores selection and layer
136  *                      visibility, and assumes that the dupli-object itself
137  *                      (e.g. the group-instantiating empty) is exported.
138  */
139 static bool export_object(const ExportSettings * const settings, const Base * const ob_base,
140                           bool is_duplicated)
141 {
142         if (!is_duplicated) {
143                 /* These two tests only make sense when the object isn't being instanced
144                  * into the scene. When it is, its exportability is determined by
145                  * its dupli-object and the DupliObject::no_draw property. */
146                 if (settings->selected_only && !object_selected(ob_base)) {
147                         return false;
148                 }
149                 // FIXME Sybren: handle these cleanly (maybe just remove code), now using active scene layer instead.
150                 if (settings->visible_layers_only && (ob_base->flag & BASE_VISIBLED) == 0) {
151                         return false;
152                 }
153         }
154
155         //      if (settings->renderable_only && (ob->restrictflag & OB_RESTRICT_RENDER)) {
156         //              return false;
157         //      }
158
159         return true;
160 }
161
162 /* ************************************************************************** */
163
164 AbcExporter::AbcExporter(Scene *scene, const char *filename, ExportSettings &settings)
165     : m_settings(settings)
166     , m_filename(filename)
167     , m_trans_sampling_index(0)
168     , m_shape_sampling_index(0)
169     , m_scene(scene)
170     , m_writer(NULL)
171 {}
172
173 AbcExporter::~AbcExporter()
174 {
175         /* Free xforms map */
176         m_xforms_type::iterator it_x, e_x;
177         for (it_x = m_xforms.begin(), e_x = m_xforms.end(); it_x != e_x; ++it_x) {
178                 delete it_x->second;
179         }
180
181         /* Free shapes vector */
182         for (int i = 0, e = m_shapes.size(); i != e; ++i) {
183                 delete m_shapes[i];
184         }
185
186         delete m_writer;
187 }
188
189 void AbcExporter::getShutterSamples(double step, bool time_relative,
190                                     std::vector<double> &samples)
191 {
192         samples.clear();
193
194         const double time_factor = time_relative ? m_scene->r.frs_sec : 1.0;
195         const double shutter_open = m_settings.shutter_open;
196         const double shutter_close = m_settings.shutter_close;
197
198         /* sample all frame */
199         if (shutter_open == 0.0 && shutter_close == 1.0) {
200                 for (double t = 0.0; t < 1.0; t += step) {
201                         samples.push_back((t + m_settings.frame_start) / time_factor);
202                 }
203         }
204         else {
205                 /* sample between shutter open & close */
206                 const int nsamples = static_cast<int>(std::max((1.0 / step) - 1.0, 1.0));
207                 const double time_inc = (shutter_close - shutter_open) / nsamples;
208
209                 for (double t = shutter_open; t <= shutter_close; t += time_inc) {
210                         samples.push_back((t + m_settings.frame_start) / time_factor);
211                 }
212         }
213 }
214
215 Alembic::Abc::TimeSamplingPtr AbcExporter::createTimeSampling(double step)
216 {
217         TimeSamplingPtr time_sampling;
218         std::vector<double> samples;
219
220         if (m_settings.frame_start == m_settings.frame_end) {
221                 time_sampling.reset(new Alembic::Abc::TimeSampling());
222                 return time_sampling;
223         }
224
225         getShutterSamples(step, true, samples);
226
227         Alembic::Abc::TimeSamplingType ts(static_cast<uint32_t>(samples.size()), 1.0 / m_scene->r.frs_sec);
228         time_sampling.reset(new Alembic::Abc::TimeSampling(ts, samples));
229
230         return time_sampling;
231 }
232
233 void AbcExporter::getFrameSet(double step, std::set<double> &frames)
234 {
235         frames.clear();
236
237         std::vector<double> shutter_samples;
238
239         getShutterSamples(step, false, shutter_samples);
240
241         for (double frame = m_settings.frame_start; frame <= m_settings.frame_end; frame += 1.0) {
242                 for (int j = 0, e = shutter_samples.size(); j < e; ++j) {
243                         frames.insert(frame + shutter_samples[j]);
244                 }
245         }
246 }
247
248 void AbcExporter::operator()(Main *bmain, float &progress, bool &was_canceled)
249 {
250         std::string scene_name;
251
252         if (bmain->name[0] != '\0') {
253                 char scene_file_name[FILE_MAX];
254                 BLI_strncpy(scene_file_name, bmain->name, FILE_MAX);
255                 scene_name = scene_file_name;
256         }
257         else {
258                 scene_name = "untitled";
259         }
260
261         Scene *scene = m_scene;
262         const double fps = FPS;
263         char buf[16];
264         snprintf(buf, 15, "%f", fps);
265         const std::string str_fps = buf;
266
267         Alembic::AbcCoreAbstract::MetaData md;
268         md.set("FramesPerTimeUnit", str_fps);
269
270         m_writer = new ArchiveWriter(m_filename, scene_name.c_str(), m_settings.export_ogawa, md);
271
272         /* Create time samplings for transforms and shapes. */
273
274         TimeSamplingPtr trans_time = createTimeSampling(m_settings.frame_step_xform);
275
276         m_trans_sampling_index = m_writer->archive().addTimeSampling(*trans_time);
277
278         TimeSamplingPtr shape_time;
279
280         if ((m_settings.frame_step_shape == m_settings.frame_step_xform) ||
281             (m_settings.frame_start == m_settings.frame_end))
282         {
283                 shape_time = trans_time;
284                 m_shape_sampling_index = m_trans_sampling_index;
285         }
286         else {
287                 shape_time = createTimeSampling(m_settings.frame_step_shape);
288                 m_shape_sampling_index = m_writer->archive().addTimeSampling(*shape_time);
289         }
290
291         OBox3dProperty archive_bounds_prop = Alembic::AbcGeom::CreateOArchiveBounds(m_writer->archive(), m_trans_sampling_index);
292
293         if (m_settings.flatten_hierarchy) {
294                 createTransformWritersFlat();
295         }
296         else {
297                 createTransformWritersHierarchy(bmain->eval_ctx);
298         }
299
300         createShapeWriters(bmain->eval_ctx);
301
302         /* Make a list of frames to export. */
303
304         std::set<double> xform_frames;
305         getFrameSet(m_settings.frame_step_xform, xform_frames);
306
307         std::set<double> shape_frames;
308         getFrameSet(m_settings.frame_step_shape, shape_frames);
309
310         /* Merge all frames needed. */
311
312         std::set<double> frames(xform_frames);
313         frames.insert(shape_frames.begin(), shape_frames.end());
314
315         /* Export all frames. */
316
317         std::set<double>::const_iterator begin = frames.begin();
318         std::set<double>::const_iterator end = frames.end();
319
320         const float size = static_cast<float>(frames.size());
321         size_t i = 0;
322
323         for (; begin != end; ++begin) {
324                 progress = (++i / size);
325
326                 if (G.is_break) {
327                         was_canceled = true;
328                         break;
329                 }
330
331                 const double frame = *begin;
332
333                 /* 'frame' is offset by start frame, so need to cancel the offset. */
334                 setCurrentFrame(bmain, frame - m_settings.frame_start);
335
336                 if (shape_frames.count(frame) != 0) {
337                         for (int i = 0, e = m_shapes.size(); i != e; ++i) {
338                                 m_shapes[i]->write();
339                         }
340                 }
341
342                 if (xform_frames.count(frame) == 0) {
343                         continue;
344                 }
345
346                 m_xforms_type::iterator xit, xe;
347                 for (xit = m_xforms.begin(), xe = m_xforms.end(); xit != xe; ++xit) {
348                         xit->second->write();
349                 }
350
351                 /* Save the archive 's bounding box. */
352                 Imath::Box3d bounds;
353
354                 for (xit = m_xforms.begin(), xe = m_xforms.end(); xit != xe; ++xit) {
355                         Imath::Box3d box = xit->second->bounds();
356                         bounds.extendBy(box);
357                 }
358
359                 archive_bounds_prop.set(bounds);
360         }
361 }
362
363 void AbcExporter::createTransformWritersHierarchy(EvaluationContext *eval_ctx)
364 {
365         for (Base *base = static_cast<Base *>(m_settings.sl->object_bases.first); base; base = base->next) {
366                 Object *ob = base->object;
367
368                 if (export_object(&m_settings, base, false)) {
369                         switch (ob->type) {
370                                 case OB_LAMP:
371                                 case OB_LATTICE:
372                                 case OB_MBALL:
373                                 case OB_SPEAKER:
374                                         /* We do not export transforms for objects of these classes. */
375                                         break;
376
377                                 default:
378                                         exploreTransform(eval_ctx, base, ob->parent, NULL);
379                         }
380                 }
381         }
382 }
383
384 void AbcExporter::createTransformWritersFlat()
385 {
386         for (Base *base = static_cast<Base *>(m_settings.sl->object_bases.first); base; base = base->next) {
387                 Object *ob = base->object;
388
389                 if (export_object(&m_settings, base, false) && object_is_shape(ob)) {
390                         std::string name = get_id_name(ob);
391                         m_xforms[name] = new AbcTransformWriter(
392                                              ob, m_writer->archive().getTop(), NULL,
393                                              m_trans_sampling_index, m_settings);
394                 }
395         }
396 }
397
398 void AbcExporter::exploreTransform(EvaluationContext *eval_ctx, Base *ob_base, Object *parent, Object *dupliObParent)
399 {
400         Object *ob = ob_base->object;
401
402         /* If an object isn't exported itself, its duplilist shouldn't be
403          * exported either. */
404         if (!export_object(&m_settings, ob_base, dupliObParent != NULL)) {
405                 return;
406         }
407
408         if (object_is_shape(ob)) {
409                 createTransformWriter(ob, parent, dupliObParent);
410         }
411
412         ListBase *lb = object_duplilist(eval_ctx, m_scene, ob);
413
414         if (lb) {
415                 Base fake_base = *ob_base;  // copy flags (like selection state) from the real object.
416                 fake_base.next = fake_base.prev = NULL;
417
418                 DupliObject *link = static_cast<DupliObject *>(lb->first);
419                 Object *dupli_ob = NULL;
420                 Object *dupli_parent = NULL;
421                 
422                 for (; link; link = link->next) {
423                         /* This skips things like custom bone shapes. */
424                         if (m_settings.renderable_only && link->no_draw) {
425                                 continue;
426                         }
427
428                         if (link->type == OB_DUPLIGROUP) {
429                                 dupli_ob = link->ob;
430                                 dupli_parent = (dupli_ob->parent) ? dupli_ob->parent : ob;
431
432                                 fake_base.object = dupli_ob;
433                                 exploreTransform(eval_ctx, &fake_base, dupli_parent, ob);
434                         }
435                 }
436         }
437
438         free_object_duplilist(lb);
439 }
440
441 AbcTransformWriter * AbcExporter::createTransformWriter(Object *ob, Object *parent, Object *dupliObParent)
442 {
443         const std::string name = get_object_dag_path_name(ob, dupliObParent);
444
445         /* An object should not be its own parent, or we'll get infinite loops. */
446         BLI_assert(ob != parent);
447         BLI_assert(ob != dupliObParent);
448
449         /* check if we have already created a transform writer for this object */
450         AbcTransformWriter *my_writer = getXForm(name);
451         if (my_writer != NULL){
452                 return my_writer;
453         }
454
455         AbcTransformWriter *parent_writer = NULL;
456         Alembic::Abc::OObject alembic_parent;
457
458         if (parent) {
459                 /* Since there are so many different ways to find parents (as evident
460                  * in the number of conditions below), we can't really look up the
461                  * parent by name. We'll just call createTransformWriter(), which will
462                  * return the parent's AbcTransformWriter pointer. */
463                 if (parent->parent) {
464                         parent_writer = createTransformWriter(parent, parent->parent, dupliObParent);
465                 }
466                 else if (parent == dupliObParent) {
467                         if (dupliObParent->parent == NULL) {
468                                 parent_writer = createTransformWriter(parent, NULL, NULL);
469                         }
470                         else {
471                                 parent_writer = createTransformWriter(parent, dupliObParent->parent, dupliObParent->parent);
472                         }
473                 }
474                 else {
475                         parent_writer = createTransformWriter(parent, dupliObParent, dupliObParent);
476                 }
477
478                 BLI_assert(parent_writer);
479                 alembic_parent = parent_writer->alembicXform();
480         }
481         else {
482                 /* Parentless objects still have the "top object" as parent
483                  * in Alembic. */
484                 alembic_parent = m_writer->archive().getTop();
485         }
486
487         my_writer = new AbcTransformWriter(ob, alembic_parent, parent_writer,
488                                            m_trans_sampling_index, m_settings);
489         m_xforms[name] = my_writer;
490         return my_writer;
491 }
492
493 void AbcExporter::createShapeWriters(EvaluationContext *eval_ctx)
494 {
495         for (Base *base = static_cast<Base *>(m_settings.sl->object_bases.first); base; base = base->next) {
496                 exploreObject(eval_ctx, base, NULL);
497         }
498 }
499
500 void AbcExporter::exploreObject(EvaluationContext *eval_ctx, Base *ob_base, Object *dupliObParent)
501 {
502         /* If an object isn't exported itself, its duplilist shouldn't be
503          * exported either. */
504         if (!export_object(&m_settings, ob_base, dupliObParent != NULL)) {
505                 return;
506         }
507
508         createShapeWriter(ob_base, dupliObParent);
509         
510         Object *ob = ob_base->object;
511         ListBase *lb = object_duplilist(eval_ctx, m_scene, ob);
512
513         if (lb) {
514                 Base fake_base = *ob_base;  // copy flags (like selection state) from the real object.
515                 fake_base.next = fake_base.prev = NULL;
516
517                 DupliObject *link = static_cast<DupliObject *>(lb->first);
518
519                 for (; link; link = link->next) {
520                         /* This skips things like custom bone shapes. */
521                         if (m_settings.renderable_only && link->no_draw) {
522                                 continue;
523                         }
524                         if (link->type == OB_DUPLIGROUP) {
525                                 fake_base.object = link->ob;
526                                 exploreObject(eval_ctx, &fake_base, ob);
527                         }
528                 }
529         }
530
531         free_object_duplilist(lb);
532 }
533
534 void AbcExporter::createShapeWriter(Base *ob_base, Object *dupliObParent)
535 {
536         Object *ob = ob_base->object;
537
538         if (!object_is_shape(ob)) {
539                 return;
540         }
541
542         std::string name;
543
544         if (m_settings.flatten_hierarchy) {
545                 name = get_id_name(ob);
546         }
547         else {
548                 name = get_object_dag_path_name(ob, dupliObParent);
549         }
550         
551         AbcTransformWriter *xform = getXForm(name);
552
553         if (!xform) {
554                 ABC_LOG(m_settings.logger) << __func__ << ": xform " << name << " is NULL\n";
555                 return;
556         }
557
558         ParticleSystem *psys = static_cast<ParticleSystem *>(ob->particlesystem.first);
559
560         for (; psys; psys = psys->next) {
561                 if (!psys_check_enabled(ob, psys, G.is_rendering) || !psys->part) {
562                         continue;
563                 }
564
565                 if (psys->part->type == PART_HAIR) {
566                         m_settings.export_child_hairs = true;
567                         m_shapes.push_back(new AbcHairWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
568                 }
569                 else if (psys->part->type == PART_EMITTER) {
570                         m_shapes.push_back(new AbcPointsWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
571                 }
572         }
573
574         switch (ob->type) {
575                 case OB_MESH:
576                 {
577                         Mesh *me = static_cast<Mesh *>(ob->data);
578
579                         if (!me || me->totvert == 0) {
580                                 return;
581                         }
582
583                         m_shapes.push_back(new AbcMeshWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings));
584                         break;
585                 }
586                 case OB_SURF:
587                 {
588                         Curve *cu = static_cast<Curve *>(ob->data);
589
590                         if (!cu) {
591                                 return;
592                         }
593
594                         m_shapes.push_back(new AbcNurbsWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings));
595                         break;
596                 }
597                 case OB_CURVE:
598                 {
599                         Curve *cu = static_cast<Curve *>(ob->data);
600
601                         if (!cu) {
602                                 return;
603                         }
604
605                         m_shapes.push_back(new AbcCurveWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings));
606                         break;
607                 }
608                 case OB_CAMERA:
609                 {
610                         Camera *cam = static_cast<Camera *>(ob->data);
611
612                         if (cam->type == CAM_PERSP) {
613                                 m_shapes.push_back(new AbcCameraWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings));
614                         }
615
616                         break;
617                 }
618         }
619 }
620
621 AbcTransformWriter *AbcExporter::getXForm(const std::string &name)
622 {
623         std::map<std::string, AbcTransformWriter *>::iterator it = m_xforms.find(name);
624
625         if (it == m_xforms.end()) {
626                 return NULL;
627         }
628
629         return it->second;
630 }
631
632 void AbcExporter::setCurrentFrame(Main *bmain, double t)
633 {
634         m_scene->r.cfra = static_cast<int>(t);
635         m_scene->r.subframe = static_cast<float>(t) - m_scene->r.cfra;
636         BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, m_scene);
637 }