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