-
Notifications
You must be signed in to change notification settings - Fork 13
/
widget.js
2222 lines (1926 loc) · 96.1 KB
/
widget.js
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* global requirejs cprequire cpdefine chilipeppr THREE ClipperLib */
// Defining the globals above helps Cloud9 not show warnings for those variables
// ChiliPeppr Widget/Element Javascript
requirejs.config({
/*
Dependencies can be defined here. ChiliPeppr uses require.js so
please refer to http://requirejs.org/docs/api.html for info.
Most widgets will not need to define Javascript dependencies.
Make sure all URLs are https and http accessible. Try to use URLs
that start with // rather than http:// or https:// so they simply
use whatever method the main page uses.
Also, please make sure you are not loading dependencies from different
URLs that other widgets may already load like jquery, bootstrap,
three.js, etc.
You may slingshot content through ChiliPeppr's proxy URL if you desire
to enable SSL for non-SSL URL's. ChiliPeppr's SSL URL is
https://i2dcui.appspot.com which is the SSL equivalent for
http://chilipeppr.com
*/
paths: {
// Example of how to define the key (you make up the key) and the URL
// Make sure you DO NOT put the .js at the end of the URL
// SmoothieCharts: '//smoothiecharts.org/smoothie',
Snap: '//i2dcui.appspot.com/slingshot?url=http://snapsvg.io/assets/js/snap.svg-min.js',
//Snap: '//i2dcui.appspot.com/slingshot?url=https://raw.githubusercontent.com/adobe-webplatform/Snap.svg/master/src/svg.js'
ThreeProjector: '//i2dcui.appspot.com/geturl?url=http://threejs.org/examples/js/renderers/Projector.js',
Clipper: '//i2dcui.appspot.com/js/clipper/clipper_unminified'
},
shim: {
// See require.js docs for how to define dependencies that
// should be loaded before your script/widget.
}
});
cprequire_test(["inline:com-zipwhip-widget-svg2gcode"], function(myWidget) {
// Test this element. This code is auto-removed by the chilipeppr.load()
// when using this widget in production. So use the cpquire_test to do things
// you only want to have happen during testing, like loading other widgets or
// doing unit tests. Don't remove end_test at the end or auto-remove will fail.
// Please note that if you are working on multiple widgets at the same time
// you may need to use the ?forcerefresh=true technique in the URL of
// your test widget to force the underlying chilipeppr.load() statements
// to referesh the cache. For example, if you are working on an Add-On
// widget to the Eagle BRD widget, but also working on the Eagle BRD widget
// at the same time you will have to make ample use of this technique to
// get changes to load correctly. If you keep wondering why you're not seeing
// your changes, try ?forcerefresh=true as a get parameter in your URL.
console.log("test running of " + myWidget.id);
// load 3dviewer
// have to tweak our own widget to get it above the 3dviewer
$('#' + myWidget.id).css('position', 'relative');
//$('#' + myWidget.id).css('background', 'none');
$('#' + myWidget.id).css('width', '320px');
$('body').prepend('<div id="3dviewer"></div>');
chilipeppr.load(
"#3dviewer",
"http://raw.githubusercontent.com/chilipeppr/widget-3dviewer/master/auto-generated-widget.html",
function() {
cprequire(['inline:com-chilipeppr-widget-3dviewer'], function (threed) {
threed.init({
doMyOwnDragDrop: false
});
// hide toolbar for room
$('#com-chilipeppr-widget-3dviewer .panel-heading').addClass("hidden");
// only init eagle widget once 3d is loaded
// init my widget
// myWidget.init(function() {
// myWidget.activate();
// });
myWidget.init();
myWidget.activate();
});
});
// load flash message
$('body').prepend('<div id="testDivForFlashMessageWidget"></div>');
chilipeppr.load(
"#testDivForFlashMessageWidget",
"http://fiddle.jshell.net/chilipeppr/90698kax/show/light/",
function() {
console.log("mycallback got called after loading flash msg module");
cprequire(["inline:com-chilipeppr-elem-flashmsg"], function(fm) {
//console.log("inside require of " + fm.id);
fm.init();
});
}
);
// load drag/drop widget that the workspace usually loads
$('body').prepend('<div id="test-drag-drop"></div>');
chilipeppr.load("#test-drag-drop", "http://fiddle.jshell.net/chilipeppr/Z9F6G/show/light/",
function () {
cprequire(
["inline:com-chilipeppr-elem-dragdrop"],
function (dd) {
dd.init();
dd.bind("body", null);
});
});
$('#' + myWidget.id).css('margin', '20px');
$('title').html(myWidget.name);
// $('#' + myWidget.id).css('background', 'none');
// test activate/deactivate
var testDeactivate = function() {
setTimeout(myWidget.unactivate.bind(myWidget), 5000);
}
var testReactivate = function() {
setTimeout(myWidget.activate.bind(myWidget), 7000);
}
//testDeactivate();
// testReactivate();
} /*end_test*/ );
// This is the main definition of your widget. Give it a unique name.
cpdefine("inline:com-zipwhip-widget-svg2gcode", ["chilipeppr_ready", "Snap", "Clipper" ], function() {
return {
/**
* The ID of the widget. You must define this and make it unique.
*/
id: "com-zipwhip-widget-svg2gcode", // Make the id the same as the cpdefine id
name: "Widget / svg2gcode", // The descriptive name of your widget.
desc: "This widget lets you import an SVG file and generate Gcode from it.",
url: "(auto fill by runme.js)", // The final URL of the working widget as a single HTML file with CSS and Javascript inlined. You can let runme.js auto fill this if you are using Cloud9.
fiddleurl: "(auto fill by runme.js)", // The edit URL. This can be auto-filled by runme.js in Cloud9 if you'd like, or just define it on your own to help people know where they can edit/fork your widget
githuburl: "(auto fill by runme.js)", // The backing github repo
testurl: "(auto fill by runme.js)", // The standalone working widget so can view it working by itself
/**
* Define pubsub signals below. These are basically ChiliPeppr's event system.
* ChiliPeppr uses amplify.js's pubsub system so please refer to docs at
* http://amplifyjs.com/api/pubsub/
*/
/**
* Define the publish signals that this widget/element owns or defines so that
* other widgets know how to subscribe to them and what they do.
*/
publish: {
// Define a key:value pair here as strings to document what signals you publish.
//'/onExampleGenerate': 'Example: Publish this signal when we go to generate gcode.'
'didDrop' : "We will publish this if we get an onDropped event and it is for an SVG file. This signal would likely be listened to by the workspace so it can actively show the widget to the user if they drop an SVG file into the workspace. The payload contains the file info like {name: \"myfile.svg\", lastModified: \"1/10/2017 12:12PM\"}",
},
/**
* Define the subscribe signals that this widget/element owns or defines so that
* other widgets know how to subscribe to them and what they do.
*/
subscribe: {
// Define a key:value pair here as strings to document what signals you subscribe to
// so other widgets can publish to this widget to have it do something.
// '/onExampleConsume': 'Example: This widget subscribe to this signal so other widgets can send to us and we'll do something with it.'
},
/**
* Document the foreign publish signals, i.e. signals owned by other widgets
* or elements, that this widget/element publishes to.
*/
foreignPublish: {
// Define a key:value pair here as strings to document what signals you publish to
// that are owned by foreign/other widgets.
// '/jsonSend': 'Example: We send Gcode to the serial port widget to do stuff with the CNC controller.'
"/com-chilipeppr-widget-3dviewer/request3dObject" : "This gives us back the 3d object from the 3d viewer so we can add Three.js objects to it."
},
/**
* Document the foreign subscribe signals, i.e. signals owned by other widgets
* or elements, that this widget/element subscribes to.
*/
foreignSubscribe: {
// Define a key:value pair here as strings to document what signals you subscribe to
// that are owned by foreign/other widgets.
// '/com-chilipeppr-elem-dragdrop/ondropped': 'Example: We subscribe to this signal at a higher priority to intercept the signal. We do not let it propagate by returning false.'
"/com-chilipeppr-widget-3dviewer/recv3dObject" : "By subscribing to this we get the callback when we /request3dObject and thus we can grab the reference to the 3d object from the 3d viewer and do things like addScene() to it with our Three.js objects.",
'/com-chilipeppr-elem-dragdrop/ondropped': 'We subscribe to this signal at a higher priority to intercept the signal, double check if it is an SVG file and if so, we do not let it propagate by returning false. That way the 3D Viewer, Gcode widget, or other widgets will not get the SVG file drag/drop events because they will not know how to interpret the SVG file.'
},
/**
* All widgets should have an init method. It should be run by the
* instantiating code like a workspace or a different widget.
*/
init: function(callback) {
console.log("I am being initted. Thanks.");
this.setupUiFromLocalStorage();
//this.init3d();
// May need to not subscribe during production. Not sure.
this.setupDragDrop();
this.btnSetup();
this.forkSetup();
if (callback) callback();
// store original svg
this.setupExampleSvg();
console.log("I am done being initted.");
},
/**
* Called by the workspace to activate this widget.
*/
activate: function() {
var that = this;
// cprequire(['ThreeProjector'], function() {
// console.log("ThreeProjector loaded");
//setTimeout( that.init3d.bind(that), 500);
that.init3d();
/*
that.init3d(function() {
//if (callback) callback();
console.log("inside activate got init3d done");
if (that.obj3d) {
that.onRender();
//this.obj3dmeta.widget.wakeAnimate();
} else {
console.log("being asked to activate svg2gcode but have no handle to 3d viewer");
}
});
*/
// });
},
/**
* Called by the workspace to deactivate this widget.
*/
unactivate: function() {
this.sceneRemoveMySceneGroup();
this.sceneDisposeMySceneGroup();
// hide floaty menus
this.hideFloatItems();
},
callbackForWorkspaceToShowUs: null,
/**
* The workspace should call this so we can ask it to show us. This is
* needed so if a file is dragged in that is SVG we can say to the workspace
* we'll handle it and that our widget should get shown.
*/
setCallbackForWorkspaceToShowUs: function(callback) {
this.callbackForWorkspaceToShowUs = callback;
},
/**
* This is called by any method in this widget if it wants the parent workspace
* to show us. This would typically be called from onDropped.
*/
askWorkspaceToShowUs: function() {
this.callbackForWorkspaceToShowUs();
},
/**
* Try to get a reference to the 3D viewer.
*/
init3d: function () {
this.get3dObj();
if (this.obj3d == null) {
console.log("loading 3d scene failed, try again in 1 second");
var attempts = 1;
var that = this;
setTimeout(function () {
that.get3dObj();
if (that.obj3d == null) {
attempts++;
setTimeout(function () {
that.get3dObj();
if (that.obj3d == null) {
console.log("giving up on trying to get 3d");
} else {
console.log("succeeded on getting 3d after attempts:", attempts);
that.onInit3dSuccess();
}
}, 5000);
} else {
console.log("succeeded on getting 3d after attempts:", attempts);
that.onInit3dSuccess();
}
}, 1000);
} else {
this.onInit3dSuccess();
}
},
originalSvg: null,
setupExampleSvg: function() {
// grab a copy of the original svg to make as the example file
this.originalSvg = $('#' + this.id + ' .input-svg').val();
var that = this;
$('#' + this.id + ' .load-logo').click(function() {
console.log("got click on load logo");
$('#' + that.id + ' .input-svg').val(that.originalSvg).trigger('change');
})
},
/**
* Call this method from init to setup all the buttons when this widget
* is first loaded. This basically attaches click events to your
* buttons. It also turns on all the bootstrap popovers by scanning
* the entire DOM of the widget.
*/
btnSetup: function() {
// Chevron hide/show body
var that = this;
$('#' + this.id + ' .hidebody').click(function(evt) {
console.log("hide/unhide body");
if ($('#' + that.id + ' .panel-body').hasClass('hidden')) {
// it's hidden, unhide
that.showBody(evt);
}
else {
// hide
that.hideBody(evt);
}
});
// Ask bootstrap to scan all the buttons in the widget to turn
// on popover menus
$('#' + this.id + ' .btn').popover({
delay: 1000,
animation: true,
placement: "auto",
trigger: "hover",
container: 'body'
});
// render
$('#' + this.id + ' .btn-render').click(this.onRender.bind(this));
// on change which re-reads the svg file and creates the Three.js object
$('#' + this.id + ' .input-svg').change(this.onChange.bind(this));
$('#' + this.id + ' .svg2gcode-cuttype').change(this.onChange.bind(this));
// input that just changes gcode, but doesn't have to re-render the svg from scratch
$('#' + this.id + ' .svg2gcode-modetype').change(this.onModeTypeChange.bind(this));
$('#' + this.id + ' .input-svalue').change(this.generateGcode.bind(this));
$('#' + this.id + ' .input-clearance').change(this.generateGcode.bind(this));
$('#' + this.id + ' .input-depthcut').change(this.generateGcode.bind(this));
$('#' + this.id + ' .input-feedrateplunge').change(this.generateGcode.bind(this));
$('#' + this.id + ' .input-feedrate').change(this.generateGcode.bind(this));
$('#' + this.id + ' .input-inflate').change(this.onInflateChange.bind(this));
$('#' + this.id + ' .btn-sendgcodetows').click(this.sendGcodeToWorkspace.bind(this));
// debug arrow
$('#' + this.id + ' .btn-arrow').click(this.drawDebugArrowHelperFor3DToScreenPosition.bind(this));
$('#' + this.id + ' .btn-test').click(this.debugDrawTestObjects.bind(this));
},
debugDrawTestObjects: function() {
this.clear3dViewer();
this.sceneRemoveMySceneGroup();
this.sceneDisposeMySceneGroup();
var width = $( window ).width();
var height = $( window ).height();
$('.test-info').text("Canvas w: " + width + ", h: " + height);
},
isChanging: false,
onChange: function() {
if (this.isChanging) {
console.warn("another change is in process");
return;
} else {
this.isChanging = true;
var that = this;
try {
this.onRender();
} catch(e) {
console.error("Error on rendering. e:", e);
}
that.isChanging = false;
}
},
onModeTypeChange: function() {
this.getSettings();
if (this.options.mode == "laser") {
$('#' + this.id + ' .mode-laser').removeClass("hidden");
$('#' + this.id + ' .mode-mill').addClass("hidden");
} else {
$('#' + this.id + ' .mode-laser').addClass("hidden");
$('#' + this.id + ' .mode-mill').removeClass("hidden");
}
this.generateGcode();
},
onRender: function(callback) {
// make sure we have all the 3d viewer pointers correctly received back
// from 3d viewer. we may not have them based on loading order.
if (this.obj3d && this.obj3dmeta && this.obj3dmeta.widget) {
// we are good to go
} else {
// we do not have them
// init3d will re-enter this method and then should not hit this else statement
this.init3d();
return;
}
this.clear3dViewer();
// get the user settings from the UI
this.getSettings();
var that = this;
// read in the svg text and draw it as three.js object in the 3d viewer
this.drawSvg();
// setTimeout(this.drawSvg.bind(this), 5000);
//that.generateGcode();
//this.extractSvgPathsFromSVGFile(this.options.svg);
// actually render the text
// this.drawText(function() {
// that.generateGcode();
// if (callback) callback();
// });
},
getSettings: function() {
// get text
this.options["svg"] = $('#' + this.id + ' .input-svg').val();
this.options["pointsperpath"] = parseInt($('#' + this.id + ' .input-pointsperpath').val());
this.options["holes"] = $('#' + this.id + ' .input-holes').is(":checked");
this.options["cut"] = $('#' + this.id + ' input[name=com-chilipeppr-widget-svg2gcode-cut]:checked').val();
this.options["dashPercent"] = $('#' + this.id + ' .input-dashPercent').val();
this.options["mode"] = $('#' + this.id + ' input[name=com-chilipeppr-widget-svg2gcode-mode]:checked').val();
this.options["laseron"] = $('#' + this.id + ' input[name=com-chilipeppr-widget-svg2gcode-laseron]:checked').val();
this.options["lasersvalue"] = $('#' + this.id + ' .input-svalue').val();
this.options["millclearanceheight"] = parseFloat($('#' + this.id + ' .input-clearance').val());
this.options["milldepthcut"] = parseFloat($('#' + this.id + ' .input-depthcut').val());
this.options["millfeedrateplunge"] = $('#' + this.id + ' .input-feedrateplunge').val();
this.options["inflate"] = parseFloat($('#' + this.id + ' .input-inflate').val());
this.options["feedrate"] = $('#' + this.id + ' .input-feedrate').val();
//console.log("settings:", this.options);
this.saveOptionsLocalStorage();
},
/**
* Called when user changes inflate value.
*/
onInflateChange: function(evt) {
console.log("onInflateChange. evt:");
this.getSettings();
if (this.inflateGrp) this.svgGroup.remove(this.inflateGrp);
if (this.options.inflate != 0) {
console.log("user wants to inflate. val:", this.options.inflate);
// save the original path and make a new one so we can go back to the original
if (!('svgGroupOriginal' in this)) {
console.log("creating original store");
// no original stored yet
this.svgParentGroupOriginal = this.svgParentGroup;
this.svgGroupOriginal = this.svgGroup;
} else {
console.log("restoring original");
// restore original
this.svgParentGroup = this.svgParentGroupOriginal;
this.svgGroup = this.svgGroupOriginal;
}
var grp = this.svgGroup;
var clipperPaths = [];
var that = this;
grp.traverse( function(child) {
if (child.name == "inflatedGroup") {
console.log("this is the inflated path from a previous run. ignore.");
return;
}
else if (child.type == "Line") {
// let's inflate the path for this line. it may not be closed
// so we need to check that.
//var threeObj = that.inflateThreeJsLineShape(child, that.options.inflate);
var clipperPath = that.threeJsVectorArrayToClipperArray(child.geometry.vertices);
clipperPaths.push(clipperPath);
// hide for now. we can unhide later if we reset.
//child.visible = false;
child.material.color = 0x000000;
child.material.transparent = true;
child.material.opacity = 0.2;
// for now add to existing object
// eventually replace it
//grp.add(threeObj);
}
else if (child.type == "Points") {
child.visible = false;
}
else {
console.log("type of ", child.type, " being skipped");
}
});
console.log("clipperPaths:", clipperPaths);
// simplify this set of paths which is a very powerful Clipper call that
// figures out holes and path orientations
var newClipperPaths = this.simplifyPolygons(clipperPaths);
// get the inflated/deflated path
var inflatedPaths = this.getInflatePath(newClipperPaths, this.options.inflate);
// we now have a huge array of clipper paths
console.log("newClipperPaths:", newClipperPaths);
this.inflateGrp = this.drawClipperPaths(inflatedPaths, 0x0000ff, 0.99, 0.01, 0, true, false, "inflatedGroup");
//threeObj.name = "inflatedGroup";
//this.svgParentGroup.remove(this.svgGroup);
//this.svgParentGroup.add(threeObj);
this.svgGroup.add(this.inflateGrp);
//grp.add(threeObj);
this.wakeAnimate();
}
},
simplifyPolygons: function(paths) {
var scale = 10000;
ClipperLib.JS.ScaleUpPaths(paths, scale);
var newClipperPaths = ClipperLib.Clipper.SimplifyPolygons(paths, ClipperLib.PolyFillType.pftEvenOdd);
// scale back down
ClipperLib.JS.ScaleDownPaths(newClipperPaths, scale);
ClipperLib.JS.ScaleDownPaths(paths, scale);
return newClipperPaths;
},
drawClipperPaths: function (paths, color, opacity, z, zstep, isClosed, isAddDirHelper, name) {
console.log("drawClipperPaths");
var lineUnionMat = new THREE.LineBasicMaterial({
color: color,
transparent: true,
opacity: opacity
});
if (z === undefined || z == null)
z = 0;
if (zstep === undefined || zstep == null)
zstep = 0;
if (isClosed === undefined || isClosed == null)
isClosed = true;
var group = new THREE.Object3D();
if (name) group.name = name;
for (var i = 0; i < paths.length; i++) {
var lineUnionGeo = new THREE.Geometry();
for (var j = 0; j < paths[i].length; j++) {
var actualZ = z;
if (zstep != 0) actualZ += zstep * j;
lineUnionGeo.vertices.push(new THREE.Vector3(paths[i][j].X, paths[i][j].Y, actualZ));
// does user want arrow helper to show direction
if (isAddDirHelper) {
/*
var pt = { X: paths[i][j].X, Y: paths[i][j].Y, Z: actualZ };
var ptNext;
if (j + 1 >= paths[i].length)
ptNext = {X: paths[i][0].X, Y: paths[i][0].Y, Z: actualZ };
else
ptNext = {X: paths[i][j+1].X, Y: paths[i][j+1].Y, Z: actualZ };
// x2-x1,y2-y1
var dir = new THREE.Vector3( ptNext.X - pt.X, ptNext.Y - pt.Y, ptNext.Z - pt.Z );
var origin = new THREE.Vector3( pt.X, pt.Y, pt.Z );
var length = 0.1;
var hex = 0xff0000;
var arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
group.add( arrowHelper );
*/
}
}
// close it by connecting last point to 1st point
if (isClosed) lineUnionGeo.vertices.push(new THREE.Vector3(paths[i][0].X, paths[i][0].Y, z));
var lineUnion = new THREE.Line(lineUnionGeo, lineUnionMat);
if (name) lineUnion.name = name;
//lineUnion.position.set(0,-20,0);
group.add(lineUnion);
}
//this.sceneAdd(group);
return group;
},
/**
* Pass in a THREE.Line that is closed, meaning it was from a real shape and the end point
* equals the start point because Clipper requires that. Make sure the
* holes have a userData value of threeLine.userData.isHole = true so we know to deflate those
* instead of inflate. To inflate by 3mm
* have delta = 3. You can also set delta to a negative number to deflate.
* We will return a new THREE.Line object or if multiple paths end up getting created
* we will return a new THREE.Group() containing THREE.Line objects.
*/
inflateThreeJsLineShape: function(threeLine, delta) {
// debugger;
console.log("inflateThreeJsLineShape. threeLine:", threeLine, "delta:", delta);
// convert Vector3 array to Clipper array
var clipperPath = this.threeJsVectorArrayToClipperArray(threeLine.geometry.vertices);
// double check there are points in array
if (clipperPath.length == 0) {
console.error("You did not pass in a THREE.Line that had any vertices. Huh?");
}
// double check that end point equals start point
if (clipperPath[0].X != clipperPath[clipperPath.length-1].X &&
clipperPath[0].Y != clipperPath[clipperPath.length-1].Y) {
console.error("Your start and end points do not match, so this is not a closed path therefore you cannot inflate it. Please close the path first.");
}
// check winding order
var orientation = ClipperLib.Clipper.Orientation(clipperPath);
console.log("orientation:", orientation);
// check if hole
var isHole = false;
if (threeLine.userData.isHole) {
isHole = true;
delta = -1 * delta;
} else {
// it's not a hole
if (orientation == true) {
// the winding order is correct
} else {
// reverse it for correct winding order
clipperPath.reverse();
}
}
var orientation = ClipperLib.Clipper.Orientation(clipperPath);
console.log("orientation:", orientation);
// get inflate path. we will get back possibly multiple paths because an inflate
// or deflate can create dangling holes, etc.
var inflatedPaths = this.getInflatePath([clipperPath], delta);
var retObj;
if (inflatedPaths.length == 1) {
// we only got one path back. cool.
var newThreeLine = threeLine.clone();
newThreeLine.geometry.vertices = this.clipperArrayToThreeJsVectorArray(inflatedPaths[0]);
newThreeLine.geometry.verticesNeedUpdate = true;
retObj = newThreeLine;
} else {
var newGroup = new THREE.Group();
// loop thru returned paths
for (var i in inflatedPaths) {
var inflatedPath = inflatedPaths[i];
// convert back to THREE.Line
var newThreeLine = threeLine.clone();
newThreeLine.geometry.vertices = this.clipperArrayToThreeJsVectorArray(inflatedPath);
newGroup.add(newThreeLine);
}
retObj = newGroup;
}
return retObj;
},
/**
* Pass in something like geometry.vertices which is an array of Vector3's and
* this method will pass back an array with Clipper formatting of [{X:nnn, Y:nnn}].
*/
threeJsVectorArrayToClipperArray: function(threeJsVectorArray) {
var clipperArr = [];
for (i = 0; i < threeJsVectorArray.length; i++) {
var pt = threeJsVectorArray[i];
clipperArr.push({X: pt.x, Y: pt.y});
}
return clipperArr;
},
/**
* Pass in an array with Clipper formatting of [{X:nnn, Y:nnn}]. We will pass back
* an array of Vector3's so you can set it to your geometry.vertices.
*/
clipperArrayToThreeJsVectorArray: function(clipperArr) {
var threeJsVectorArray = [];
for (var i in clipperArr) {
var pt = clipperArr[i];
threeJsVectorArray.push(new THREE.Vector3(pt.X, pt.Y, 0));
}
return threeJsVectorArray;
},
/**
* Pass in an array of an array of paths or holes. For example, pass in
* paths = [[{X:0, Y:0}, {X:10:Y0}, {X:10, Y:10}, {X:0, Y:0}]. Your path must
* be closed so the end point must equal the start point. To inflate by 3mm
* have delta = 3. You can also set delta to a negative number to deflate. Make
* sure the winding order is correct as well.
*/
getInflatePath: function (paths, delta, joinType) {
var scale = 10000;
ClipperLib.JS.ScaleUpPaths(paths, scale);
var miterLimit = 2;
var arcTolerance = 10;
joinType = joinType ? joinType : ClipperLib.JoinType.jtRound
var co = new ClipperLib.ClipperOffset(miterLimit, arcTolerance);
co.AddPaths(paths, joinType, ClipperLib.EndType.etClosedPolygon);
//var delta = 0.0625; // 1/16 inch endmill
var offsetted_paths = new ClipperLib.Paths();
co.Execute(offsetted_paths, delta * scale);
// scale back down
ClipperLib.JS.ScaleDownPaths(offsetted_paths, scale);
ClipperLib.JS.ScaleDownPaths(paths, scale);
return offsetted_paths;
},
generateGcodeTimeoutPtr: null,
isGcodeInRegeneratingState: false,
/**
* This method will trigger a process to generateGcode however, it
* allows this to be called a bunch of times and it will always wait
* to do the generate about 1 second later and de-dupe the multiple calls.
*/
generateGcode: function() {
// this may be an odd place to trigger gcode change, but this method
// is called on all scaling changes, so do it here for now
if (this.generateGcodeTimeoutPtr) {
//console.log("clearing last setTimeout for generating gcode cuz don't need anymore");
clearTimeout(this.generateGcodeTimeoutPtr);
}
if (!this.isGcodeInRegeneratingState) {
$('#' + this.id + " .gcode").prop('disabled', true);
$('#' + this.id + " .btn-sendgcodetows").prop('disabled', true);
$('#' + this.id + " .regenerate").removeClass('hidden');
$('#' + this.id + " .gcode-size-span").addClass('hidden');
// set this to true so next time we are called fast we know we don't have
// to set the UI elements again. they'll get set back and this flag after
// the gcode is generated
this.isGcodeInRegeneratingState = true;
} else {
// do nothing
//console.log("already indicated in UI we have to regenerate");
}
this.generateGcodeTimeoutPtr = setTimeout(this.generateGcodeCallback.bind(this), 1000);
},
/**
* Iterate over the text3d that was generated and create
* Gcode to mill/cut the three.js object.
*/
generateGcodeCallback: function() {
// get settings
this.getSettings();
var g = "(Gcode generated by ChiliPeppr Svg2Gcode Widget)\n";
//g += "(Text: " + this.mySceneGroup.userData.text + ")\n";
g += "G21 (mm)\n";
// get the THREE.Group() that is the txt3d
var grp = this.svgGroup;
var txtGrp = this.svgGroup;
var that = this;
var isLaserOn = false;
var isAtClearanceHeight = false;
var isFeedrateSpecifiedAlready = false;
txtGrp.traverse( function(child) {
if (child.type == "Line") {
// let's create gcode for all points in line
for (i = 0; i < child.geometry.vertices.length; i++) {
var localPt = child.geometry.vertices[i];
var worldPt = grp.localToWorld(localPt.clone());
if (i == 0) {
// first point in line where we start lasering/milling
// move to point
// if milling, we need to move to clearance height
if (that.options.mode == "mill") {
if (!isAtClearanceHeight) {
g += "G0 Z" + that.options.millclearanceheight + "\n";
}
}
// move to start point
g += "G0 X" + worldPt.x.toFixed(3) +
" Y" + worldPt.y.toFixed(3) + "\n";
// if milling move back to depth cut
if (that.options.mode == "mill") {
var halfDistance = (that.options.millclearanceheight - that.options.milldepthcut) / 2;
g += "G0 Z" + (that.options.millclearanceheight - halfDistance).toFixed(3)
+ "\n";
g += "G1 F" + that.options.millfeedrateplunge +
" Z" + that.options.milldepthcut + "\n";
isAtClearanceHeight = false;
}
}
else {
// we are in a non-first line so this is normal moving
// see if laser or milling
if (that.options.mode == "laser") {
// if the laser is not on, we need to turn it on
if (!isLaserOn) {
if (that.options.laseron == "M3") {
g += "M3 S" + that.options.lasersvalue;
} else {
g += that.options.laseron;
}
g += " (laser on)\n";
isLaserOn = true;
}
} else {
// this is milling. if we are not at depth cut
// we need to get there
}
// do normal feedrate move
var feedrate;
if (isFeedrateSpecifiedAlready) {
feedrate = "";
} else {
feedrate = " F" + that.options.feedrate;
isFeedrateSpecifiedAlready = true;
}
g += "G1" + feedrate +
" X" + worldPt.x.toFixed(3) +
" Y" + worldPt.y.toFixed(3) + "\n";
}
}
// make feedrate have to get specified again on next line
// if there is one
isFeedrateSpecifiedAlready = false;
// see if laser or milling
if (that.options.mode == "laser") {
// turn off laser at end of line
isLaserOn = false;
if (that.options.laseron == "M3")
g += "M5 (laser off)\n";
else
g += "M9 (laser off)\n";
} else {
// milling. move back to clearance height
g += "G0 Z" + that.options.millclearanceheight + "\n";
isAtClearanceHeight = true;
}
}
});
console.log("generated gcode. length:", g.length);
//console.log("gcode:", g);
$('#' + this.id + " .gcode").val(g).prop('disabled', false);
$('#' + this.id + " .btn-sendgcodetows").prop('disabled', false);
$('#' + this.id + " .regenerate").addClass('hidden');
$('#' + this.id + " .gcode-size-span").removeClass('hidden');
$('#' + this.id + " .gcode-size").text(parseInt(g.length / 1024) + "KB");
this.isGcodeInRegeneratingState = false;
},
/**
* Contains the SVG rendered Three.js group with everything in it including
* the textbox handles and the marquee. So this is not the Three.js object
* that only contains the SVG that was rendered. Use svgGroup for that which
* is a child.
*/
svgParentGroup: null,
/**
* Contains the actual rendered SVG file. This is where the action is.
*/
svgGroup: null,
/**
* Contains the original path from SVG file. This is like layer 1 of the rendering.
*/
svgPath: null,
/**
* Contains the inflated/deflated path. This is like layer 2 of the rendering. If no
* inflate/deflate was asked for by user, this path is still generated but at 0 inflate.
*/
svgInflatePath: null,
/**
* Contains the dashed/solid path which is generated from svgInflatePath. This is like
* layer 3 of the rendering. Solid is the default, so if no inflate or dash then this path
* is like a copy of the original svgPath.
*/
svgSolidDashPath: null,
/**
* Contains the toolpath path if user is doing milling and wants to move the path to a
* different Z layer. This is like layer 4 of the rendering.
*/
svgToolPath: null,
/**
* Contains the particle we map the width textbox 3d to 2d screen projection.
*/
widthParticle: null,
/**
* Contains the particle we map the height textbox 3d to 2d screen projection.
*/
heightParticle: null,
/**
* Contains the particle we map the lower/left corner of marquee.
*/
alignBoxParticle: null,
drawSvg: function() {
// see if file is valid
if (this.options.svg.length == 0) return;
var error = this.extractSvgPathsFromSVGFile(this.options.svg);
if (error) {
// do nothing
console.warn("there was an error with svg file");
} else {
this.mySceneGroup = this.svgParentGroup;
this.sceneReAddMySceneGroup();
// get the new 3d viewer object centered on camera
chilipeppr.publish('/com-chilipeppr-widget-3dviewer/viewextents' );
// make sure camera change triggers
//setTimeout(this.onCameraChange.bind(this), 50);
this.onCameraChange(); //.bind(this);
this.generateGcode();
}
},
extractSvgPathsFromSVGFile: function(file) {
var fragment = Snap.parse(file);
console.log("fragment:", fragment);
// make sure we get 1 group. if not there's an error
var g = fragment.select("g");
console.log("g:", g);
if (g == null) {
// before we give up if there's not one group, check
// if there are just paths inlined
var pathSet = fragment.selectAll("path");
if (pathSet == null) {
$('#' + this.id + " .error-parse").removeClass("hidden");
return true;
} else {
console.log("no groups, but we have some paths so proceed to code below.");
}
}
$('#' + this.id + " .error-parse").addClass("hidden");
var groups = fragment.selectAll("g");
console.log("groups:", groups);
if (groups.length > 1) {
console.warn("too many groups in svg. need a flattened svg file.");
$('#' + this.id + " .error-flattened").removeClass("hidden");
return true;
}