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