Cleanup: let's try to avoid too much indirect header imports, makes things harder...
[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 #ifdef WITH_ALEMBIC_HDF5
28 #  include <Alembic/AbcCoreHDF5/All.h>
29 #endif
30
31 #include <Alembic/AbcCoreOgawa/All.h>
32
33 #include "abc_camera.h"
34 #include "abc_curves.h"
35 #include "abc_hair.h"
36 #include "abc_mesh.h"
37 #include "abc_nurbs.h"
38 #include "abc_points.h"
39 #include "abc_transform.h"
40 #include "abc_util.h"
41
42 extern "C" {
43 #include "DNA_camera_types.h"
44 #include "DNA_curve_types.h"
45 #include "DNA_mesh_types.h"
46 #include "DNA_modifier_types.h"
47 #include "DNA_object_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_space_types.h"  /* for FILE_MAX */
50
51 #include "BLI_string.h"
52
53 #ifdef WIN32
54 /* needed for MSCV because of snprintf from BLI_string */
55 #       include "BLI_winstuff.h"
56 #endif
57
58 #include "BKE_anim.h"
59 #include "BKE_global.h"
60 #include "BKE_idprop.h"
61 #include "BKE_main.h"
62 #include "BKE_modifier.h"
63 #include "BKE_particle.h"
64 #include "BKE_scene.h"
65 }
66
67 using Alembic::Abc::TimeSamplingPtr;
68 using Alembic::Abc::OBox3dProperty;
69
70 /* ************************************************************************** */
71
72 ExportSettings::ExportSettings()
73     : scene(NULL)
74     , selected_only(false)
75     , visible_layers_only(false)
76     , renderable_only(false)
77     , frame_start(1)
78     , frame_end(1)
79     , frame_step_xform(1)
80     , frame_step_shape(1)
81     , shutter_open(0.0)
82     , shutter_close(1.0)
83     , global_scale(1.0f)
84     , flatten_hierarchy(false)
85     , export_normals(false)
86     , export_uvs(false)
87     , export_vcols(false)
88     , export_face_sets(false)
89     , export_vweigths(false)
90     , apply_subdiv(false)
91     , use_subdiv_schema(false)
92     , export_child_hairs(true)
93     , export_ogawa(true)
94     , pack_uv(false)
95     , do_convert_axis(false)
96 {}
97
98 static bool object_is_smoke_sim(Object *ob)
99 {
100         ModifierData *md = modifiers_findByType(ob, eModifierType_Smoke);
101
102         if (md) {
103                 SmokeModifierData *smd = reinterpret_cast<SmokeModifierData *>(md);
104                 return (smd->type == MOD_SMOKE_TYPE_DOMAIN);
105         }
106
107         return false;
108 }
109
110 static bool object_is_shape(Object *ob)
111 {
112         switch (ob->type) {
113                 case OB_MESH:
114                         if (object_is_smoke_sim(ob)) {
115                                 return false;
116                         }
117
118                         return true;
119                 case OB_CURVE:
120                 case OB_SURF:
121                 case OB_CAMERA:
122                         return true;
123                 default:
124                         return false;
125         }
126 }
127
128 static bool export_object(const ExportSettings * const settings, Object *ob)
129 {
130         if (settings->selected_only && !parent_selected(ob)) {
131                 return false;
132         }
133
134         if (settings->visible_layers_only && !(settings->scene->lay & ob->lay)) {
135                 return false;
136         }
137
138         if (settings->renderable_only && (ob->restrictflag & OB_RESTRICT_RENDER)) {
139                 return false;
140         }
141
142         return true;
143 }
144
145 /* ************************************************************************** */
146
147 AbcExporter::AbcExporter(Scene *scene, const char *filename, ExportSettings &settings)
148     : m_settings(settings)
149     , m_filename(filename)
150     , m_trans_sampling_index(0)
151     , m_shape_sampling_index(0)
152     , m_scene(scene)
153 {}
154
155 AbcExporter::~AbcExporter()
156 {
157         std::map<std::string, AbcTransformWriter*>::iterator it, e;
158         for (it = m_xforms.begin(), e = m_xforms.end(); it != e; ++it) {
159                 delete it->second;
160         }
161
162         for (int i = 0, e = m_shapes.size(); i != e; ++i) {
163                 delete m_shapes[i];
164         }
165 }
166
167 void AbcExporter::getShutterSamples(double step, bool time_relative,
168                                     std::vector<double> &samples)
169 {
170         samples.clear();
171
172         const double time_factor = time_relative ? m_scene->r.frs_sec : 1.0;
173         const double shutter_open = m_settings.shutter_open;
174         const double shutter_close = m_settings.shutter_close;
175
176         /* sample all frame */
177         if (shutter_open == 0.0 && shutter_close == 1.0) {
178                 for (double t = 0; t < 1.0; t += step) {
179                         samples.push_back((t + m_settings.frame_start) / time_factor);
180                 }
181         }
182         else {
183                 /* sample between shutter open & close */
184                 const int nsamples = std::max((1.0 / step) - 1.0, 1.0);
185                 const double time_inc = (shutter_close - shutter_open) / nsamples;
186
187                 for (double t = shutter_open; t <= shutter_close; t += time_inc) {
188                         samples.push_back((t + m_settings.frame_start) / time_factor);
189                 }
190         }
191 }
192
193 Alembic::Abc::TimeSamplingPtr AbcExporter::createTimeSampling(double step)
194 {
195         TimeSamplingPtr time_sampling;
196         std::vector<double> samples;
197
198         if (m_settings.frame_start == m_settings.frame_end) {
199                 time_sampling.reset(new Alembic::Abc::TimeSampling());
200                 return time_sampling;
201         }
202
203         getShutterSamples(step, true, samples);
204
205         Alembic::Abc::TimeSamplingType ts(static_cast<uint32_t>(samples.size()), 1.0 / m_scene->r.frs_sec);
206         time_sampling.reset(new Alembic::Abc::TimeSampling(ts, samples));
207
208         return time_sampling;
209 }
210
211 void AbcExporter::getFrameSet(double step, std::set<double> &frames)
212 {
213         frames.clear();
214
215         std::vector<double> shutter_samples;
216
217         getShutterSamples(step, false, shutter_samples);
218
219         for (int frame = m_settings.frame_start; frame <= m_settings.frame_end; ++frame) {
220                 for (int j = 0, e = shutter_samples.size(); j < e; ++j) {
221                         frames.insert(frame + shutter_samples[j]);
222                 }
223         }
224 }
225
226 void AbcExporter::operator()(Main *bmain, float &progress, bool &was_canceled)
227 {
228         std::string scene_name;
229
230         if (bmain->name[0] != '\0') {
231                 char scene_file_name[FILE_MAX];
232                 BLI_strncpy(scene_file_name, bmain->name, FILE_MAX);
233                 scene_name = scene_file_name;
234         }
235         else {
236                 scene_name = "untitled";
237         }
238
239         Scene *scene = m_scene;
240         const int fps = FPS;
241         char buf[16];
242         snprintf(buf, 15, "%d", fps);
243         const std::string str_fps = buf;
244
245         Alembic::AbcCoreAbstract::MetaData md;
246         md.set("FramesPerTimeUnit", str_fps);
247
248         Alembic::Abc::Argument arg(md);
249
250 #ifdef WITH_ALEMBIC_HDF5
251         if (!m_settings.export_ogawa) {
252                 m_archive = Alembic::Abc::CreateArchiveWithInfo(Alembic::AbcCoreHDF5::WriteArchive(),
253                                                                 m_filename,
254                                                                 "Blender",
255                                                                 scene_name,
256                                                                 Alembic::Abc::ErrorHandler::kThrowPolicy,
257                                                                 arg);
258         }
259         else
260 #endif
261         {
262                 m_archive = Alembic::Abc::CreateArchiveWithInfo(Alembic::AbcCoreOgawa::WriteArchive(),
263                                                                 m_filename,
264                                                                 "Blender",
265                                                                 scene_name,
266                                                                 Alembic::Abc::ErrorHandler::kThrowPolicy,
267                                                                 arg);
268         }
269
270         /* Create time samplings for transforms and shapes. */
271
272         TimeSamplingPtr trans_time = createTimeSampling(m_settings.frame_step_xform);
273
274         m_trans_sampling_index = m_archive.addTimeSampling(*trans_time);
275
276         TimeSamplingPtr shape_time;
277
278         if ((m_settings.frame_step_shape == m_settings.frame_step_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_step_shape);
286                 m_shape_sampling_index = m_archive.addTimeSampling(*shape_time);
287         }
288
289         OBox3dProperty archive_bounds_prop = Alembic::AbcGeom::CreateOArchiveBounds(m_archive, m_trans_sampling_index);
290
291         if (m_settings.flatten_hierarchy) {
292                 createTransformWritersFlat();
293         }
294         else {
295                 createTransformWritersHierarchy(bmain->eval_ctx);
296         }
297
298         createShapeWriters(bmain->eval_ctx);
299
300         /* Make a list of frames to export. */
301
302         std::set<double> xform_frames;
303         getFrameSet(m_settings.frame_step_xform, xform_frames);
304
305         std::set<double> shape_frames;
306         getFrameSet(m_settings.frame_step_shape, shape_frames);
307
308         /* Merge all frames needed. */
309
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 - m_settings.frame_start);
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                 std::map<std::string, AbcTransformWriter *>::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         Base *base = static_cast<Base *>(m_scene->base.first);
364
365         while (base) {
366                 Object *ob = base->object;
367
368                 if (export_object(&m_settings, ob)) {
369                         switch(ob->type) {
370                                 case OB_LAMP:
371                                 case OB_LATTICE:
372                                 case OB_MBALL:
373                                 case OB_SPEAKER:
374                                         /* We do not export transforms for objects of these classes. */
375                                         break;
376
377                                 default:
378                                         exploreTransform(eval_ctx, ob, ob->parent, NULL);
379                         }
380                 }
381
382                 base = base->next;
383         }
384 }
385
386 void AbcExporter::createTransformWritersFlat()
387 {
388         Base *base = static_cast<Base *>(m_scene->base.first);
389
390         while (base) {
391                 Object *ob = base->object;
392
393                 if (export_object(&m_settings, ob) && object_is_shape(ob)) {
394                         std::string name = get_id_name(ob);
395                         m_xforms[name] = new AbcTransformWriter(ob, m_archive.getTop(), 0, m_trans_sampling_index, m_settings);
396                 }
397
398                 base = base->next;
399         }
400 }
401
402 void AbcExporter::exploreTransform(EvaluationContext *eval_ctx, Object *ob, Object *parent, Object *dupliObParent)
403 {
404         createTransformWriter(ob, parent, dupliObParent);
405
406         ListBase *lb = object_duplilist(eval_ctx, m_scene, ob);
407
408         if (lb) {
409                 DupliObject *link = static_cast<DupliObject *>(lb->first);
410                 Object *dupli_ob = NULL;
411                 Object *dupli_parent = NULL;
412                 
413                 while (link) {
414                         if (link->type == OB_DUPLIGROUP) {
415                                 dupli_ob = link->ob;
416                                 dupli_parent = (dupli_ob->parent) ? dupli_ob->parent : ob;
417
418                                 exploreTransform(eval_ctx, dupli_ob, dupli_parent, ob);
419                         }
420
421                         link = link->next;
422                 }
423         }
424
425         free_object_duplilist(lb);
426 }
427
428 void AbcExporter::createTransformWriter(Object *ob, Object *parent, Object *dupliObParent)
429 {
430         const std::string name = get_object_dag_path_name(ob, dupliObParent);
431
432         /* check if we have already created a transform writer for this object */
433         if (m_xforms.find(name) != m_xforms.end()){
434                 std::cerr << "xform " << name << " already exists\n";
435                 return;
436         }
437
438         AbcTransformWriter *parent_xform = NULL;
439
440         if (parent) {
441                 const std::string parentname = get_object_dag_path_name(parent, dupliObParent);
442                 parent_xform = getXForm(parentname);
443
444                 if (!parent_xform) {
445                         if (parent->parent) {
446                                 createTransformWriter(parent, parent->parent, dupliObParent);
447                         }
448                         else {
449                                 createTransformWriter(parent, dupliObParent, dupliObParent);
450                         }
451
452                         parent_xform = getXForm(parentname);
453                 }
454         }
455
456         if (parent_xform) {
457                 m_xforms[name] = new AbcTransformWriter(ob, parent_xform->alembicXform(), parent_xform, m_trans_sampling_index, m_settings);
458                 m_xforms[name]->setParent(parent);
459         }
460         else {
461                 m_xforms[name] = new AbcTransformWriter(ob, m_archive.getTop(), NULL, m_trans_sampling_index, m_settings);
462         }
463 }
464
465 void AbcExporter::createShapeWriters(EvaluationContext *eval_ctx)
466 {
467         Base *base = static_cast<Base *>(m_scene->base.first);
468
469         while (base) {
470                 Object *ob = base->object;
471                 exploreObject(eval_ctx, ob, NULL);
472
473                 base = base->next;
474         }
475 }
476
477 void AbcExporter::exploreObject(EvaluationContext *eval_ctx, Object *ob, Object *dupliObParent)
478 {
479         ListBase *lb = object_duplilist(eval_ctx, m_scene, ob);
480         
481         createShapeWriter(ob, dupliObParent);
482         
483         if (lb) {
484                 DupliObject *dupliob = static_cast<DupliObject *>(lb->first);
485
486                 while (dupliob) {
487                         if (dupliob->type == OB_DUPLIGROUP) {
488                                 exploreObject(eval_ctx, dupliob->ob, ob);
489                         }
490
491                         dupliob = dupliob->next;
492                 }
493         }
494
495         free_object_duplilist(lb);
496 }
497
498 void AbcExporter::createShapeWriter(Object *ob, Object *dupliObParent)
499 {
500         if (!object_is_shape(ob)) {
501                 return;
502         }
503
504         if (!export_object(&m_settings, ob)) {
505                 return;
506         }
507
508         std::string name;
509
510         if (m_settings.flatten_hierarchy) {
511                 name = get_id_name(ob);
512         }
513         else {
514                 name = get_object_dag_path_name(ob, dupliObParent);
515         }
516         
517         AbcTransformWriter *xform = getXForm(name);
518
519         if (!xform) {
520                 std::cerr << __func__ << ": xform " << name << " is NULL\n";
521                 return;
522         }
523
524         ParticleSystem *psys = static_cast<ParticleSystem *>(ob->particlesystem.first);
525
526         for (; psys; psys = psys->next) {
527                 if (!psys_check_enabled(ob, psys, G.is_rendering) || !psys->part) {
528                         continue;
529                 }
530
531                 if (psys->part->type == PART_HAIR) {
532                         m_settings.export_child_hairs = true;
533                         m_shapes.push_back(new AbcHairWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
534                 }
535                 else if (psys->part->type == PART_EMITTER) {
536                         m_shapes.push_back(new AbcPointsWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
537                 }
538         }
539
540         switch(ob->type) {
541                 case OB_MESH:
542                 {
543                         Mesh *me = static_cast<Mesh *>(ob->data);
544
545                         if (!me || me->totvert == 0) {
546                                 return;
547                         }
548
549                         m_shapes.push_back(new AbcMeshWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings));
550                         break;
551                 }
552                 case OB_SURF:
553                 {
554                         Curve *cu = static_cast<Curve *>(ob->data);
555
556                         if (!cu) {
557                                 return;
558                         }
559
560                         m_shapes.push_back(new AbcNurbsWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings));
561                         break;
562                 }
563                 case OB_CURVE:
564                 {
565                         Curve *cu = static_cast<Curve *>(ob->data);
566
567                         if (!cu) {
568                                 return;
569                         }
570
571                         m_shapes.push_back(new AbcCurveWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings));
572                         break;
573                 }
574                 case OB_CAMERA:
575                 {
576                         Camera *cam = static_cast<Camera *>(ob->data);
577
578                         if (cam->type == CAM_PERSP) {
579                                 m_shapes.push_back(new AbcCameraWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings));
580                         }
581
582                         break;
583                 }
584         }
585 }
586
587 AbcTransformWriter *AbcExporter::getXForm(const std::string &name)
588 {
589         std::map<std::string, AbcTransformWriter *>::iterator it = m_xforms.find(name);
590
591         if (it == m_xforms.end()) {
592                 return NULL;
593         }
594
595         return it->second;
596 }
597
598 void AbcExporter::setCurrentFrame(Main *bmain, double t)
599 {
600         m_scene->r.cfra = std::floor(t);
601         m_scene->r.subframe = t - m_scene->r.cfra;
602         BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, m_scene, m_scene->lay);
603 }