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