/[svn]/gigedit/trunk/src/gigedit/CombineInstrumentsDialog.cpp
ViewVC logotype

Contents of /gigedit/trunk/src/gigedit/CombineInstrumentsDialog.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2894 - (show annotations) (download)
Sat Apr 30 14:42:14 2016 UTC (3 years, 1 month ago) by schoenebeck
File size: 43879 byte(s)
* Enabled auto save & restore of window size & position of all
  remaining windows.
* Bumped version (1.0.0.svn7).

1 /*
2 Copyright (c) 2014-2016 Christian Schoenebeck
3
4 This file is part of "gigedit" and released under the terms of the
5 GNU General Public License version 2.
6 */
7
8 #include "CombineInstrumentsDialog.h"
9
10 // enable this for debug messages being printed while combining the instruments
11 #define DEBUG_COMBINE_INSTRUMENTS 0
12
13 #include "global.h"
14 #include "compat.h"
15
16 #include <set>
17 #include <iostream>
18 #include <assert.h>
19 #include <stdarg.h>
20 #include <string.h>
21
22 #include <glibmm/ustring.h>
23 #include <gtkmm/messagedialog.h>
24 #include <gtkmm/label.h>
25
26 Glib::ustring gig_to_utf8(const gig::String& gig_string);
27 Glib::ustring dimTypeAsString(gig::dimension_t d);
28
29 typedef std::vector< std::pair<gig::Instrument*, gig::Region*> > OrderedRegionGroup;
30 typedef std::map<gig::Instrument*, gig::Region*> RegionGroup;
31 typedef std::map<DLS::range_t,RegionGroup> RegionGroups;
32
33 typedef std::vector<DLS::range_t> DimensionZones;
34 typedef std::map<gig::dimension_t,DimensionZones> Dimensions;
35
36 typedef std::map<gig::dimension_t,int> DimensionCase;
37
38 typedef std::map<gig::dimension_t, int> DimensionRegionUpperLimits;
39
40 typedef std::set<Glib::ustring> Warnings;
41
42 ///////////////////////////////////////////////////////////////////////////
43 // private static data
44
45 static Warnings g_warnings;
46
47 ///////////////////////////////////////////////////////////////////////////
48 // private functions
49
50 #if DEBUG_COMBINE_INSTRUMENTS
51 static void printRanges(const RegionGroups& regions) {
52 std::cout << "{ ";
53 for (RegionGroups::const_iterator it = regions.begin(); it != regions.end(); ++it) {
54 if (it != regions.begin()) std::cout << ", ";
55 std::cout << (int)it->first.low << ".." << (int)it->first.high;
56 }
57 std::cout << " }" << std::flush;
58 }
59 #endif
60
61 /**
62 * Store a warning message that shall be stored and displayed to the user as a
63 * list of warnings after the overall operation has finished. Duplicate warning
64 * messages are automatically eliminated.
65 */
66 inline void addWarning(const char* fmt, ...) {
67 va_list arg;
68 va_start(arg, fmt);
69 const int SZ = 255 + strlen(fmt);
70 char* buf = new char[SZ];
71 vsnprintf(buf, SZ, fmt, arg);
72 Glib::ustring s = buf;
73 delete [] buf;
74 va_end(arg);
75 std::cerr << _("WARNING:") << " " << s << std::endl << std::flush;
76 g_warnings.insert(s);
77 }
78
79 /**
80 * If the two ranges overlap, then this function returns the smallest point
81 * within that overlapping zone. If the two ranges do not overlap, then this
82 * function will return -1 instead.
83 */
84 inline int smallestOverlapPoint(const DLS::range_t& r1, const DLS::range_t& r2) {
85 if (r1.overlaps(r2.low)) return r2.low;
86 if (r2.overlaps(r1.low)) return r1.low;
87 return -1;
88 }
89
90 /**
91 * Get the most smallest region point (not necessarily its region start point)
92 * of all regions of the given instruments, start searching at keyboard
93 * position @a iStart.
94 *
95 * @returns very first region point >= iStart, or -1 if no region could be
96 * found with a range member point >= iStart
97 */
98 static int findLowestRegionPoint(std::vector<gig::Instrument*>& instruments, int iStart) {
99 DLS::range_t searchRange = { uint16_t(iStart), 127 };
100 int result = -1;
101 for (uint i = 0; i < instruments.size(); ++i) {
102 gig::Instrument* instr = instruments[i];
103 for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
104 if (rgn->KeyRange.overlaps(searchRange)) {
105 int lowest = smallestOverlapPoint(rgn->KeyRange, searchRange);
106 if (result == -1 || lowest < result) result = lowest;
107 }
108 }
109 }
110 return result;
111 }
112
113 /**
114 * Get the most smallest region end of all regions of the given instruments,
115 * start searching at keyboard position @a iStart.
116 *
117 * @returns very first region end >= iStart, or -1 if no region could be found
118 * with a range end >= iStart
119 */
120 static int findFirstRegionEnd(std::vector<gig::Instrument*>& instruments, int iStart) {
121 DLS::range_t searchRange = { uint16_t(iStart), 127 };
122 int result = -1;
123 for (uint i = 0; i < instruments.size(); ++i) {
124 gig::Instrument* instr = instruments[i];
125 for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
126 if (rgn->KeyRange.overlaps(searchRange)) {
127 if (result == -1 || rgn->KeyRange.high < result)
128 result = rgn->KeyRange.high;
129 }
130 }
131 }
132 return result;
133 }
134
135 /**
136 * Returns a list of all regions of the given @a instrument where the respective
137 * region's key range overlaps the given @a range.
138 */
139 static std::vector<gig::Region*> getAllRegionsWhichOverlapRange(gig::Instrument* instrument, DLS::range_t range) {
140 //std::cout << "All regions which overlap { " << (int)range.low << ".." << (int)range.high << " } : " << std::flush;
141 std::vector<gig::Region*> v;
142 for (gig::Region* rgn = instrument->GetFirstRegion(); rgn; rgn = instrument->GetNextRegion()) {
143 if (rgn->KeyRange.overlaps(range)) {
144 v.push_back(rgn);
145 //std::cout << (int)rgn->KeyRange.low << ".." << (int)rgn->KeyRange.high << ", " << std::flush;
146 }
147 }
148 //std::cout << " END." << std::endl;
149 return v;
150 }
151
152 /**
153 * Returns all regions of the given @a instruments where the respective region's
154 * key range overlaps the given @a range. The regions returned are ordered (in a
155 * map) by their instrument pointer.
156 */
157 static RegionGroup getAllRegionsWhichOverlapRange(std::vector<gig::Instrument*>& instruments, DLS::range_t range) {
158 RegionGroup group;
159 for (uint i = 0; i < instruments.size(); ++i) {
160 gig::Instrument* instr = instruments[i];
161 std::vector<gig::Region*> v = getAllRegionsWhichOverlapRange(instr, range);
162 if (v.empty()) continue;
163 if (v.size() > 1) {
164 addWarning("More than one region found!");
165 }
166 group[instr] = v[0];
167 }
168 return group;
169 }
170
171 /** @brief Identify required regions.
172 *
173 * Takes a list of @a instruments as argument (which are planned to be combined
174 * as separate dimension zones of a certain dimension into one single new
175 * instrument) and fulfills the following tasks:
176 *
177 * - 1. Identification of total amount of regions required to create a new
178 * instrument to become a combined version of the given instruments.
179 * - 2. Precise key range of each of those identified required regions to be
180 * created in that new instrument.
181 * - 3. Grouping the original source regions of the given original instruments
182 * to the respective target key range (new region) of the instrument to be
183 * created.
184 *
185 * @param instruments - list of instruments that are planned to be combined
186 * @returns structured result of the tasks described above
187 */
188 static RegionGroups groupByRegionIntersections(std::vector<gig::Instrument*>& instruments) {
189 RegionGroups groups;
190
191 // find all region intersections of all instruments
192 std::vector<DLS::range_t> intersections;
193 for (int iStart = 0; iStart <= 127; ) {
194 iStart = findLowestRegionPoint(instruments, iStart);
195 if (iStart < 0) break;
196 const int iEnd = findFirstRegionEnd(instruments, iStart);
197 DLS::range_t range = { uint16_t(iStart), uint16_t(iEnd) };
198 intersections.push_back(range);
199 iStart = iEnd + 1;
200 }
201
202 // now sort all regions to those found intersections
203 for (uint i = 0; i < intersections.size(); ++i) {
204 const DLS::range_t& range = intersections[i];
205 RegionGroup group = getAllRegionsWhichOverlapRange(instruments, range);
206 if (!group.empty())
207 groups[range] = group;
208 else
209 addWarning("Empty region group!");
210 }
211
212 return groups;
213 }
214
215 /** @brief Identify required dimensions.
216 *
217 * Takes a planned new region (@a regionGroup) as argument and identifies which
218 * precise dimensions would have to be created for that new region, along with
219 * the amount of dimension zones and their precise individual zone sizes.
220 *
221 * @param regionGroup - planned new region for a new instrument
222 * @returns set of dimensions that shall be created for the given planned region
223 */
224 static Dimensions getDimensionsForRegionGroup(RegionGroup& regionGroup) {
225 std::map<gig::dimension_t, std::set<int> > dimUpperLimits;
226
227 // collect all dimension region zones' upper limits
228 for (RegionGroup::iterator it = regionGroup.begin();
229 it != regionGroup.end(); ++it)
230 {
231 gig::Region* rgn = it->second;
232 int previousBits = 0;
233 for (uint d = 0; d < rgn->Dimensions; ++d) {
234 const gig::dimension_def_t& def = rgn->pDimensionDefinitions[d];
235 for (uint z = 0; z < def.zones; ++z) {
236 int dr = z << previousBits;
237 gig::DimensionRegion* dimRgn = rgn->pDimensionRegions[dr];
238 // Store the individual dimension zone sizes (or actually their
239 // upper limits here) for each dimension.
240 // HACK: Note that the velocity dimension is specially handled
241 // here. Instead of taking over custom velocity split sizes
242 // here, only a bogus number (zone index number) is stored for
243 // each velocity zone, that way only the maxiumum amount of
244 // velocity splits of all regions is stored here, and when their
245 // individual DimensionRegions are finally copied (later), the
246 // individual velocity split size are copied by that.
247 dimUpperLimits[def.dimension].insert(
248 (def.dimension == gig::dimension_velocity) ?
249 z : (def.split_type == gig::split_type_bit) ?
250 ((z+1) * 128/def.zones - 1) : dimRgn->DimensionUpperLimits[dr]
251 );
252 }
253 previousBits += def.bits;
254 }
255 }
256
257 // convert upper limit set to range vector
258 Dimensions dims;
259 for (std::map<gig::dimension_t, std::set<int> >::const_iterator it = dimUpperLimits.begin();
260 it != dimUpperLimits.end(); ++it)
261 {
262 gig::dimension_t type = it->first;
263 int iLow = 0;
264 for (std::set<int>::const_iterator itNums = it->second.begin();
265 itNums != it->second.end(); ++itNums)
266 {
267 const int iUpperLimit = *itNums;
268 DLS::range_t range = { uint16_t(iLow), uint16_t(iUpperLimit) };
269 dims[type].push_back(range);
270 iLow = iUpperLimit + 1;
271 }
272 }
273
274 return dims;
275 }
276
277 inline int getDimensionIndex(gig::dimension_t type, gig::Region* rgn) {
278 for (uint i = 0; i < rgn->Dimensions; ++i)
279 if (rgn->pDimensionDefinitions[i].dimension == type)
280 return i;
281 return -1;
282 }
283
284 static void fillDimValues(uint* values/*[8]*/, DimensionCase dimCase, gig::Region* rgn, bool bShouldHaveAllDimensionsPassed) {
285 #if DEBUG_COMBINE_INSTRUMENTS
286 printf("dimvalues = { ");
287 fflush(stdout);
288 #endif
289 for (DimensionCase::iterator it = dimCase.begin(); it != dimCase.end(); ++it) {
290 gig::dimension_t type = it->first;
291 int iDimIndex = getDimensionIndex(type, rgn);
292 if (bShouldHaveAllDimensionsPassed) assert(iDimIndex >= 0);
293 else if (iDimIndex < 0) continue;
294 values[iDimIndex] = it->second;
295 #if DEBUG_COMBINE_INSTRUMENTS
296 printf("%x=%d, ", type, it->second);
297 #endif
298 }
299 #if DEBUG_COMBINE_INSTRUMENTS
300 printf("}\n");
301 #endif
302 }
303
304 static DimensionRegionUpperLimits getDimensionRegionUpperLimits(gig::DimensionRegion* dimRgn) {
305 DimensionRegionUpperLimits limits;
306 gig::Region* rgn = dimRgn->GetParent();
307 for (uint d = 0; d < rgn->Dimensions; ++d) {
308 const gig::dimension_def_t& def = rgn->pDimensionDefinitions[d];
309 limits[def.dimension] = dimRgn->DimensionUpperLimits[d];
310 }
311 return limits;
312 }
313
314 static void restoreDimensionRegionUpperLimits(gig::DimensionRegion* dimRgn, const DimensionRegionUpperLimits& limits) {
315 gig::Region* rgn = dimRgn->GetParent();
316 for (DimensionRegionUpperLimits::const_iterator it = limits.begin();
317 it != limits.end(); ++it)
318 {
319 int index = getDimensionIndex(it->first, rgn);
320 assert(index >= 0);
321 dimRgn->DimensionUpperLimits[index] = it->second;
322 }
323 }
324
325 /**
326 * Returns the sum of all bits of all dimensions defined before the given
327 * dimensions (@a type). This allows to access cases of that particular
328 * dimension directly.
329 *
330 * @param type - dimension that shall be used
331 * @param rgn - parent region of that dimension
332 */
333 inline int baseBits(gig::dimension_t type, gig::Region* rgn) {
334 int previousBits = 0;
335 for (uint i = 0; i < rgn->Dimensions; ++i) {
336 if (rgn->pDimensionDefinitions[i].dimension == type) break;
337 previousBits += rgn->pDimensionDefinitions[i].bits;
338 }
339 return previousBits;
340 }
341
342 inline int dimensionRegionIndex(gig::DimensionRegion* dimRgn) {
343 gig::Region* rgn = dimRgn->GetParent();
344 int sz = sizeof(rgn->pDimensionRegions) / sizeof(gig::DimensionRegion*);
345 for (int i = 0; i < sz; ++i)
346 if (rgn->pDimensionRegions[i] == dimRgn)
347 return i;
348 return -1;
349 }
350
351 /** @brief Get exact zone ranges of given dimension.
352 *
353 * This function is useful for the velocity type dimension. In contrast to other
354 * dimension types, this dimension can have different zone ranges (that is
355 * different individual start and end points of its dimension zones) depending
356 * on which zones of other dimensions (on that gig::Region) are currently
357 * selected.
358 *
359 * @param type - dimension where the zone ranges should be retrieved for
360 * (usually the velocity dimension in this context)
361 * @param dimRgn - reflects the exact cases (zone selections) of all other
362 * dimensions than the given one in question
363 * @returns individual ranges for each zone of the questioned dimension type,
364 * it returns an empty result on errors instead
365 */
366 static DimensionZones preciseDimensionZonesFor(gig::dimension_t type, gig::DimensionRegion* dimRgn) {
367 DimensionZones zones;
368 gig::Region* rgn = dimRgn->GetParent();
369 int iDimension = getDimensionIndex(type, rgn);
370 if (iDimension < 0) return zones;
371 const gig::dimension_def_t& def = rgn->pDimensionDefinitions[iDimension];
372 int iDimRgn = dimensionRegionIndex(dimRgn);
373 int iBaseBits = baseBits(type, rgn);
374 int mask = ~(((1 << def.bits) - 1) << iBaseBits);
375
376 #if DEBUG_COMBINE_INSTRUMENTS
377 printf("velo zones { ");
378 fflush(stdout);
379 #endif
380 int iLow = 0;
381 for (int z = 0; z < def.zones; ++z) {
382 gig::DimensionRegion* dimRgn2 =
383 rgn->pDimensionRegions[ (iDimRgn & mask) | ( z << iBaseBits) ];
384 int iHigh = dimRgn2->DimensionUpperLimits[iDimension];
385 DLS::range_t range = { uint16_t(iLow), uint16_t(iHigh) };
386 #if DEBUG_COMBINE_INSTRUMENTS
387 printf("%d..%d, ", iLow, iHigh);
388 fflush(stdout);
389 #endif
390 zones.push_back(range);
391 iLow = iHigh + 1;
392 }
393 #if DEBUG_COMBINE_INSTRUMENTS
394 printf("}\n");
395 #endif
396 return zones;
397 }
398
399 struct CopyAssignSchedEntry {
400 gig::DimensionRegion* src;
401 gig::DimensionRegion* dst;
402 int velocityZone;
403 int totalSrcVelocityZones;
404 };
405 typedef std::vector<CopyAssignSchedEntry> CopyAssignSchedule;
406
407 /** @brief Schedule copying DimensionRegions from source Region to target Region.
408 *
409 * Schedules copying the entire articulation informations (including sample
410 * reference) from all individual DimensionRegions of source Region @a inRgn to
411 * target Region @a outRgn. It is expected that the required dimensions (thus
412 * the required dimension regions) were already created before calling this
413 * function.
414 *
415 * To be precise, it does the task above only for the dimension zones defined by
416 * the three arguments @a mainDim, @a iSrcMainBit, @a iDstMainBit, which reflect
417 * a selection which dimension zones shall be copied. All other dimension zones
418 * will not be scheduled to be copied by a single call of this function. So this
419 * function needs to be called several time in case all dimension regions shall
420 * be copied of the entire region (@a inRgn, @a outRgn).
421 *
422 * @param outRgn - where the dimension regions shall be copied to
423 * @param inRgn - all dimension regions that shall be copied from
424 * @param dims - precise dimension definitions of target region
425 * @param mainDim - this dimension type, in combination with @a iSrcMainBit and
426 * @a iDstMainBit defines a selection which dimension region
427 * zones shall be copied by this call of this function
428 * @param iDstMainBit - destination bit of @a mainDim
429 * @param iSrcMainBit - source bit of @a mainDim
430 * @param schedule - list of all DimensionRegion copy operations which is filled
431 * during the nested loops / recursions of this function call
432 * @param dimCase - just for internal purpose (function recursion), don't pass
433 * anything here, this function will call itself recursively
434 * will fill this container with concrete dimension values for
435 * selecting the precise dimension regions during its task
436 */
437 static void scheduleCopyDimensionRegions(gig::Region* outRgn, gig::Region* inRgn,
438 Dimensions dims, gig::dimension_t mainDim,
439 int iDstMainBit, int iSrcMainBit,
440 CopyAssignSchedule* schedule,
441 DimensionCase dimCase = DimensionCase())
442 {
443 if (dims.empty()) { // reached deepest level of function recursion ...
444 CopyAssignSchedEntry e;
445
446 // resolve the respective source & destination DimensionRegion ...
447 uint srcDimValues[8] = {};
448 uint dstDimValues[8] = {};
449 DimensionCase srcDimCase = dimCase;
450 DimensionCase dstDimCase = dimCase;
451 srcDimCase[mainDim] = iSrcMainBit;
452 dstDimCase[mainDim] = iDstMainBit;
453
454 #if DEBUG_COMBINE_INSTRUMENTS
455 printf("-------------------------------\n");
456 printf("iDstMainBit=%d iSrcMainBit=%d\n", iDstMainBit, iSrcMainBit);
457 #endif
458
459 // first select source & target dimension region with an arbitrary
460 // velocity split zone, to get access to the precise individual velocity
461 // split zone sizes (if there is actually a velocity dimension at all,
462 // otherwise we already select the desired source & target dimension
463 // region here)
464 #if DEBUG_COMBINE_INSTRUMENTS
465 printf("src "); fflush(stdout);
466 #endif
467 fillDimValues(srcDimValues, srcDimCase, inRgn, false);
468 #if DEBUG_COMBINE_INSTRUMENTS
469 printf("dst "); fflush(stdout);
470 #endif
471 fillDimValues(dstDimValues, dstDimCase, outRgn, false);
472 gig::DimensionRegion* srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);
473 gig::DimensionRegion* dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);
474 #if DEBUG_COMBINE_INSTRUMENTS
475 printf("iDstMainBit=%d iSrcMainBit=%d\n", iDstMainBit, iSrcMainBit);
476 printf("srcDimRgn=%lx dstDimRgn=%lx\n", (uint64_t)srcDimRgn, (uint64_t)dstDimRgn);
477 printf("srcSample='%s' dstSample='%s'\n",
478 (!srcDimRgn->pSample ? "NULL" : srcDimRgn->pSample->pInfo->Name.c_str()),
479 (!dstDimRgn->pSample ? "NULL" : dstDimRgn->pSample->pInfo->Name.c_str())
480 );
481 #endif
482
483 assert(srcDimRgn->GetParent() == inRgn);
484 assert(dstDimRgn->GetParent() == outRgn);
485
486 // now that we have access to the precise velocity split zone upper
487 // limits, we can select the actual source & destination dimension
488 // regions we need to copy (assuming that source or target region has
489 // a velocity dimension)
490 if (outRgn->GetDimensionDefinition(gig::dimension_velocity)) {
491 // re-select target dimension region (with correct velocity zone)
492 DimensionZones dstZones = preciseDimensionZonesFor(gig::dimension_velocity, dstDimRgn);
493 assert(dstZones.size() > 1);
494 const int iDstZoneIndex =
495 (mainDim == gig::dimension_velocity)
496 ? iDstMainBit : dstDimCase[gig::dimension_velocity]; // (mainDim == gig::dimension_velocity) exception case probably unnecessary here
497 e.velocityZone = iDstZoneIndex;
498 #if DEBUG_COMBINE_INSTRUMENTS
499 printf("dst velocity zone: %d/%d\n", iDstZoneIndex, (int)dstZones.size());
500 #endif
501 assert(uint(iDstZoneIndex) < dstZones.size());
502 dstDimCase[gig::dimension_velocity] = dstZones[iDstZoneIndex].low; // arbitrary value between low and high
503 #if DEBUG_COMBINE_INSTRUMENTS
504 printf("dst velocity value = %d\n", dstDimCase[gig::dimension_velocity]);
505 printf("dst refilled "); fflush(stdout);
506 #endif
507 fillDimValues(dstDimValues, dstDimCase, outRgn, false);
508 dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);
509 #if DEBUG_COMBINE_INSTRUMENTS
510 printf("reselected dstDimRgn=%lx\n", (uint64_t)dstDimRgn);
511 printf("dstSample='%s'%s\n",
512 (!dstDimRgn->pSample ? "NULL" : dstDimRgn->pSample->pInfo->Name.c_str()),
513 (dstDimRgn->pSample ? " <--- ERROR ERROR ERROR !!!!!!!!! " : "")
514 );
515 #endif
516
517 // re-select source dimension region with correct velocity zone
518 // (if it has a velocity dimension that is)
519 if (inRgn->GetDimensionDefinition(gig::dimension_velocity)) {
520 DimensionZones srcZones = preciseDimensionZonesFor(gig::dimension_velocity, srcDimRgn);
521 e.totalSrcVelocityZones = srcZones.size();
522 assert(srcZones.size() > 0);
523 if (srcZones.size() <= 1) {
524 addWarning("Input region has a velocity dimension with only ONE zone!");
525 }
526 int iSrcZoneIndex =
527 (mainDim == gig::dimension_velocity)
528 ? iSrcMainBit : iDstZoneIndex;
529 if (uint(iSrcZoneIndex) >= srcZones.size())
530 iSrcZoneIndex = srcZones.size() - 1;
531 srcDimCase[gig::dimension_velocity] = srcZones[iSrcZoneIndex].low; // same zone as used above for target dimension region (no matter what the precise zone ranges are)
532 #if DEBUG_COMBINE_INSTRUMENTS
533 printf("src refilled "); fflush(stdout);
534 #endif
535 fillDimValues(srcDimValues, srcDimCase, inRgn, false);
536 srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);
537 #if DEBUG_COMBINE_INSTRUMENTS
538 printf("reselected srcDimRgn=%lx\n", (uint64_t)srcDimRgn);
539 printf("srcSample='%s'\n",
540 (!srcDimRgn->pSample ? "NULL" : srcDimRgn->pSample->pInfo->Name.c_str())
541 );
542 #endif
543 }
544 }
545
546 // Schedule copy operation of source -> target DimensionRegion for the
547 // time after all nested loops have been traversed. We have to postpone
548 // the actual copy operations this way, because otherwise it would
549 // overwrite informations inside the destination DimensionRegion object
550 // that we need to read in the code block above.
551 e.src = srcDimRgn;
552 e.dst = dstDimRgn;
553 schedule->push_back(e);
554
555 return; // returning from deepest level of function recursion
556 }
557
558 // Copying n dimensions requires n nested loops. That's why this function
559 // is calling itself recursively to provide the required amount of nested
560 // loops. With each call it pops from argument 'dims' and pushes to
561 // argument 'dimCase'.
562
563 Dimensions::iterator itDimension = dims.begin();
564 gig::dimension_t type = itDimension->first;
565 DimensionZones zones = itDimension->second;
566 dims.erase(itDimension);
567
568 int iZone = 0;
569 for (DimensionZones::iterator itZone = zones.begin();
570 itZone != zones.end(); ++itZone, ++iZone)
571 {
572 DLS::range_t zoneRange = *itZone;
573 gig::dimension_def_t* def = outRgn->GetDimensionDefinition(type);
574 dimCase[type] = (def->split_type == gig::split_type_bit) ? iZone : zoneRange.low;
575
576 // recurse until 'dims' is exhausted (and dimCase filled up with concrete value)
577 scheduleCopyDimensionRegions(outRgn, inRgn, dims, mainDim, iDstMainBit, iSrcMainBit, schedule, dimCase);
578 }
579 }
580
581 static OrderedRegionGroup sortRegionGroup(const RegionGroup& group, const std::vector<gig::Instrument*>& instruments) {
582 OrderedRegionGroup result;
583 for (std::vector<gig::Instrument*>::const_iterator it = instruments.begin();
584 it != instruments.end(); ++it)
585 {
586 RegionGroup::const_iterator itRgn = group.find(*it);
587 if (itRgn == group.end()) continue;
588 result.push_back(
589 std::pair<gig::Instrument*, gig::Region*>(
590 itRgn->first, itRgn->second
591 )
592 );
593 }
594 return result;
595 }
596
597 /** @brief Combine given list of instruments to one instrument.
598 *
599 * Takes a list of @a instruments as argument and combines them to one single
600 * new @a output instrument. For this task, it will create a dimension of type
601 * given by @a mainDimension in the new instrument and copies the source
602 * instruments to those dimension zones.
603 *
604 * @param instruments - (input) list of instruments that shall be combined,
605 * they will only be read, so they will be left untouched
606 * @param gig - (input/output) .gig file where the new combined instrument shall
607 * be created
608 * @param output - (output) on success this pointer will be set to the new
609 * instrument being created
610 * @param mainDimension - the dimension that shall be used to combine the
611 * instruments
612 * @throw RIFF::Exception on any kinds of errors
613 */
614 static void combineInstruments(std::vector<gig::Instrument*>& instruments, gig::File* gig, gig::Instrument*& output, gig::dimension_t mainDimension) {
615 output = NULL;
616
617 // divide the individual regions to (probably even smaller) groups of
618 // regions, coping with the fact that the source regions of the instruments
619 // might have quite different range sizes and start and end points
620 RegionGroups groups = groupByRegionIntersections(instruments);
621 #if DEBUG_COMBINE_INSTRUMENTS
622 std::cout << std::endl << "New regions: " << std::flush;
623 printRanges(groups);
624 std::cout << std::endl;
625 #endif
626
627 if (groups.empty())
628 throw gig::Exception(_("No regions found to create a new instrument with."));
629
630 // create a new output instrument
631 gig::Instrument* outInstr = gig->AddInstrument();
632 outInstr->pInfo->Name = _("NEW COMBINATION");
633
634 // Distinguishing in the following code block between 'horizontal' and
635 // 'vertical' regions. The 'horizontal' ones are meant to be the key ranges
636 // in the output instrument, while the 'vertical' regions are meant to be
637 // the set of source regions that shall be layered to that 'horizontal'
638 // region / key range. It is important to know, that the key ranges defined
639 // in the 'horizontal' and 'vertical' regions might differ.
640
641 // merge the instruments to the new output instrument
642 for (RegionGroups::iterator itGroup = groups.begin();
643 itGroup != groups.end(); ++itGroup) // iterate over 'horizontal' / target regions ...
644 {
645 gig::Region* outRgn = outInstr->AddRegion();
646 outRgn->SetKeyRange(itGroup->first.low, itGroup->first.high);
647 #if DEBUG_COMBINE_INSTRUMENTS
648 printf("---> Start target region %d..%d\n", itGroup->first.low, itGroup->first.high);
649 #endif
650
651 // detect the total amount of zones required for the given main
652 // dimension to build up this combi for current key range
653 int iTotalZones = 0;
654 for (RegionGroup::iterator itRgn = itGroup->second.begin();
655 itRgn != itGroup->second.end(); ++itRgn)
656 {
657 gig::Region* inRgn = itRgn->second;
658 gig::dimension_def_t* def = inRgn->GetDimensionDefinition(mainDimension);
659 iTotalZones += (def) ? def->zones : 1;
660 }
661 #if DEBUG_COMBINE_INSTRUMENTS
662 printf("Required total zones: %d, vertical regions: %d\n", iTotalZones, itGroup->second.size());
663 #endif
664
665 // create all required dimensions for this output region
666 // (except the main dimension used for separating the individual
667 // instruments, we create that particular dimension as next step)
668 Dimensions dims = getDimensionsForRegionGroup(itGroup->second);
669 // the given main dimension which is used to combine the instruments is
670 // created separately after the next code block, and the main dimension
671 // should not be part of dims here, because it also used for iterating
672 // all dimensions zones, which would lead to this dimensions being
673 // iterated twice
674 dims.erase(mainDimension);
675 {
676 std::vector<gig::dimension_t> skipTheseDimensions; // used to prevent a misbehavior (i.e. crash) of the combine algorithm in case one of the source instruments has a dimension with only one zone, which is not standard conform
677
678 for (Dimensions::iterator itDim = dims.begin();
679 itDim != dims.end(); ++itDim)
680 {
681 gig::dimension_def_t def;
682 def.dimension = itDim->first; // dimension type
683 def.zones = itDim->second.size();
684 def.bits = zoneCountToBits(def.zones);
685 if (def.zones < 2) {
686 addWarning(
687 "Attempt to create dimension with type=0x%x with only "
688 "ONE zone (because at least one of the source "
689 "instruments seems to have such a velocity dimension "
690 "with only ONE zone, which is odd)! Skipping this "
691 "dimension for now.",
692 (int)itDim->first
693 );
694 skipTheseDimensions.push_back(itDim->first);
695 continue;
696 }
697 #if DEBUG_COMBINE_INSTRUMENTS
698 std::cout << "Adding new regular dimension type=" << std::hex << (int)def.dimension << std::dec << ", zones=" << (int)def.zones << ", bits=" << (int)def.bits << " ... " << std::flush;
699 #endif
700 outRgn->AddDimension(&def);
701 #if DEBUG_COMBINE_INSTRUMENTS
702 std::cout << "OK" << std::endl << std::flush;
703 #endif
704 }
705 // prevent the following dimensions to be processed further below
706 // (since the respective dimension was not created above)
707 for (int i = 0; i < skipTheseDimensions.size(); ++i)
708 dims.erase(skipTheseDimensions[i]);
709 }
710
711 // create the main dimension (if necessary for current key range)
712 if (iTotalZones > 1) {
713 gig::dimension_def_t def;
714 def.dimension = mainDimension; // dimension type
715 def.zones = iTotalZones;
716 def.bits = zoneCountToBits(def.zones);
717 #if DEBUG_COMBINE_INSTRUMENTS
718 std::cout << "Adding new main combi dimension type=" << std::hex << (int)def.dimension << std::dec << ", zones=" << (int)def.zones << ", bits=" << (int)def.bits << " ... " << std::flush;
719 #endif
720 outRgn->AddDimension(&def);
721 #if DEBUG_COMBINE_INSTRUMENTS
722 std::cout << "OK" << std::endl << std::flush;
723 #endif
724 } else {
725 dims.erase(mainDimension);
726 }
727
728 // for the next task we need to have the current RegionGroup to be
729 // sorted by instrument in the same sequence as the 'instruments' vector
730 // argument passed to this function (because the std::map behind the
731 // 'RegionGroup' type sorts by memory address instead, and that would
732 // sometimes lead to the source instruments' region to be sorted into
733 // the wrong target layer)
734 OrderedRegionGroup currentGroup = sortRegionGroup(itGroup->second, instruments);
735
736 // schedule copying the source dimension regions to the target dimension
737 // regions
738 CopyAssignSchedule schedule;
739 int iDstMainBit = 0;
740 for (OrderedRegionGroup::iterator itRgn = currentGroup.begin();
741 itRgn != currentGroup.end(); ++itRgn) // iterate over 'vertical' / source regions ...
742 {
743 gig::Region* inRgn = itRgn->second;
744 #if DEBUG_COMBINE_INSTRUMENTS
745 printf("[source region of '%s']\n", inRgn->GetParent()->pInfo->Name.c_str());
746 #endif
747
748 // determine how many main dimension zones this input region requires
749 gig::dimension_def_t* def = inRgn->GetDimensionDefinition(mainDimension);
750 const int inRgnMainZones = (def) ? def->zones : 1;
751
752 for (uint iSrcMainBit = 0; iSrcMainBit < inRgnMainZones; ++iSrcMainBit, ++iDstMainBit) {
753 scheduleCopyDimensionRegions(
754 outRgn, inRgn, dims, mainDimension,
755 iDstMainBit, iSrcMainBit, &schedule
756 );
757 }
758 }
759
760 // finally copy the scheduled source -> target dimension regions
761 for (uint i = 0; i < schedule.size(); ++i) {
762 CopyAssignSchedEntry& e = schedule[i];
763
764 // backup the target DimensionRegion's current dimension zones upper
765 // limits (because the target DimensionRegion's upper limits are
766 // already defined correctly since calling AddDimension(), and the
767 // CopyAssign() call next, will overwrite those upper limits
768 // unfortunately
769 DimensionRegionUpperLimits dstUpperLimits = getDimensionRegionUpperLimits(e.dst);
770 DimensionRegionUpperLimits srcUpperLimits = getDimensionRegionUpperLimits(e.src);
771
772 // now actually copy over the current DimensionRegion
773 const gig::Region* const origRgn = e.dst->GetParent(); // just for sanity check below
774 e.dst->CopyAssign(e.src);
775 assert(origRgn == e.dst->GetParent()); // if gigedit is crashing here, then you must update libgig (to at least SVN r2547, v3.3.0.svn10)
776
777 // restore all original dimension zone upper limits except of the
778 // velocity dimension, because the velocity dimension zone sizes are
779 // allowed to differ for individual DimensionRegions in gig v3
780 // format
781 //
782 // if the main dinension is the 'velocity' dimension, then skip
783 // restoring the source's original velocity zone limits, because
784 // dealing with merging that is not implemented yet
785 // TODO: merge custom velocity splits if main dimension is the velocity dimension (for now equal sized velocity zones are used if mainDim is 'velocity')
786 if (srcUpperLimits.count(gig::dimension_velocity) && mainDimension != gig::dimension_velocity) {
787 if (!dstUpperLimits.count(gig::dimension_velocity)) {
788 addWarning("Source instrument seems to have a velocity dimension whereas new target instrument doesn't!");
789 } else {
790 dstUpperLimits[gig::dimension_velocity] =
791 (e.velocityZone >= e.totalSrcVelocityZones)
792 ? 127 : srcUpperLimits[gig::dimension_velocity];
793 }
794 }
795 restoreDimensionRegionUpperLimits(e.dst, dstUpperLimits);
796 }
797 }
798
799 // success
800 output = outInstr;
801 }
802
803 ///////////////////////////////////////////////////////////////////////////
804 // class 'CombineInstrumentsDialog'
805
806 CombineInstrumentsDialog::CombineInstrumentsDialog(Gtk::Window& parent, gig::File* gig)
807 : ManagedDialog(_("Combine Instruments"), parent, true),
808 m_gig(gig), m_fileWasChanged(false), m_newCombinedInstrument(NULL),
809 m_cancelButton(_("_Cancel"), true), m_OKButton(_("_OK"), true),
810 m_descriptionLabel(), m_tableDimCombo(2, 2), m_comboDimType(),
811 m_labelDimType(Glib::ustring(_("Combine by Dimension:")) + " ", Gtk::ALIGN_END)
812 {
813 m_scrolledWindow.add(m_treeView);
814 m_scrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
815
816 get_vbox()->pack_start(m_descriptionLabel, Gtk::PACK_SHRINK);
817 get_vbox()->pack_start(m_tableDimCombo, Gtk::PACK_SHRINK);
818 get_vbox()->pack_start(m_scrolledWindow);
819 get_vbox()->pack_start(m_buttonBox, Gtk::PACK_SHRINK);
820
821 #if GTKMM_MAJOR_VERSION >= 3
822 m_descriptionLabel.set_line_wrap();
823 #endif
824 m_descriptionLabel.set_text(_(
825 "Select at least two instruments below that shall be combined (as "
826 "separate dimension zones of the selected dimension type) as a new "
827 "instrument. The original instruments remain untouched.\n\n"
828 "You may use this tool for example to combine solo instruments into "
829 "a combi sound arrangement by selecting the 'layer' dimension, or you "
830 "might combine similar sounding solo sounds into separate velocity "
831 "split layers by using the 'velocity' dimension, and so on."
832 ));
833
834 // add dimension type combo box
835 {
836 int iLayerDimIndex = -1;
837 Glib::RefPtr<Gtk::ListStore> refComboModel = Gtk::ListStore::create(m_comboDimsModel);
838 for (int i = 0x01, iRow = 0; i < 0xff; i++) {
839 Glib::ustring sType =
840 dimTypeAsString(static_cast<gig::dimension_t>(i));
841 if (sType.find("Unknown") != 0) {
842 Gtk::TreeModel::Row row = *(refComboModel->append());
843 row[m_comboDimsModel.m_type_id] = i;
844 row[m_comboDimsModel.m_type_name] = sType;
845 if (i == gig::dimension_layer) iLayerDimIndex = iRow;
846 iRow++;
847 }
848 }
849 m_comboDimType.set_model(refComboModel);
850 m_comboDimType.pack_start(m_comboDimsModel.m_type_id);
851 m_comboDimType.pack_start(m_comboDimsModel.m_type_name);
852 m_tableDimCombo.attach(m_labelDimType, 0, 1, 0, 1);
853 m_tableDimCombo.attach(m_comboDimType, 1, 2, 0, 1);
854 m_comboDimType.set_active(iLayerDimIndex); // preselect "layer" dimension
855 }
856
857 m_refTreeModel = Gtk::ListStore::create(m_columns);
858 m_treeView.set_model(m_refTreeModel);
859 m_treeView.set_tooltip_text(_(
860 "Use SHIFT + left click or CTRL + left click to select the instruments "
861 "you want to combine."
862 ));
863 m_treeView.append_column("Instrument", m_columns.m_col_name);
864 m_treeView.set_headers_visible(false);
865 m_treeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
866 m_treeView.get_selection()->signal_changed().connect(
867 sigc::mem_fun(*this, &CombineInstrumentsDialog::onSelectionChanged)
868 );
869 m_treeView.show();
870
871 for (int i = 0; true; ++i) {
872 gig::Instrument* instr = gig->GetInstrument(i);
873 if (!instr) break;
874
875 #if DEBUG_COMBINE_INSTRUMENTS
876 {
877 std::cout << "Instrument (" << i << ") '" << instr->pInfo->Name << "' Regions: " << std::flush;
878 for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
879 std::cout << rgn->KeyRange.low << ".." << rgn->KeyRange.high << ", " << std::flush;
880 }
881 std::cout << std::endl;
882 }
883 std::cout << std::endl;
884 #endif
885
886 Glib::ustring name(gig_to_utf8(instr->pInfo->Name));
887 Gtk::TreeModel::iterator iter = m_refTreeModel->append();
888 Gtk::TreeModel::Row row = *iter;
889 row[m_columns.m_col_name] = name;
890 row[m_columns.m_col_instr] = instr;
891 }
892
893 m_buttonBox.set_layout(Gtk::BUTTONBOX_END);
894 m_buttonBox.set_border_width(5);
895 m_buttonBox.pack_start(m_cancelButton, Gtk::PACK_SHRINK);
896 m_buttonBox.pack_start(m_OKButton, Gtk::PACK_SHRINK);
897 m_buttonBox.show();
898
899 m_cancelButton.show();
900 m_OKButton.set_sensitive(false);
901 m_OKButton.show();
902
903 m_cancelButton.signal_clicked().connect(
904 sigc::mem_fun(*this, &CombineInstrumentsDialog::hide)
905 );
906
907 m_OKButton.signal_clicked().connect(
908 sigc::mem_fun(*this, &CombineInstrumentsDialog::combineSelectedInstruments)
909 );
910
911 show_all_children();
912
913 // show a warning to user if he uses a .gig in v2 format
914 if (gig->pVersion->major < 3) {
915 Glib::ustring txt = _(
916 "You are currently using a .gig file in old v2 format. The current "
917 "combine algorithm will most probably fail trying to combine "
918 "instruments in this old format. So better save the file in new v3 "
919 "format before trying to combine your instruments."
920 );
921 Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_WARNING);
922 msg.run();
923 }
924 }
925
926 void CombineInstrumentsDialog::combineSelectedInstruments() {
927 std::vector<gig::Instrument*> instruments;
928 std::vector<Gtk::TreeModel::Path> v = m_treeView.get_selection()->get_selected_rows();
929 for (uint i = 0; i < v.size(); ++i) {
930 Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(v[i]);
931 Gtk::TreeModel::Row row = *it;
932 Glib::ustring name = row[m_columns.m_col_name];
933 gig::Instrument* instrument = row[m_columns.m_col_instr];
934 #if DEBUG_COMBINE_INSTRUMENTS
935 printf("Selection '%s' 0x%lx\n\n", name.c_str(), int64_t((void*)instrument));
936 #endif
937 instruments.push_back(instrument);
938 }
939
940 g_warnings.clear();
941
942 try {
943 // which main dimension was selected in the combo box?
944 gig::dimension_t mainDimension;
945 {
946 Gtk::TreeModel::iterator iterType = m_comboDimType.get_active();
947 if (!iterType) throw gig::Exception("No dimension selected");
948 Gtk::TreeModel::Row rowType = *iterType;
949 if (!rowType) throw gig::Exception("Something is wrong regarding dimension selection");
950 int iTypeID = rowType[m_comboDimsModel.m_type_id];
951 mainDimension = static_cast<gig::dimension_t>(iTypeID);
952 }
953
954 // now start the actual cobination task ...
955 combineInstruments(instruments, m_gig, m_newCombinedInstrument, mainDimension);
956 } catch (RIFF::Exception e) {;
957 Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
958 msg.run();
959 return;
960 } catch (...) {
961 Glib::ustring txt = _("An unknown exception occurred!");
962 Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
963 msg.run();
964 return;
965 }
966
967 if (!g_warnings.empty()) {
968 Glib::ustring txt = _(
969 "Combined instrument was created successfully, but there were warnings:"
970 );
971 txt += "\n\n";
972 for (Warnings::const_iterator itWarn = g_warnings.begin();
973 itWarn != g_warnings.end(); ++itWarn)
974 {
975 txt += "-> " + *itWarn + "\n";
976 }
977 txt += "\n";
978 txt += _(
979 "You might also want to check the console for further warnings and "
980 "error messages."
981 );
982 Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_WARNING);
983 msg.run();
984 }
985
986 // no error occurred
987 m_fileWasChanged = true;
988 hide();
989 }
990
991 void CombineInstrumentsDialog::onSelectionChanged() {
992 std::vector<Gtk::TreeModel::Path> v = m_treeView.get_selection()->get_selected_rows();
993 m_OKButton.set_sensitive(v.size() >= 2);
994 }
995
996 bool CombineInstrumentsDialog::fileWasChanged() const {
997 return m_fileWasChanged;
998 }
999
1000 gig::Instrument* CombineInstrumentsDialog::newCombinedInstrument() const {
1001 return m_newCombinedInstrument;
1002 }

  ViewVC Help
Powered by ViewVC