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, const char *filename, ExportSettings &settings)
172     : m_bmain(bmain)
173     , m_settings(settings)
174     , m_filename(filename)
175     , m_trans_sampling_index(0)
176     , m_shape_sampling_index(0)
177     , m_eval_ctx(eval_ctx)
178     , m_scene(scene)
179     , m_writer(NULL)
180 {}
181
182 AbcExporter::~AbcExporter()
183 {
184         /* Free xforms map */
185         m_xforms_type::iterator it_x, e_x;
186         for (it_x = m_xforms.begin(), e_x = m_xforms.end(); it_x != e_x; ++it_x) {
187                 delete it_x->second;
188         }
189
190         /* Free shapes vector */
191         for (int i = 0, e = m_shapes.size(); i != e; ++i) {
192                 delete m_shapes[i];
193         }
194
195         delete m_writer;
196 }
197
198 void AbcExporter::getShutterSamples(unsigned int nr_of_samples,
199                                     bool time_relative,
200                                     std::vector<double> &samples)
201 {
202         Scene *scene = m_scene; /* for use in the FPS macro */
203         samples.clear();
204
205         unsigned int frame_offset = time_relative ? m_settings.frame_start : 0;
206         double time_factor = time_relative ? FPS : 1.0;
207         double shutter_open = m_settings.shutter_open;
208         double shutter_close = m_settings.shutter_close;
209         double time_inc = (shutter_close - shutter_open) / nr_of_samples;
210
211         /* sample between shutter open & close */
212         for (int sample=0; sample < nr_of_samples; ++sample) {
213                 double sample_time = shutter_open + time_inc * sample;
214                 double time = (frame_offset + sample_time) / time_factor;
215
216                 samples.push_back(time);
217         }
218 }
219
220 Alembic::Abc::TimeSamplingPtr AbcExporter::createTimeSampling(double step)
221 {
222         std::vector<double> samples;
223
224         if (m_settings.frame_start == m_settings.frame_end) {
225                 return TimeSamplingPtr(new Alembic::Abc::TimeSampling());
226         }
227
228         getShutterSamples(step, true, samples);
229
230         Alembic::Abc::TimeSamplingType ts(
231                     static_cast<uint32_t>(samples.size()),
232                     1.0 / m_scene->r.frs_sec);
233
234         return TimeSamplingPtr(new Alembic::Abc::TimeSampling(ts, samples));
235 }
236
237 void AbcExporter::getFrameSet(unsigned int nr_of_samples,
238                               std::set<double> &frames)
239 {
240         frames.clear();
241
242         std::vector<double> shutter_samples;
243
244         getShutterSamples(nr_of_samples, false, shutter_samples);
245
246         for (double frame = m_settings.frame_start; frame <= m_settings.frame_end; frame += 1.0) {
247                 for (size_t j = 0; j < nr_of_samples; ++j) {
248                         frames.insert(frame + shutter_samples[j]);
249                 }
250         }
251 }
252
253 void AbcExporter::operator()(Main *bmain, float &progress, bool &was_canceled)
254 {
255         std::string scene_name;
256
257         if (bmain->name[0] != '\0') {
258                 char scene_file_name[FILE_MAX];
259                 BLI_strncpy(scene_file_name, bmain->name, FILE_MAX);
260                 scene_name = scene_file_name;
261         }
262         else {
263                 scene_name = "untitled";
264         }
265
266         Scene *scene = m_scene;
267         const double fps = FPS;
268         char buf[16];
269         snprintf(buf, 15, "%f", fps);
270         const std::string str_fps = buf;
271
272         Alembic::AbcCoreAbstract::MetaData md;
273         md.set("FramesPerTimeUnit", str_fps);
274
275         m_writer = new ArchiveWriter(m_filename, scene_name.c_str(), m_settings.export_ogawa, md);
276
277         /* Create time samplings for transforms and shapes. */
278
279         TimeSamplingPtr trans_time = createTimeSampling(m_settings.frame_samples_xform);
280
281         m_trans_sampling_index = m_writer->archive().addTimeSampling(*trans_time);
282
283         TimeSamplingPtr shape_time;
284
285         if ((m_settings.frame_samples_shape == m_settings.frame_samples_xform) ||
286             (m_settings.frame_start == m_settings.frame_end))
287         {
288                 shape_time = trans_time;
289                 m_shape_sampling_index = m_trans_sampling_index;
290         }
291         else {
292                 shape_time = createTimeSampling(m_settings.frame_samples_shape);
293                 m_shape_sampling_index = m_writer->archive().addTimeSampling(*shape_time);
294         }
295
296         OBox3dProperty archive_bounds_prop = Alembic::AbcGeom::CreateOArchiveBounds(m_writer->archive(), m_trans_sampling_index);
297
298         createTransformWritersHierarchy(bmain->eval_ctx);
299         createShapeWriters(bmain->eval_ctx);
300
301         /* Make a list of frames to export. */
302
303         std::set<double> xform_frames;
304         getFrameSet(m_settings.frame_samples_xform, xform_frames);
305
306         std::set<double> shape_frames;
307         getFrameSet(m_settings.frame_samples_shape, shape_frames);
308
309         /* Merge all frames needed. */
310         std::set<double> frames(xform_frames);
311         frames.insert(shape_frames.begin(), shape_frames.end());
312
313         /* Export all frames. */
314
315         std::set<double>::const_iterator begin = frames.begin();
316         std::set<double>::const_iterator end = frames.end();
317
318         const float size = static_cast<float>(frames.size());
319         size_t i = 0;
320
321         for (; begin != end; ++begin) {
322                 progress = (++i / size);
323
324                 if (G.is_break) {
325                         was_canceled = true;
326                         break;
327                 }
328
329                 const double frame = *begin;
330
331                 /* 'frame' is offset by start frame, so need to cancel the offset. */
332                 setCurrentFrame(bmain, frame);
333
334                 if (shape_frames.count(frame) != 0) {
335                         for (int i = 0, e = m_shapes.size(); i != e; ++i) {
336                                 m_shapes[i]->write();
337                         }
338                 }
339
340                 if (xform_frames.count(frame) == 0) {
341                         continue;
342                 }
343
344                 m_xforms_type::iterator xit, xe;
345                 for (xit = m_xforms.begin(), xe = m_xforms.end(); xit != xe; ++xit) {
346                         xit->second->write();
347                 }
348
349                 /* Save the archive 's bounding box. */
350                 Imath::Box3d bounds;
351
352                 for (xit = m_xforms.begin(), xe = m_xforms.end(); xit != xe; ++xit) {
353                         Imath::Box3d box = xit->second->bounds();
354                         bounds.extendBy(box);
355                 }
356
357                 archive_bounds_prop.set(bounds);
358         }
359 }
360
361 void AbcExporter::createTransformWritersHierarchy(EvaluationContext *eval_ctx)
362 {
363         for (Base *base = static_cast<Base *>(m_settings.sl->object_bases.first); base; base = base->next) {
364                 Object *ob = base->object;
365
366                 if (export_object(&m_settings, base, false)) {
367                         switch (ob->type) {
368                                 case OB_LAMP:
369                                 case OB_LATTICE:
370                                 case OB_SPEAKER:
371                                         /* We do not export transforms for objects of these classes. */
372                                         break;
373                                 default:
374                                         exploreTransform(eval_ctx, base, ob->parent, NULL);
375                         }
376                 }
377         }
378 }
379
380 void AbcExporter::exploreTransform(EvaluationContext *eval_ctx, Base *ob_base, Object *parent, Object *dupliObParent)
381 {
382         Object *ob = ob_base->object;
383
384         /* If an object isn't exported itself, its duplilist shouldn't be
385          * exported either. */
386         if (!export_object(&m_settings, ob_base, dupliObParent != NULL)) {
387                 return;
388         }
389
390         if (object_type_is_exportable(m_scene, ob)) {
391                 createTransformWriter(eval_ctx, ob, parent, dupliObParent);
392         }
393
394         ListBase *lb = object_duplilist(eval_ctx, m_scene, ob);
395
396         if (lb) {
397                 Base fake_base = *ob_base;  // copy flags (like selection state) from the real object.
398                 fake_base.next = fake_base.prev = NULL;
399
400                 DupliObject *link = static_cast<DupliObject *>(lb->first);
401                 Object *dupli_ob = NULL;
402                 Object *dupli_parent = NULL;
403                 
404                 for (; link; link = link->next) {
405                         /* This skips things like custom bone shapes. */
406                         if (m_settings.renderable_only && link->no_draw) {
407                                 continue;
408                         }
409
410                         if (link->type == OB_DUPLIGROUP) {
411                                 dupli_ob = link->ob;
412                                 dupli_parent = (dupli_ob->parent) ? dupli_ob->parent : ob;
413
414                                 fake_base.object = dupli_ob;
415                                 exploreTransform(eval_ctx, &fake_base, dupli_parent, ob);
416                         }
417                 }
418         }
419
420         free_object_duplilist(lb);
421 }
422
423 AbcTransformWriter * AbcExporter::createTransformWriter(EvaluationContext *eval_ctx, Object *ob, Object *parent, Object *dupliObParent)
424 {
425         /* An object should not be its own parent, or we'll get infinite loops. */
426         BLI_assert(ob != parent);
427         BLI_assert(ob != dupliObParent);
428
429         std::string name;
430         if (m_settings.flatten_hierarchy) {
431                 name = get_id_name(ob);
432         }
433         else {
434                 name = get_object_dag_path_name(ob, dupliObParent);
435         }
436
437         /* check if we have already created a transform writer for this object */
438         AbcTransformWriter *my_writer = getXForm(name);
439         if (my_writer != NULL) {
440                 return my_writer;
441         }
442
443         AbcTransformWriter *parent_writer = NULL;
444         Alembic::Abc::OObject alembic_parent;
445
446         if (m_settings.flatten_hierarchy || parent == NULL) {
447                 /* Parentless objects still have the "top object" as parent
448                  * in Alembic. */
449                 alembic_parent = m_writer->archive().getTop();
450         }
451         else {
452                 /* Since there are so many different ways to find parents (as evident
453                  * in the number of conditions below), we can't really look up the
454                  * parent by name. We'll just call createTransformWriter(), which will
455                  * return the parent's AbcTransformWriter pointer. */
456                 if (parent->parent) {
457                         if (parent == dupliObParent) {
458                                 parent_writer = createTransformWriter(eval_ctx, parent, parent->parent, NULL);
459                         }
460                         else {
461                                 parent_writer = createTransformWriter(eval_ctx, parent, parent->parent, dupliObParent);
462                         }
463                 }
464                 else if (parent == dupliObParent) {
465                         if (dupliObParent->parent == NULL) {
466                                 parent_writer = createTransformWriter(eval_ctx, parent, NULL, NULL);
467                         }
468                         else {
469                                 parent_writer = createTransformWriter(eval_ctx, parent, dupliObParent->parent, dupliObParent->parent);
470                         }
471                 }
472                 else {
473                         parent_writer = createTransformWriter(eval_ctx, parent, dupliObParent, dupliObParent);
474                 }
475
476                 BLI_assert(parent_writer);
477                 alembic_parent = parent_writer->alembicXform();
478         }
479
480         my_writer = new AbcTransformWriter(eval_ctx, ob, alembic_parent, parent_writer,
481                                            m_trans_sampling_index, m_settings);
482
483         /* When flattening, the matrix of the dupliobject has to be added. */
484         if (m_settings.flatten_hierarchy && dupliObParent) {
485                 my_writer->m_proxy_from = dupliObParent;
486         }
487
488         m_xforms[name] = my_writer;
489         return my_writer;
490 }
491
492 void AbcExporter::createShapeWriters(EvaluationContext *eval_ctx)
493 {
494         for (Base *base = static_cast<Base *>(m_settings.sl->object_bases.first); base; base = base->next) {
495                 exploreObject(eval_ctx, base, NULL);
496         }
497 }
498
499 void AbcExporter::exploreObject(EvaluationContext *eval_ctx, Base *ob_base, Object *dupliObParent)
500 {
501         /* If an object isn't exported itself, its duplilist shouldn't be
502          * exported either. */
503         if (!export_object(&m_settings, ob_base, dupliObParent != NULL)) {
504                 return;
505         }
506
507         createShapeWriter(ob_base, dupliObParent);
508         
509         Object *ob = ob_base->object;
510         ListBase *lb = object_duplilist(eval_ctx, m_scene, ob);
511
512         if (lb) {
513                 Base fake_base = *ob_base;  // copy flags (like selection state) from the real object.
514                 fake_base.next = fake_base.prev = NULL;
515
516                 DupliObject *link = static_cast<DupliObject *>(lb->first);
517
518                 for (; link; link = link->next) {
519                         /* This skips things like custom bone shapes. */
520                         if (m_settings.renderable_only && link->no_draw) {
521                                 continue;
522                         }
523                         if (link->type == OB_DUPLIGROUP) {
524                                 fake_base.object = link->ob;
525                                 exploreObject(eval_ctx, &fake_base, ob);
526                         }
527                 }
528         }
529
530         free_object_duplilist(lb);
531 }
532
533 void AbcExporter::createParticleSystemsWriters(Object *ob, AbcTransformWriter *xform)
534 {
535         if (!m_settings.export_hair && !m_settings.export_particles) {
536                 return;
537         }
538
539         ParticleSystem *psys = static_cast<ParticleSystem *>(ob->particlesystem.first);
540
541         for (; psys; psys = psys->next) {
542                 if (!psys_check_enabled(ob, psys, G.is_rendering) || !psys->part) {
543                         continue;
544                 }
545
546                 if (m_settings.export_hair && psys->part->type == PART_HAIR) {
547                         m_settings.export_child_hairs = true;
548                         m_shapes.push_back(new AbcHairWriter(m_eval_ctx, m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
549                 }
550                 else if (m_settings.export_particles && psys->part->type == PART_EMITTER) {
551                         m_shapes.push_back(new AbcPointsWriter(m_eval_ctx, m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
552                 }
553         }
554 }
555
556 void AbcExporter::createShapeWriter(Base *ob_base, Object *dupliObParent)
557 {
558         Object *ob = ob_base->object;
559
560         if (!object_type_is_exportable(m_scene, ob)) {
561                 return;
562         }
563
564         std::string name;
565
566         if (m_settings.flatten_hierarchy) {
567                 name = get_id_name(ob);
568         }
569         else {
570                 name = get_object_dag_path_name(ob, dupliObParent);
571         }
572         
573         AbcTransformWriter *xform = getXForm(name);
574
575         if (!xform) {
576                 ABC_LOG(m_settings.logger) << __func__ << ": xform " << name << " is NULL\n";
577                 return;
578         }
579
580         createParticleSystemsWriters(ob, xform);
581
582         switch (ob->type) {
583                 case OB_MESH:
584                 {
585                         Mesh *me = static_cast<Mesh *>(ob->data);
586
587                         if (!me) {
588                                 return;
589                         }
590
591                         m_shapes.push_back(new AbcMeshWriter(m_eval_ctx, m_scene, ob, xform, m_shape_sampling_index, m_settings));
592                         break;
593                 }
594                 case OB_SURF:
595                 {
596                         Curve *cu = static_cast<Curve *>(ob->data);
597
598                         if (!cu) {
599                                 return;
600                         }
601
602                         m_shapes.push_back(new AbcNurbsWriter(m_eval_ctx, m_scene, ob, xform, m_shape_sampling_index, m_settings));
603                         break;
604                 }
605                 case OB_CURVE:
606                 {
607                         Curve *cu = static_cast<Curve *>(ob->data);
608
609                         if (!cu) {
610                                 return;
611                         }
612
613                         m_shapes.push_back(new AbcCurveWriter(m_eval_ctx, m_scene, ob, xform, m_shape_sampling_index, m_settings));
614                         break;
615                 }
616                 case OB_CAMERA:
617                 {
618                         Camera *cam = static_cast<Camera *>(ob->data);
619
620                         if (cam->type == CAM_PERSP) {
621                                 m_shapes.push_back(new AbcCameraWriter(m_eval_ctx, m_scene, ob, xform, m_shape_sampling_index, m_settings));
622                         }
623
624                         break;
625                 }
626                 case OB_MBALL:
627                 {
628                         MetaBall *mball = static_cast<MetaBall *>(ob->data);
629                         if (!mball) {
630                                 return;
631                         }
632
633                         m_shapes.push_back(new AbcMBallWriter(
634                                                m_bmain, m_eval_ctx, m_scene, ob, xform,
635                                                m_shape_sampling_index, m_settings));
636                         break;
637                 }
638         }
639 }
640
641 AbcTransformWriter *AbcExporter::getXForm(const std::string &name)
642 {
643         std::map<std::string, AbcTransformWriter *>::iterator it = m_xforms.find(name);
644
645         if (it == m_xforms.end()) {
646                 return NULL;
647         }
648
649         return it->second;
650 }
651
652 void AbcExporter::setCurrentFrame(Main *bmain, double t)
653 {
654         m_scene->r.cfra = static_cast<int>(t);
655         m_scene->r.subframe = static_cast<float>(t) - m_scene->r.cfra;
656         BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, m_scene);
657 }