28e75db2862538006cdd4018993dc1af3f1035c2
[blender.git] / source / blender / alembic / intern / abc_curves.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  * The Original Code is Copyright (C) 2016 K√©vin Dietrich.
19  * All rights reserved.
20  *
21  * ***** END GPL LICENSE BLOCK *****
22  *
23  */
24
25 #include "abc_curves.h"
26
27 #include <cstdio>
28
29 #include "abc_transform.h"
30 #include "abc_util.h"
31
32 extern "C" {
33 #include "MEM_guardedalloc.h"
34
35 #include "DNA_curve_types.h"
36 #include "DNA_object_types.h"
37
38 #include "BLI_listbase.h"
39
40 #include "BKE_cdderivedmesh.h"
41 #include "BKE_curve.h"
42 #include "BKE_object.h"
43
44 #include "ED_curve.h"
45 }
46
47 using Alembic::Abc::IInt32ArrayProperty;
48 using Alembic::Abc::Int32ArraySamplePtr;
49 using Alembic::Abc::FloatArraySamplePtr;
50 using Alembic::Abc::P3fArraySamplePtr;
51 using Alembic::Abc::UcharArraySamplePtr;
52
53 using Alembic::AbcGeom::ICurves;
54 using Alembic::AbcGeom::ICurvesSchema;
55 using Alembic::AbcGeom::IFloatGeomParam;
56 using Alembic::AbcGeom::ISampleSelector;
57 using Alembic::AbcGeom::kWrapExisting;
58 using Alembic::AbcGeom::CurvePeriodicity;
59
60 using Alembic::AbcGeom::OCurves;
61 using Alembic::AbcGeom::OCurvesSchema;
62 using Alembic::AbcGeom::ON3fGeomParam;
63 using Alembic::AbcGeom::OV2fGeomParam;
64
65 /* ************************************************************************** */
66
67 AbcCurveWriter::AbcCurveWriter(Scene *scene,
68                                Object *ob,
69                                AbcTransformWriter *parent,
70                                uint32_t time_sampling,
71                                ExportSettings &settings)
72     : AbcObjectWriter(scene, ob, time_sampling, settings, parent)
73 {
74         OCurves curves(parent->alembicXform(), m_name, m_time_sampling);
75         m_schema = curves.getSchema();
76 }
77
78 void AbcCurveWriter::do_write()
79 {
80         Curve *curve = static_cast<Curve *>(m_object->data);
81
82         std::vector<Imath::V3f> verts;
83         std::vector<int32_t> vert_counts;
84         std::vector<float> widths;
85         std::vector<float> weights;
86         std::vector<float> knots;
87         std::vector<uint8_t> orders;
88         Imath::V3f temp_vert;
89
90         Alembic::AbcGeom::BasisType curve_basis;
91         Alembic::AbcGeom::CurveType curve_type;
92         Alembic::AbcGeom::CurvePeriodicity periodicity;
93
94         Nurb *nurbs = static_cast<Nurb *>(curve->nurb.first);
95         for (; nurbs; nurbs = nurbs->next) {
96                 if (nurbs->bp) {
97                         curve_basis = Alembic::AbcGeom::kNoBasis;
98                         curve_type = Alembic::AbcGeom::kLinear;
99
100                         const int totpoint = nurbs->pntsu * nurbs->pntsv;
101
102                         const BPoint *point = nurbs->bp;
103
104                         for (int i = 0; i < totpoint; ++i, ++point) {
105                                 copy_yup_from_zup(temp_vert.getValue(), point->vec);
106                                 verts.push_back(temp_vert);
107                                 weights.push_back(point->vec[3]);
108                                 widths.push_back(point->radius);
109                         }
110                 }
111                 else if (nurbs->bezt) {
112                         curve_basis = Alembic::AbcGeom::kBezierBasis;
113                         curve_type = Alembic::AbcGeom::kCubic;
114
115                         const int totpoint = nurbs->pntsu;
116
117                         const BezTriple *bezier = nurbs->bezt;
118
119                         /* TODO(kevin): store info about handles, Alembic doesn't have this. */
120                         for (int i = 0; i < totpoint; ++i, ++bezier) {
121                                 copy_yup_from_zup(temp_vert.getValue(), bezier->vec[1]);
122                                 verts.push_back(temp_vert);
123                                 widths.push_back(bezier->radius);
124                         }
125                 }
126
127                 if ((nurbs->flagu & CU_NURB_ENDPOINT) != 0) {
128                         periodicity = Alembic::AbcGeom::kNonPeriodic;
129                 }
130                 else if ((nurbs->flagu & CU_NURB_CYCLIC) != 0) {
131                         periodicity = Alembic::AbcGeom::kPeriodic;
132
133                         /* Duplicate the start points to indicate that the curve is actually
134                          * cyclic since other software need those.
135                          */
136
137                         for (int i = 0; i < nurbs->orderu; ++i) {
138                                 verts.push_back(verts[i]);
139                         }
140                 }
141
142                 if (nurbs->knotsu != NULL) {
143                         const size_t num_knots = KNOTSU(nurbs);
144
145                         /* Add an extra knot at the beggining and end of the array since most apps
146                          * require/expect them. */
147                         knots.resize(num_knots + 2);
148
149                         for (int i = 0; i < num_knots; ++i) {
150                                 knots[i + 1] = nurbs->knotsu[i];
151                         }
152
153                         if ((nurbs->flagu & CU_NURB_CYCLIC) != 0) {
154                                 knots[0] = nurbs->knotsu[0];
155                                 knots[num_knots - 1] = nurbs->knotsu[num_knots - 1];
156                         }
157                         else {
158                                 knots[0] = (2.0f * nurbs->knotsu[0] - nurbs->knotsu[1]);
159                                 knots[num_knots - 1] = (2.0f * nurbs->knotsu[num_knots - 1] - nurbs->knotsu[num_knots - 2]);
160                         }
161                 }
162
163                 orders.push_back(nurbs->orderu + 1);
164                 vert_counts.push_back(verts.size());
165         }
166
167         Alembic::AbcGeom::OFloatGeomParam::Sample width_sample;
168         width_sample.setVals(widths);
169
170         m_sample = OCurvesSchema::Sample(verts,
171                                          vert_counts,
172                                          curve_type,
173                                          periodicity,
174                                          width_sample,
175                                          OV2fGeomParam::Sample(),  /* UVs */
176                                          ON3fGeomParam::Sample(),  /* normals */
177                                          curve_basis,
178                                          weights,
179                                          orders,
180                                          knots);
181
182         m_sample.setSelfBounds(bounds());
183         m_schema.set(m_sample);
184 }
185
186 /* ************************************************************************** */
187
188 AbcCurveReader::AbcCurveReader(const Alembic::Abc::IObject &object, ImportSettings &settings)
189     : AbcObjectReader(object, settings)
190 {
191         ICurves abc_curves(object, kWrapExisting);
192         m_curves_schema = abc_curves.getSchema();
193
194         get_min_max_time(m_iobject, m_curves_schema, m_min_time, m_max_time);
195 }
196
197 bool AbcCurveReader::valid() const
198 {
199         return m_curves_schema.valid();
200 }
201
202 void AbcCurveReader::readObjectData(Main *bmain, float time)
203 {
204         Curve *cu = BKE_curve_add(bmain, m_data_name.c_str(), OB_CURVE);
205
206         cu->flag |= CU_DEFORM_FILL | CU_3D;
207         cu->actvert = CU_ACT_NONE;
208         cu->resolu = 1;
209
210         m_object = BKE_object_add_only_object(bmain, OB_CURVE, m_object_name.c_str());
211         m_object->data = cu;
212
213         read_curve_sample(cu, m_curves_schema, time);
214
215         if (has_animations(m_curves_schema, m_settings)) {
216                 addCacheModifier();
217         }
218 }
219
220 /* ************************************************************************** */
221
222 void read_curve_sample(Curve *cu, const ICurvesSchema &schema, const float time)
223 {
224         const ISampleSelector sample_sel(time);
225         ICurvesSchema::Sample smp = schema.getValue(sample_sel);
226         const Int32ArraySamplePtr num_vertices = smp.getCurvesNumVertices();
227         const P3fArraySamplePtr positions = smp.getPositions();
228         const FloatArraySamplePtr weights = smp.getPositionWeights();
229         const FloatArraySamplePtr knots = smp.getKnots();
230         const CurvePeriodicity periodicity = smp.getWrap();
231         const UcharArraySamplePtr orders = smp.getOrders();
232
233         const IFloatGeomParam widths_param = schema.getWidthsParam();
234         FloatArraySamplePtr radiuses;
235
236         if (widths_param.valid()) {
237                 IFloatGeomParam::Sample wsample = widths_param.getExpandedValue(sample_sel);
238                 radiuses = wsample.getVals();
239         }
240
241         int knot_offset = 0;
242
243         size_t idx = 0;
244         for (size_t i = 0; i < num_vertices->size(); ++i) {
245                 const int num_verts = (*num_vertices)[i];
246
247                 Nurb *nu = static_cast<Nurb *>(MEM_callocN(sizeof(Nurb), "abc_getnurb"));
248                 nu->resolu = cu->resolu;
249                 nu->resolv = cu->resolv;
250                 nu->pntsu = num_verts;
251                 nu->pntsv = 1;
252                 nu->flag |= CU_SMOOTH;
253
254                 switch (smp.getType()) {
255                         case Alembic::AbcGeom::kCubic:
256                                 nu->orderu = 4;
257                                 break;
258                         case Alembic::AbcGeom::kVariableOrder:
259                                 if (orders && orders->size() > i) {
260                                         nu->orderu = static_cast<short>((*orders)[i]);
261                                 }
262                                 break;
263                         case Alembic::AbcGeom::kLinear:
264                         default:
265                                 nu->orderu = 2;
266                 }
267
268                 if (periodicity == Alembic::AbcGeom::kNonPeriodic) {
269                         nu->flagu |= CU_NURB_ENDPOINT;
270                 }
271                 else if (periodicity == Alembic::AbcGeom::kPeriodic) {
272                         nu->flagu |= CU_NURB_CYCLIC;
273
274                         /* Check the number of points which overlap, we don't have
275                          * overlapping points in Blender, but other software do use them to
276                          * indicate that a curve is actually cyclic. Usually the number of
277                          * overlapping points is equal to the order/degree of the curve.
278                          */
279
280                         const int start = idx;
281                         const int end = idx + num_verts;
282                         int overlap = 0;
283
284                         for (int j = start, k = end - nu->orderu; j < nu->orderu; ++j, ++k) {
285                                 const Imath::V3f &p1 = (*positions)[j];
286                                 const Imath::V3f &p2 = (*positions)[k];
287
288                                 if (p1 != p2) {
289                                         break;
290                                 }
291
292                                 ++overlap;
293                         }
294
295                         /* TODO: Special case, need to figure out how it coincides with knots. */
296                         if (overlap == 0 && num_verts > 2 && (*positions)[start] == (*positions)[end - 1]) {
297                                 overlap = 1;
298                         }
299
300                         /* There is no real cycles. */
301                         if (overlap == 0) {
302                                 nu->flagu &= ~CU_NURB_CYCLIC;
303                                 nu->flagu |= CU_NURB_ENDPOINT;
304                         }
305
306                         nu->pntsu -= overlap;
307                 }
308
309                 const bool do_weights = (weights != NULL) && (weights->size() > 1);
310                 float weight = 1.0f;
311
312                 const bool do_radius = (radiuses != NULL) && (radiuses->size() > 1);
313                 float radius = (radiuses && radiuses->size() == 1) ? (*radiuses)[0] : 1.0f;
314
315                 nu->type = CU_NURBS;
316
317                 nu->bp = static_cast<BPoint *>(MEM_callocN(sizeof(BPoint) * nu->pntsu, "abc_getnurb"));
318                 BPoint *bp = nu->bp;
319
320                 for (int j = 0; j < nu->pntsu; ++j, ++bp, ++idx) {
321                         const Imath::V3f &pos = (*positions)[idx];
322
323                         if (do_radius) {
324                                 radius = (*radiuses)[idx];
325                         }
326
327                         if (do_weights) {
328                                 weight = (*weights)[idx];
329                         }
330
331                         copy_zup_from_yup(bp->vec, pos.getValue());
332                         bp->vec[3] = weight;
333                         bp->f1 = SELECT;
334                         bp->radius = radius;
335                         bp->weight = 1.0f;
336                 }
337
338                 if (knots && knots->size() != 0) {
339                         nu->knotsu = static_cast<float *>(MEM_callocN(KNOTSU(nu) * sizeof(float), "abc_setsplineknotsu"));
340
341                         /* TODO: second check is temporary, for until the check for cycles is rock solid. */
342                         if (periodicity == Alembic::AbcGeom::kPeriodic && (KNOTSU(nu) == knots->size() - 2)) {
343                                 /* Skip first and last knots. */
344                                 for (size_t i = 1; i < knots->size() - 1; ++i) {
345                                         nu->knotsu[i - 1] = (*knots)[knot_offset + i];
346                                 }
347                         }
348                         else {
349                                 /* TODO: figure out how to use the knots array from other
350                                  * software in this case. */
351                                 BKE_nurb_knot_calc_u(nu);
352                         }
353
354                         knot_offset += knots->size();
355                 }
356                 else {
357                         BKE_nurb_knot_calc_u(nu);
358                 }
359
360                 BLI_addtail(BKE_curve_nurbs_get(cu), nu);
361         }
362 }
363
364 /* NOTE: Alembic only stores data about control points, but the DerivedMesh
365  * passed from the cache modifier contains the displist, which has more data
366  * than the control points, so to avoid corrupting the displist we modify the
367  * object directly and create a new DerivedMesh from that. Also we might need to
368  * create new or delete existing NURBS in the curve.
369  */
370 DerivedMesh *AbcCurveReader::read_derivedmesh(DerivedMesh * /*dm*/, const float time, int /*read_flag*/, const char ** /*err_str*/)
371 {
372         ISampleSelector sample_sel(time);
373         const ICurvesSchema::Sample sample = m_curves_schema.getValue(sample_sel);
374
375         const P3fArraySamplePtr &positions = sample.getPositions();
376         const Int32ArraySamplePtr num_vertices = sample.getCurvesNumVertices();
377
378         int vertex_idx = 0;
379         int curve_idx = 0;
380         Curve *curve = static_cast<Curve *>(m_object->data);
381
382         const int curve_count = BLI_listbase_count(&curve->nurb);
383
384         if (curve_count != num_vertices->size()) {
385                 BKE_nurbList_free(&curve->nurb);
386                 read_curve_sample(curve, m_curves_schema, time);
387         }
388         else {
389                 Nurb *nurbs = static_cast<Nurb *>(curve->nurb.first);
390                 for (; nurbs; nurbs = nurbs->next, ++curve_idx) {
391                         const int totpoint = (*num_vertices)[curve_idx];
392
393                         if (nurbs->bp) {
394                                 BPoint *point = nurbs->bp;
395
396                                 for (int i = 0; i < totpoint; ++i, ++point, ++vertex_idx) {
397                                         const Imath::V3f &pos = (*positions)[vertex_idx];
398                                         copy_zup_from_yup(point->vec, pos.getValue());
399                                 }
400                         }
401                         else if (nurbs->bezt) {
402                                 BezTriple *bezier = nurbs->bezt;
403
404                                 for (int i = 0; i < totpoint; ++i, ++bezier, ++vertex_idx) {
405                                         const Imath::V3f &pos = (*positions)[vertex_idx];
406                                         copy_zup_from_yup(bezier->vec[1], pos.getValue());
407                                 }
408                         }
409                 }
410         }
411
412         return CDDM_from_curve(m_object);
413 }