-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJS_TransferByUV.ls
677 lines (596 loc) · 18.6 KB
/
JS_TransferByUV.ls
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
/*------------------------------------------------------------------------------
Modeler LScript: Transfer By UV
Version: 1.2
Author: Johan Steen
Author URI: http://www.artstorm.net/
Date: 27 Oct 2010
Description: Transfers VMaps from the background to the background by using
the UV coordinates as reference.
Copyright (c) 2010, Johan Steen
All Rights Reserved.
Use is subject to license terms.
------------------------------------------------------------------------------*/
@version 2.4
@warnings
@script modeler
@name "JS_TransferByUV"
// Main Variables
tbuv_version = "1.2";
tbuv_date = "27 October 2010";
cfg_file = getdir(SETTINGSDIR) + getsep() + "JS_TransferByUV.cfg";
// GUI Settings
var tolerance = 0.02;
var VMType = 1; // 1 = Weights, 2 = Morphs, 3 = Selections
var interpolate = false;
// GUI Gadgets
var ctlVMList, ctlInterpolate;
// Misc
var fg;
var bg;
// Point Variables
var uvMap; // Holds the selected UV map
var iTotBGPnts; // Integer with total number of points in BG layer
var iTotFGPnts; // Integer with total number of selected points in FG layer
var globalPntCnt; // Integer with total number of poins in FG layer
var aBGPntData; // Array that keeps track of all point coords and UV coords
var selPnts; // Array that keeps track of current user point selection
// Stats Variables
var statsNoUV = 0;
var statsUnMatched = nil;
// Vertex Maps
var VMDim;
var VMNamePost = nil;
var arrWeights;
var arrMorphs;
var arrSelections;
var arrListVMaps; // The array in the Listbox (copied from the others).
var arrSelectedVMaps; // Array that contains the VMaps selected in the listbox.
main {
// Make all preparations so the plugin finds enough data to be used.
// --------------------------------------------------------------------------------
// Get selected UV Map
uvMap = VMap(VMTEXTURE, 0) || error("Please select a UV map."); // By using 0, the modeler selected UV map is acquired.
// Get total number of points, not caring about selections
selmode(GLOBAL);
globalPntCnt = pointcount();
// Get user selected point count
selmode(USER);
var iTotFGPnts = pointcount();
// Get the layers
fg = lyrfg();
bg = lyrbg();
// Error handling: If no BG selected or more than 1 BG layer selected, exit plugin
if(bg == nil) error("Please select a BG layer.");
if(bg.size() > 1) error("Please select only one BG layer.");
// Error handling: if FG is empty, exit plugin
if(iTotFGPnts <= 0) error("Please use a FG layer with geometry.");
// If selected points differs from total points, store the selection
if (globalPntCnt != iTotFGPnts) {
storeSelPnts();
}
// Switch to BG, and Get number of points in BG layer
lyrsetfg(bg);
iTotBGPnts = pointcount();
// Error handling: If BG is empty, exit plugin
if(iTotBGPnts == 0){
lyrsetfg(fg);
lyrsetbg(bg);
error("Please use a BG layer with geometry.");
}
// Retrieve all available Vertex Maps, and set Default
getVertexMaps();
arrListVMaps = arrWeights;
//
// Open the main window and collect / process user input.
// --------------------------------------------------------------------------------
// Restore layer selections
lyrsetfg(fg);
lyrsetbg(bg);
var mainWin = openMainWin();
if (mainWin == false)
return;
/* Window Closed, start the process */
undogroupbegin();
// Switch to BG again
lyrsetfg(bg);
// Initialize the progress bar (iTotBGPnts for looping the BG array + iTotFGPnts when looping though the FG points )
moninit((iTotBGPnts + 1) + iTotFGPnts);
// Get all info from bg layer
var abort = scanBGData();
// Update number of BG Points (if some lacked UV coords)
// using iTotBGPnts on each loop later, is faster than using .size() on each iteration
iTotBGPnts = aBGPntData.size();
// Restore layer selections
lyrsetfg(fg);
lyrsetbg(bg);
// If aborted during getBGInfo, exit
if(abort) return true;
abort = matchUV();
monend();
undogroupend();
// If aborted during matching, return without displaying the result window
if (abort)
return;
openResultWin();
}
/*
* Function to retrieve all Vertex Maps used.
*
* @returns Nothing
*/
getVertexMaps {
editbegin();
var vmap = VMap();
while(vmap) {
switch (vmap.type) {
case VMWEIGHT: arrWeights += vmap.name; break;
case VMMORPH: arrMorphs += vmap.name; break;
case VMSELECT: arrSelections += vmap.name; break;
}
vmap = vmap.next();
}
editend();
}
/*
* Function to loop through the BG points and build an array of all uv/vmap values
*
* @returns Nothing
*/
scanBGData
{
aBGPntData = nil;
editbegin();
var ctr = 1;
foreach(p, points)
{
// Increase the progress bar
if(monstep()){
editend(ABORT);
return true;
}
// Get the UV values
var uv = uvMap.getValue(p);
// Check so the point contains UV data
if(uv == nil){
// skip rest of the loop and continue with the next point
continue;
}
// If UV data was present
aBGPntData[ctr, 1] = <uv[1],uv[2],0>;
for (i = 1; i <= arrSelectedVMaps.count(); i++) {
var vm = VMap(VMType, arrSelectedVMaps[i]);
if(vm.isMapped(p)) {
aBGPntData[ctr, i + 1] = vm.getValue(p);
// Special case for selection maps
if (vm.type == VMSELECT) {
aBGPntData[ctr, i + 1] = true;
}
} else {
aBGPntData[ctr, i + 1] = nil;
}
}
ctr++;
}
editend();
return false;
}
/*
* Functions to match the UV data between the layers
*
* @returns false for success, true for abort.
*/
matchUV {
// If selected points differs from total points, get the selection
if (globalPntCnt != iTotFGPnts) {
getSelPnts();
}
editbegin();
// loop through all points in foreground
foreach(p,points){
// Get the UV for current point
var uv = uvMap.getValue(p);
var arrGridMatches[5,2];
if(uv == nil) {
// If the point lacks UV coords
statsNoUV++;
} else {
// Interpolated or standard match
if (interpolate == true)
arrGridMatches = findGridMatch(uv);
else
matchPnt = findMatch(uv);
// If a match was found, copy the VMap values
if (arrGridMatches[1,1] == true || matchPnt != nil) {
if (interpolate == true)
transferVMapGrid(p, arrGridMatches);
else
transferVMap(p, matchPnt);
} else {
// if no match was found, add the unmatched point to the stats array
statsUnMatched += p;
}
}
// Increase the progressbar
if(monstep()){
monend();
editend(ABORT);
return true;
}
}
editend();
return false;
}
findMatch: uv {
// Convert the UV coords to a vector
var uvVec = <uv[1],uv[2],0>;
var bestMatch = nil; // Keep track of current best match
var matchPnt = nil;
// Loop through all BG UV coords
for (i=1; i <= iTotBGPnts; i++) {
// Get the distance between the FG and BG UV coord vectors
var getDist = vmag(uvVec - aBGPntData[i,1]);
// If perfect match is found
if (getDist == 0) {
// match immediately and break the for loop
matchPnt = i;
break;
}
// Check if distance is smaller than current best match, and that distance is within the tolerance
if (getDist < bestMatch && getDist < tolerance) {
bestMatch = getDist;
matchPnt = i;
}
}
return matchPnt;
}
/*
* Functions to transfer the VMaps
*
* @returns Nothing
*/
transferVMap: p, matchPnt {
for (i = 1; i <= arrSelectedVMaps.count(); i++) {
if (aBGPntData[matchPnt, i + 1] != nil) {
var vm = VMap(VMType, arrSelectedVMaps[i] + VMNamePost, VMDim);
vm.setValue(p, aBGPntData[matchPnt, i + 1]);
}
}
}
/*
* Functions to interpolate the weight values
*
*
*/
findGridMatch: uv {
// Convert the UV coords to a vector
var uvVec = <uv[1],uv[2],0>;
var bestMatch = nil; // Keep track of current best match
var matchPnt = nil;
var arrGridMatches = array(5, 2); // Initializes an array to keep track of best matches in a grid [1] = pid in bgarr, [2] = dist
arrGridMatches[1, 1] = false;
arrGridMatches[1, 2] = 0;
// Loop through all BG UV coords
for (i=1; i <= iTotBGPnts; i++) {
// Get the distance and direction between the FG and BG UV coord vectors
var distance = vmag(uvVec - aBGPntData[i,1]);
var direction = normalize(aBGPntData[i,1] - uvVec);
// If perfect match is found
if (distance == 0) {
// match immediately and break the for loop
matchPnt = i;
for (j = 2; j <= 5; j++) {
arrGridMatches[j, 1] = i;
arrGridMatches[j, 2] = 0;
arrGridMatches[1, 1] = true;
arrGridMatches[1, 2] = 15;
}
break;
}
/* arrGridMatches - Multidimensional array
slot 1,1: Match(es) found. slot 1,2: Binary number getting flagged for each grid section matched (00001111)
slot 2-5,1-2: grid section, 1: point id - 2: distance
*/
// Check if distance is smaller than current best match, and that distance is within the tolerance
if (distance < tolerance) {
// BR = +-, TR = ++, BL = --, TL = -+
if (direction.x >= 0 && direction.y >= 0 && distance < arrGridMatches[2, 2]) {
arrGridMatches[1, 1] = true;
arrGridMatches[1, 2] = arrGridMatches[1, 2]|1;
arrGridMatches[2, 1] = i;
arrGridMatches[2, 2] = distance;
}
if (direction.x >= 0 && direction.y <= 0 && distance < arrGridMatches[3, 2]) {
arrGridMatches[1, 1] = true;
arrGridMatches[1, 2] = arrGridMatches[1, 2]|2;
arrGridMatches[3, 1] = i;
arrGridMatches[3, 2] = distance;
}
if (direction.x <= 0 && direction.y <= 0 && distance < arrGridMatches[4, 2]) {
arrGridMatches[1, 1] = true;
arrGridMatches[1, 2] = arrGridMatches[1, 2]|4;
arrGridMatches[4, 1] = i;
arrGridMatches[4, 2] = distance;
}
if (direction.x <= 0 && direction.y >= 0 && distance < arrGridMatches[5, 2]) {
arrGridMatches[1, 1] = true;
arrGridMatches[1, 2] = arrGridMatches[1, 2]|8;
arrGridMatches[5, 1] = i;
arrGridMatches[5, 2] = distance;
}
}
}
return arrGridMatches;
}
transferVMapGrid: p, arrGridMatches {
var arrPnts = nil;
var arrDistances = nil;
var arrFalloffs = nil;
var nTotalFalloff = 0;
// Collect the point info into arrays.
if ((arrGridMatches[1, 2]&1) > 0) { arrPnts += arrGridMatches[2,1]; arrDistances += arrGridMatches[2,2]; }
if ((arrGridMatches[1, 2]&2) > 0) { arrPnts += arrGridMatches[3,1]; arrDistances += arrGridMatches[3,2]; }
if ((arrGridMatches[1, 2]&4) > 0) { arrPnts += arrGridMatches[4,1]; arrDistances += arrGridMatches[4,2]; }
if ((arrGridMatches[1, 2]&8) > 0) { arrPnts += arrGridMatches[5,1]; arrDistances += arrGridMatches[5,2]; }
// Calculate falloff
for (i = 1; i <= arrPnts.count(); i++) {
if (arrDistances[i] != 0) {
var falloff = 1 / (arrDistances[i]); // 1/x seems to give reliable falloff values when combined
arrFalloffs += falloff;
nTotalFalloff = nTotalFalloff + falloff;
} else {
arrFalloffs += 0;
nTotalFalloff = 0;
}
}
// Normalize the falloff
if (nTotalFalloff != 0) {
for (i = 1; i <= arrFalloffs.count(); i++) {
var falloff = arrFalloffs[i];
falloff = falloff / nTotalFalloff;
arrFalloffs[i] = falloff;
}
}
// Loop through all selected weight maps
for (i = 1; i <= arrSelectedVMaps.count(); i++) {
// Loop through all BG points matched and see if they have the same value
var same = false;
var check = nil;
for (j = 1; j <= arrPnts.count(); j++) {
var pid = arrPnts[j];
if (aBGPntData[pid, i + 1] != nil) {
var weight = aBGPntData[pid, i + 1];
weight = weight[1];
if ( weight == check || check == nil) {
same = true;
} else {
same = false;
continue;
}
check = weight;
}
}
// Calculate the new weight value
vmval = number(0);
for (j = 1; j <= arrPnts.count(); j++) {
pid = arrPnts[j];
falloff = arrFalloffs[j];
if (aBGPntData[pid, i + 1] != nil) {
var weight = (aBGPntData[pid, i + 1]);
var distance = arrDistances[j];
weight = weight[1].asNum();
// if all matched weight where the same, just apply them to make sure no interpolation is made in those regions.
if (distance == 0 || nTotalFalloff == 0 || same == true) {
weight = weight * (1 / arrPnts.count());
} else {
weight = weight * falloff;
}
vmval = vmval + weight;
}
}
// And apply it
if (vmval != nil) {
var vm = VMap(VMType, arrSelectedVMaps[i] + VMNamePost, VMDim);
vm.setValue(p, vmval);
}
}
}
/*
* Functions to handle point selections
*
* @returns Nothing
*/
// Stores all selected Point ID's in an array
storeSelPnts
{
editbegin();
foreach(p, points) {
selPnts += p;
}
editend();
}
// Selects all points stored in the selection array
getSelPnts
{
selmode(USER);
selpolygon(CLEAR); // Switch to polygon mode, to speed up drawing of point selections
selpoint(SET, POINTID, selPnts);
selpoint(SET,NPEQ,1000); // Switch back to point selection mode (Dummy selection value to keep current selection)
}
/*
* Functions to handle the windows
*
* @returns Nothing
*/
// Main Window, Returns false for cancel
openMainWin
{
load_config();
reqbegin("Transfer By UV v" + tbuv_version);
reqsize(248,444); // Width, Height
ctlTol = ctlnumber("Tolerance", tolerance);
ctlVMType = ctlpopup("VMap Type", VMType, @ "Weights","Morphs","Selections" @);
ctlInterpolate = ctlcheckbox("Weight Interpolation", interpolate);
ctlVMList = ctllistbox("Vertex Maps", 204, 274, "VMListSize", "VMListItem");
ctlAbout = ctlbutton("About the Plugin", 73, "openAboutWin");
ctlSep1 = ctlsep();
ctlSep2 = ctlsep();
var yComp = 0;
ctlposition(ctlVMType, 25, 10);
ctlposition(ctlTol, 32, 32, 204);
ctlposition(ctlInterpolate, 86, 54, 150);
ctlposition(ctlSep1, 0, 82);
ctlposition(ctlVMList, 10, 92);
ctlposition(ctlSep2, 0, 376);
ctlposition(ctlAbout, 86, 384, 150);
// Refresh controller on VMap Type Change
ctlrefresh(ctlVMType, "refreshMainWin");
if (!reqpost())
return false;
// Collect the input
tolerance = getvalue(ctlTol);
VMType = getvalue(ctlVMType);
// Set interpolate to false no matter what is set if not Weight mode
interpolate = (VMType == 1) ? getvalue(ctlInterpolate) : 0;
save_config();
// Convert VMTYPE to LScript Constant
switch (VMType) {
case 1: VMType = VMWEIGHT; VMDim = 1; break;
case 2: VMType = VMMORPH; VMDim = 3; break;
case 3: VMType = VMSELECT; VMDim = 1; VMNamePost = "_copy"; break;
}
// Get the names of the selected VMaps
var vmaps_idx = getvalue(ctlVMList);
for (i = 1; i <= vmaps_idx.count(); i++)
arrSelectedVMaps += arrListVMaps[vmaps_idx[i]];
reqend();
return true;
}
// Refresh the GUI when VMap type changes
refreshMainWin: value
{
switch (value) {
case 1: arrListVMaps = arrWeights; ctlInterpolate.active(true); break;
case 2: arrListVMaps = arrMorphs; ctlInterpolate.active(false); break;
case 3: arrListVMaps = arrSelections; ctlInterpolate.active(false); break;
}
// Clear listbox Selection
setvalue(ctlVMList, nil);
requpdate();
}
// UDFs for the Listbox
VMListSize {
return(arrListVMaps.count());
}
VMListItem: index {
return(arrListVMaps[index]);
}
// Result Window
openResultWin
{
reqbegin("Transfer By UV");
reqsize(240,170); // X,Y
// Add result info here
c2 = ctltext("","Points without UVs: " + statsNoUV);
ctlposition(c2,10,10,200,13);
c3 = ctltext("","Unmatched Points: " + statsUnMatched.size());
ctlposition(c3,10,30,200,13);
c10 = ctlcheckbox("Create selection set of unmatched points", false);
ctlposition(c10,10,76);
return if !reqpost();
// Create selection set of unmatched points
if (getvalue(c10) == true && statsUnMatched.size() != 0) {
selmode(USER);
editbegin();
selMap = VMap(VMSELECT,"UnMatched",1);
foreach(p,statsUnMatched)
{
selMap.setValue(p,1);
}
editend();
}
reqend();
}
// About Window
openAboutWin
{
reqbegin("About Transfer By UV");
reqsize(330,160);
ctlText1 = ctltext("","Transfer By UV", "Version: " + tbuv_version, "Build Date: " + tbuv_date);
ctlText4 = ctltext("","Programming by Johan Steen.");
ctlText5 = ctltext("","Variation of an idea by Lee Perry-Smith.");
ctlSep1 = ctlsep();
ctlposition(ctlText1, 10, 10);
ctlposition(ctlSep1, 0, 64);
ctlposition(ctlText4, 10, 78);
ctlposition(ctlText5, 10, 100);
url_johan = "http://www.artstorm.net/";
url_lee = "http://www.ir-ltd.net/";
url_docs = "http://www.artstorm.net/plugins/transfer-by-uv/";
ctlurl1 = ctlbutton("Artstorm", 100, "goto_url", "url_johan");
ctlurl2 = ctlbutton("Infinite Realities", 100, "goto_url", "url_lee");
ctlurl3 = ctlbutton("Help", 100, "goto_url", "url_docs");
ctlposition(ctlurl1, 220, 75);
ctlposition(ctlurl2, 220, 97);
ctlposition(ctlurl3, 220, 10);
return if !reqpost();
reqend();
}
/*
* Load and apply the configuration file
* @since 1.2
* @returns Nothing
*/
load_config
{
// Open file
loader = File(cfg_file, "r");
// Check if file was opened
if(loader) {
// Loop util eof
while( !loader.eof() ) {
parsed_line = loader.parse("\t");
// Apply the settings
if (parsed_line[1] == "tolerance") tolerance = number(parsed_line[2]);
if (parsed_line[1] == "vm_type") VMType = number(parsed_line[2]);
if (parsed_line[1] == "interpolate") interpolate = number(parsed_line[2]);
}
// Close file
loader.close();
}
}
/*
* Save the current settings to the configuration file
* @since 1.2
* @returns Nothing
*/
save_config
{
// Open file
saver = File(cfg_file, "w");
// Check if the file was openend
if (saver) {
// Save the settings with tab separation
saver.writeln("tolerance", "\t", tolerance);
saver.writeln("vm_type", "\t", VMType);
saver.writeln("interpolate", "\t", interpolate);
// Close file
saver.close();
}
}
/*
* Opens a website in the system's browser
* @since 1.1
* @modified 1.2
* @param url (string) URL to open
* @returns Nothing
*/
goto_url: url
{
// Query the environment for the command line interpreter
cmd_ln = string(getenv("comspec"));
// Spawn the process
spawn_id = spawn(cmd_ln, " /C start ", url);
// If the spawn was unsuccessful, notify the user
if (spawn_id == nil)
info ("Failed to open website ", url);
}