-
Notifications
You must be signed in to change notification settings - Fork 41
/
auto-generated-widget.html
4513 lines (3995 loc) · 205 KB
/
auto-generated-widget.html
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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Widget / 3D GCode Viewer</title>
<!-- ChiliPeppr is based on bootstrap CSS. -->
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!-- Customized version of require.js for ChiliPeppr. Please see require.js docs for how
ChiliPeppr's dependency system works as it's based on require.js. -->
<script type='text/javascript' src="//i2dcui.appspot.com/js/require.js"></script>
<style type='text/css'>
/* CSS for ChiliPeppr Widget */
#com-chilipeppr-widget-3dviewer .panel-heading {
z-index:1;
position:relative;
}
.com-chilipeppr-widget-3dviewer-simulator-title {
border-radius: 3px;
border-bottom-right-radius: 0;
border-top-right-radius: 0;
float:left;
position: relative;
border: 1px solid #ccc;
display: inline-block;
border-right-width: 0;
}
#com-chilipeppr-widget-3dviewer-body {
/* height: 350px; */
padding:0;
margin:0;
position: relative;
border:0px solid red;
background-color: blue;
}
#com-chilipeppr-widget-3dviewer-renderArea {
position: fixed;
left: 0;
right: 0;
bottom: 0;
top: 0;
background-color: #000000;
/* z-index:0; */
}
#com-chilipeppr-widget-3dviewer .disabled .glyphicon {
color: #dddddd;
}
#com-chilipeppr-widget-3dviewer #warningArea {
position: absolute;
top:0;
left:0;
padding: 10px;
font-size: 9px;
color: white;
}
#com-chilipeppr-widget-3dviewer-infoArea {
position: absolute;
bottom:0;
left:0;
padding: 10px;
font-size: 9px;
color: #333333;
/* background-color: black; */
}
#com-chilipeppr-widget-3dviewer-infoArea .info {
position: absolute;
bottom:0;
left:0;
color: blue;
background-color:red;
}
#com-chilipeppr-widget-3dviewer-renderArea .data-details {
position: absolute;
bottom:0;
left:10;
/* background-color: transparent; */
color: #333333;
padding: 10px;
font-size: 9px;
}
.com-chilipeppr-widget-3dviewer-inspect {
padding-bottom:0;
margin-bottom:0;
font-size:10px;
position:absolute;
min-width:250px;
max-width:100%;
/* width:100%; */
z-index: 9;
box-shadow: 0 0 20px #888888;
}
.com-chilipeppr-widget-3dviewer-panzoom-indicator {
font-size:10px;
padding-top: 7px;
}
</style>
<script type='text/javascript'>
//<![CDATA[
/* global requirejs cprequire cpdefine chilipeppr THREE */
// Defining the globals above helps Cloud9 not show warnings for those variables
// ChiliPeppr Widget/Element Javascript
requirejs.config({
paths: {
//Three: '//i2dcui.appspot.com/geturl?url=http://threejs.org/build/three.min.js',
// Keep in mind that the /slingshot url does the same as /geturl but it is not cached
// Three: '//i2dcui.appspot.com/slingshot?url=http://threejs.org/build/three.min.js',
// Three: '//i2dcui.appspot.com/geturl?url=http://threejs.org/build/three.js',
Three: 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r76/three',
ThreeTextGeometry: '//i2dcui.appspot.com/js/three/TextGeometry',
ThreeFontUtils: '//i2dcui.appspot.com/js/three/FontUtils',
//ThreeDetector: '//i2dcui.appspot.com/geturl?url=http://threejs.org/examples/js/Detector.js',
ThreeDetector: '//i2dcui.appspot.com/geturl?url=https://raw.githubusercontent.com/mrdoob/three.js/r80/examples/js/Detector.js',
//ThreeTrackballControls: '//i2dcui.appspot.com/geturl?url=http://threejs.org/examples/js/controls/TrackballControls.js',
// Latest release
// ThreeTrackballControls: '//i2dcui.appspot.com/slingshot?url=http://threejs.org/examples/js/controls/TrackballControls.js',
// r79 (to solve that mousewheel zoom started not working in r80, so had to force to older version. eventually they'll fix the bug cuz i filed it)
// ThreeTrackballControls: '//i2dcui.appspot.com/slingshot?url=http://rawgit.com/mrdoob/three.js/r79/examples/js/controls/TrackballControls.js',
ThreeTrackballControls: '//i2dcui.appspot.com/geturl?url=http://rawgit.com/mrdoob/three.js/r79/examples/js/controls/TrackballControls.js',
ThreeOrbitControls: '//threejs.org/examples/js/controls/OrbitControls',
ThreeHelvetiker: '//i2dcui.appspot.com/js/three/threehelvetiker',
ThreeTypeface: 'https://superi.googlecode.com/svn-history/r1953/trunk/MBrand/MBrand/Scripts/typeface-0.15',
ThreeTween: '//i2dcui.appspot.com/js/three/tween.min',
ThreeBufferGeometryUtils: '//i2dcui.appspot.com/js/three/BufferGeometryUtils',
ThreeCanvasRenderer: '//i2dcui.appspot.com/geturl?url=http://threejs.org/examples/js/renderers/CanvasRenderer.js',
ThreeProjector: '//i2dcui.appspot.com/geturl?url=http://threejs.org/examples/js/renderers/Projector.js',
},
shim: {
ThreeTextGeometry: ['Three'],
ThreeFontUtils: ['Three', 'ThreeTextGeometry'],
ThreeHelvetiker: ['Three', 'ThreeTextGeometry', 'ThreeFontUtils'],
//ThreeHelvetiker: ['Three', 'ThreeTextGeometry'],
ThreeTrackballControls: ['Three'],
ThreeTween: ['Three'],
ThreeSparks: ['Three'],
ThreeParticle: ['Three'],
ThreeBufferGeometryUtils: ['Three'],
ThreeCanvasRenderer: ['Three', 'ThreeProjector'],
ThreeProjector: ['Three']
}
});
cprequire_test(['inline:com-chilipeppr-widget-3dviewer'], function (threed) {
// 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.
console.log("Running 3dviewer");
// set my title while in test mode so it's pretty
$('title').html(threed.name);
// actually finally init me
threed.init({doMyOwnDragDrop: true});
// test resize signal
setTimeout(function() {
chilipeppr.publish('/' + threed.id + '/resize', "" );
}, 3000);
//dragdrop
$('body').prepend('<div id="test-drag-drop"></div>');
chilipeppr.load("#test-drag-drop",
// "http://fiddle.jshell.net/chilipeppr/Z9F6G/show/light/",
"http://raw.githubusercontent.com/chilipeppr/elem-dragdrop/master/auto-generated-widget.html",
function () {
cprequire(
["inline:com-chilipeppr-elem-dragdrop"],
function (dd) {
dd.init();
dd.bind("body", null);
});
});
// flashmsg
$('body').prepend('<div id="com-chilipeppr-flash"></div>');
chilipeppr.load("#com-chilipeppr-flash",
"http://raw.githubusercontent.com/chilipeppr/element-flash/master/auto-generated-widget.html",
// "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();
});
});
var testGotoline = function() {
// send sample gcodeline commands as if the gcode sender widget were sending them
setTimeout(function() {
chilipeppr.publish('/com-chilipeppr-widget-3dviewer/gotoline', {line: 3, gcode: "G21 G90 G64 G40"} );
}, 3000);
setTimeout(function() {
chilipeppr.publish('/com-chilipeppr-widget-3dviewer/gotoline', {line: 4, gcode: "G0 Z3.0"} );
}, 6000);
setTimeout(function() {
chilipeppr.publish('/com-chilipeppr-widget-3dviewer/gotoline', {line: 10, gcode: "G0 X130.8865 Y-11.5919"} );
}, 9000);
setTimeout(function() {
chilipeppr.publish('/com-chilipeppr-widget-3dviewer/gotoline', {line: 11, gcode: "G0 Z1.5"} );
}, 12000);
setTimeout(function() {
chilipeppr.publish('/com-chilipeppr-widget-3dviewer/gotoline', {line: 22, gcode: "G1 F300.0 Z0.0"} );
}, 12800);
}
var testGotoXyz = function() {
// send sample gcodeline commands as if the gcode sender widget were sending them
setTimeout(function() {
chilipeppr.publish('/com-chilipeppr-interface-cnccontroller/axes', {x:0.0, y:0.0, z:10.0} );
}, 3000);
setTimeout(function() {
chilipeppr.publish('/com-chilipeppr-interface-cnccontroller/axes', {z:-2.0} );
}, 4000);
setTimeout(function() {
chilipeppr.publish('/com-chilipeppr-interface-cnccontroller/axes', {x:0.0, z:6.0} );
}, 55000);
}
var testClear = function() {
setTimeout(function() {
chilipeppr.publish('/com-chilipeppr-widget-3dviewer/sceneclear' );
}, 5000);
}
//testClear();
var testViewExtents = function() {
setTimeout(function() {
chilipeppr.publish('/com-chilipeppr-widget-3dviewer/viewextents' );
}, 5000);
}
//testViewExtents();
//testGotoXyz();
//threed.init();
console.log("3d viewer initted");
} /*end_test*/ );
cpdefine('inline:com-chilipeppr-widget-3dviewer', ['chilipeppr_ready', 'Three', 'ThreeDetector', 'ThreeTrackballControls', 'ThreeTween', 'ThreeHelvetiker', 'ThreeBufferGeometryUtils'], function () {
return {
id: 'com-chilipeppr-widget-3dviewer',
name: "Widget / 3D GCode Viewer",
desc: "Visualize your GCode in 3D by simulating your GCode run or seeing where your run is at in 3D while your CNC operation is in action.",
url: "http://raw.githubusercontent.com/chilipeppr/widget-3dviewer/master/auto-generated-widget.html", // 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: "http://ide.c9.io/chilipeppr/widget-3dviewer", // 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: "http://github.com/chilipeppr/widget-3dviewer", // The backing github repo
testurl: "http://widget-3dviewer-chilipeppr.c9users.io/widget.html", // The standalone working widget so can view it working by itself
publish: {
'/recv3dObject' : "When you send a /request3dObject you will receive a signal back of /recv3dObject. This signal has a payload of the THREE.js user object being shown in the 3D viewer.",
'/recvUnits' : 'When you send a /requestUnits you will receive back this signal with a payload of "mm" or "inch" as a string. Please also see /unitsChanged in case you want to know whenever units are changed from a file open event. You can request what units the Gcode are in from the 3D Viewer. Since the 3D Viewer parses Gcode, it can determine the units. The 3D Viewer is mostly unit agnostic, however to draw the toolhead, grid, and extents labels it does need to know the units to draw the decorations in a somewhat appropriate size.',
'/unitsChanged' : 'This signal is published when the user loads a new file into the 3D viewer and the units change. If other widgets need to know what units are being used, you should subscribe to this signal to be notified on demand.',
'/sceneReloaded' : "This signal is sent when the scene has been (re)load because the user dragged / dropped. The payload indicates the global bounding box of the scene. This signal is similar to listening to /com-chilipeppr-elem-dragdrop/ondropped however, /sceneReloaded is guaranteed to fire every time the 3D viewer loads a new file into the viewer. Credit for this signal goes to Dat Chu who created it for his GrblLaser workspace."
},
subscribe: {
'/gotoline': "This widget subscribes to this channel so other widgets can move the toolhead and highlight the Gcode line being worked on. This would mostly be when sending Gcode from a Gcode viewer/sender widget, that widget can have the 3D view follow along. Just the line number should be sent as the 3D viewer has it's own cache of the Gcode data loaded.",
'/resize' : "You can ask this widget to resize itself. It will resize the rendering area to the region it is bound to (typically the window width/height).",
'/sceneadd' : "You can send Threejs objects to this widget and they will be added to the scene. You must send true THREE.Line() or other ThreeJS objects in that are added as scene.add() objects.",
'/sceneremove' : "You can also remove objects from the 3D scene. This is the opposite of /sceneadd",
'/sceneclear' : "This resets the 3D viewer and clears the scene. It keeps the axes, toolhead, and grid. The user object and extents is removed.",
'/drawextents' : "This asks the 3D viewer to draw the extents of what it is showing.",
'/viewextents' : "This asks the 3D viewer to place the entire 3D object set in the view window from a front facing position. It is the equivalent of the button with the \"eye\" icon in the toolbar.",
'/setunits' : "Pass in a string of \"mm\" or \"inch\" to set the units for the 3D Viewer.",
'/wakeanimate' : "The 3d viewer sleeps the rendering after 5 seconds. So if you are going to do any updates to the 3D scene you should wake the animation before your update. It will timeout on its own so you don't have to worry about it. /sceneadd and /sceneremove do their own waking so you don't need to ask for it on those.",
'/request3dObject' : "You can request the parent-most object that is showing in the 3D viewer. This is a THREE.js object that is generated by the 3D viewer. It contains all user elements shown in the scene. It does not contain the XYZ axis, toolhead, or other system elements. When you send this signal you will receive a publish back on /recv3dObject",
'/requestUnits' : 'Send in this signal and you will be sent back a /recvUnits with a payload of "mm" or "inch" as a string. Please also see /unitsChanged in case you want to know whenever units are changed from a file open event. You can request what units the Gcode are in from the 3D Viewer. Since the 3D Viewer parses Gcode, it can determine the units. The 3D Viewer is mostly unit agnostic, however to draw the toolhead, grid, and extents labels it does need to know the units to draw the decorations in a somewhat appropriate size.'
},
foreignSubscribe: {
"/com-chilipeppr-interface-cnccontroller/axes" : "If we see this signal come in, we move the toolhead to the xyz position in the payload of the signal.",
"/com-chilipeppr-elem-dragdrop/ondropped" : "When a user drags and drops a file to the main window, we want to get notified so we can load it into the 3D viewer. During development mode in JSFiddle, this widget loads it's own com-chilipeppr-elem-dragdrop so you can test development, but when this widget is loaded in a full ChiliPeppr app it uses the global com-chilipeppr-elem-dragdrop."
},
foreignPublish: {
},
scene: null,
object: null,
camera: null,
controls: null,
toolhead: null,
tween: null,
tweenHighlight: null,
tweenIndex: null,
tweenSpeed: 1,
tweenPaused: false,
tweenIsPlaying: false,
wantAnimate: true, // we automatically timeout rendering to save on cpu
initOptions: {},
init: function (initOptions) {
this.initOptions = initOptions;
var that = this;
/*
if (!Modernizr.webgl) {
alert('Sorry, you need a WebGL capable browser to use this.\n\nGet the latest Chrome or FireFox.');
return;
}
if (!Modernizr.localstorage) {
alert("Man, your browser is ancient. I can't work with this. Please upgrade.");
return;
}
*/
// Show 'About' dialog for first time visits.
/*
if (!localStorage.getItem("not-first-visit")) {
localStorage.setItem("not-first-visit", true);
setTimeout(about, 500);
}
*/
// Drop files from desktop onto main page to import them.
// We also can subscribe to the main chilipeppr drag/drop
// pubsub to get drop events from a parent, rather than doing
// this on our own
// subscribe to file load events
chilipeppr.subscribe("/com-chilipeppr-elem-dragdrop/ondropped", this, this.onPubSubFileLoaded);
if (this.initOptions && this.initOptions.doMyOwnDragDrop) {
console.log("Doing my own drag drop for 3D viewer cuz asked to. Attaching to body tag in DOM.");
$('body').on('dragover', function (event) {
event.stopPropagation();
event.preventDefault();
event.originalEvent.dataTransfer.dropEffect = 'copy'
}).on('drop', function (event) {
console.log("got drop:", event);
event.stopPropagation();
event.preventDefault();
var files = event.originalEvent.dataTransfer.files;
if (files.length > 0) {
var reader = new FileReader();
reader.onload = function () {
console.log("opening file. reader:", reader);
console.log ("stringify", JSON.stringify(reader.result, null, 2) );
that.openGCodeFromText(reader.result);
};
reader.readAsText(files[0]);
// reader.readAsArrayBuffer(files[0]);
}
});
}
that.scene = that.createScene($('#com-chilipeppr-widget-3dviewer-renderArea'));
var lastImported = localStorage.getItem('last-imported');
var lastLoaded = localStorage.getItem('last-loaded');
if (lastImported) {
that.openGCodeFromText(lastImported);
} else {
//console.log("would have opened octocat");
//that.openGCodeFromPath(lastLoaded || 'examples/octocat.gcode');
console.log("loading chilipeppr logo");
that.openGCodeFromPath(lastLoaded || 'http://www.chilipeppr.com/3d/chilipepprlogo.nc');
}
var lastFpsRate = localStorage.getItem ('fpsRate');
if (lastFpsRate) {
console.log("got prior FPS Rate, setting it now: ", lastFpsRate, "//rk");
//this.setFrameRate(parseInt(lastFpsRate) );
var fr = parseInt(lastFpsRate);
this.setFrameRate(fr);
// set css to show selected
$('.com-chilipeppr-widget-3dviewer-settings-fr').removeClass('alert-info');
$('.com-chilipeppr-widget-3dviewer-settings-fr-' + fr).addClass('alert-info');
}
// setup toolbar buttons
this.btnSetup();
this.forkSetup();
//this.setDetails("blah");
// subscribe to gotoline signal so we can move toolhead to correct location
// to sync with the gcode sender
chilipeppr.subscribe('/' + this.id + '/gotoline', this, this.gotoLine);
// subscribe to gotoline signal so we can move toolhead to correct location
// to sync with the actual milling machine
chilipeppr.subscribe('/com-chilipeppr-interface-cnccontroller/axes', this, this.gotoXyz);
// we can be asked to resize ourself by a publish call to this signal
chilipeppr.subscribe('/' + this.id + '/resize', this, this.resize);
// requestUnits, recvUnits
chilipeppr.subscribe("/" + this.id + "/requestUnits", this, this.requestUnits);
// setup more pubsub to allow other widgets to inject objects to our scene
this.setupScenePubSub();
this.setupGridSizeMenu();
this.setupCogMenu();
this.setupFpsMenu();
this.initJog(); //this.setupJog();
this.initInspect();
// hide the pan/zoom/orbit msg after 1 minute
setTimeout(function() {
console.log("hiding pan/zoom/orbit msg");
$('.com-chilipeppr-widget-3dviewer-panzoom-indicator').fadeOut("slow"); //addClass("hidden");
}, 60 * 1000);
},
setupScenePubSub: function() {
// these pubsubs let others add objects to our 3d scene
chilipeppr.subscribe("/" + this.id + "/wakeanimate", this, this.wakeAnimate);
chilipeppr.subscribe("/" + this.id + "/sceneadd", this, this.sceneAdd);
chilipeppr.subscribe("/" + this.id + "/sceneremove", this, this.sceneRemove);
chilipeppr.subscribe("/" + this.id + "/sceneclear", this, this.sceneClear);
chilipeppr.subscribe("/" + this.id + "/drawextents", this, this.drawAxesToolAndExtents);
chilipeppr.subscribe("/" + this.id + "/viewextents", this, this.viewExtents);
chilipeppr.subscribe("/" + this.id + "/setunits", this, this.setUnits);
chilipeppr.subscribe("/" + this.id + "/request3dObject", this, this.request3dObject);
},
onSignalSceneReloadedFailAttempts: 0, // track failed nulls
onSignalSceneReloaded: function () {
// this can get called before there is userData, so check for that
// and if so, wait to publish until there is
if (this.object && this.object.userData && this.object.userData.bbbox2) {
console.log("publishing /sceneReloaded. It took us X attempts:", this.onSignalSceneReloadedFailAttempts);
chilipeppr.publish("/" + this.id + "/sceneReloaded", this.object.userData.bbbox2);
this.onSignalSceneReloadedFailAttempts = 0;
} else {
// call ourselves again in 2 seconds
if (this.onSignalSceneReloadedFailAttempts >= 5) {
// give up
console.log("tried 5 times onSignalSceneReloadedFailAttempts. giving up.");
this.onSignalSceneReloadedFailAttempts = 0;
} else {
this.onSignalSceneReloadedFailAttempts++;
setTimeout(this.onSignalSceneReloaded.bind(this), 2000);
}
}
},
// INSPECT CODE REGION
isInspectSelect: false,
initInspect: function() {
// attach click event
console.log("doing one time run of initial inspect setup. this should not run more than once!!!");
$('.com-chilipeppr-widget-3d-menu-inspect').click(this.toggleInspect.bind(this));
// attach shortcut key
var el = $('#com-chilipeppr-widget-3dviewer-renderArea');
el.focus();
$(document).keydown(this.inspectKeyDown.bind(this));
$(document).keyup(this.inspectKeyUp.bind(this));
this.inspectLastDecorateGroup = new THREE.Group();
this.sceneAdd(this.inspectLastDecorateGroup);
// get dialog element
this.inspectDlgEl = $('.com-chilipeppr-widget-3dviewer-inspect');
// setup click event
this.inspectDlgEl.find('.inspect-btn-goto').click(this.onInspectGoto.bind(this));
this.inspectDlgEl.find('.close').click(function() {
$('.com-chilipeppr-widget-3dviewer-inspect').addClass("hidden");
});
// create three.js group to hold all preview lines
this.inspectPreviewGroup = new THREE.Group();
},
setupInspect: function(evt) {
console.log("setupInspect.");
if (this.isInspectSelect) {
console.log("we are already in inspect mode. being asked to setup, but returning cuz u can't setup more than once.");
return;
}
// start watching mouse
var el = $(this.renderer.domElement);
el.mousemove(this.inspectMouseMove.bind(this));
el.click(this.inspectMouseClick.bind(this));
$('.com-chilipeppr-widget-3d-menu-inspect').addClass("active");
$('.com-chilipeppr-widget-3d-menu-inspect').addClass("btn-primary");
// make sure animation stays on
//this.gotoXyz({x:0,y:0,z:3});
if (this.inspectArrowGrp != null) {
this.sceneAdd(this.inspectArrowGrp);
//this.inspectArrowGrp.visible = true;
}
this.sceneAdd(this.inspectPreviewGroup);
this.isInspectSelect = true;
},
unsetupInspect: function() {
console.log("unsetupInspect");
if (!this.isInspectSelect) {
console.log("we are being asked to unsetup inspect, but it is not running so why are we getting called?");
return;
}
var el = $(this.renderer.domElement);
el.unbind("mousemove");
el.unbind("click");
$('.com-chilipeppr-widget-3d-menu-inspect').removeClass("active");
$('.com-chilipeppr-widget-3d-menu-inspect').removeClass("btn-primary");
//this.unsetupJogRaycaster();
if (this.inspectArrowGrp != null) {
this.sceneRemove(this.inspectArrowGrp);
//this.inspectArrowGrp.visible = false;
}
this.sceneRemove(this.inspectPreviewGroup);
this.isInspectSelect = false;
},
toggleInspect: function(evt) {
if ($('.com-chilipeppr-widget-3d-menu-inspect').hasClass("active")) {
// turn off
this.unsetupInspect(evt);
} else {
this.setupInspect(evt);
}
},
inspectKeyDown: function(evt) {
if ((evt.shiftKey) && !this.isInspectSelect) {
this.wakeAnimate();
this.setupInspect(evt);
}
},
inspectKeyUp: function(evt) {
if ((evt.keyCode == 16) && this.isInspectSelect) {
this.unsetupInspect(evt);
}
},
inspectMouseClick: function(evt) {
console.log("inspectMouseClick. evt:", evt);
return;
if (evt.ctrlKey || evt.altKey) {
if (this.jogCurPos != null) {
var pt = this.jogCurPos;
var gcode = "G90 G0 X" + pt.x.toFixed(3) + " Y" + pt.y.toFixed(3);
gcode += "\n";
chilipeppr.publish("/com-chilipeppr-widget-serialport/send", gcode);
} else {
console.warn("this.jogCurPos should not be null");
}
}
},
onInspectGoto: function(evt) {
if (this.inspectLastObj.uuid != "") {
var lineNum = this.inspectLastObj.userData.args.indx + 1;
chilipeppr.publish("/com-chilipeppr-widget-gcode/jumpToLine", lineNum);
}
},
inspectArrowGrp: null,
createInspectArrow: function() {
if (this.inspectArrowGrp != null) return;
// build pointer line
this.inspectArrowGrp = new THREE.Group();
// draw dotted lines from jog tip and shadow
var lineMat = new THREE.LineDashedMaterial( { color: 0xff0000, dashSize: this.getUnitVal(1), gapSize: this.getUnitVal(1), transparent: true, opacity: 0.5 } );
var lineGeo = new THREE.Geometry();
lineGeo.vertices.push(new THREE.Vector3( 0, 0, this.getUnitVal(-100) ));
lineGeo.vertices.push(new THREE.Vector3( 0, 0, this.getUnitVal(100) ));
var line = new THREE.Line(lineGeo, lineMat); //, THREE.LineStrip);
this.inspectArrowLine = line;
this.inspectArrowGrp.add(line);
this.sceneAdd(this.inspectArrowGrp);
console.log("just added inspectArrowGrp:", this.inspectArrowGrp);
},
inspectCurPos: null,
inspectLastObj: {uuid:""},
inspectLastDecorateGroup: null,
inspectDlgEl: null,
inspectMouseMove: function(evt) {
//event.preventDefault();
if (!this.isInspectSelect) {
return;
}
this.createInspectArrow();
this.wakeAnimate();
console.log("inspectMouseMove. evt:", evt);
var mouse = {};
mouse.x = ( evt.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( evt.clientY / window.innerHeight ) * 2 + 1;
var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 ).unproject( this.camera );
var origin = this.camera.position.clone();
var dir = vector.sub( this.camera.position ).normalize();
// set where arrow is pointing
//this.inspectArrowGrp.position.set(origin.x, origin.y, 0);
var raycaster = new THREE.Raycaster( origin, dir );
raycaster.linePrecision = 0.2;
//console.log("mouse:", mouse, "raycaster:", raycaster);
//console.log("inspecting object.children", this.object.children);
//var io = raycaster.intersectObjects(this.object.children, true);
var io = raycaster.intersectObjects(this.object.userData.threeObjs.children, true);
//console.log("io:", io);
if (io.length > 0) {
// we hit some objects
var obj = io[0];
//console.log("obj:", obj);
// see if this is a new object we haven't hit yet
if (this.inspectLastObj.uuid != obj.object.uuid) {
var o = obj.object;
var ud = o.userData;
console.log("hit new object:", o);
//this.inspectLastOpacity = o.material.opacity;
// reset last object
//console.log("testing for reset last object. this.inspectLastObj:", this.inspectLastObj);
// remove all previous preview items
this.inspectPreviewGroup.children.forEach(function(threeObj) {
this.inspectPreviewGroup.remove(threeObj);
}, this);
if (this.inspectLastObj.uuid != "") {
//this.inspectPreviewGroup(
//this.sceneRemove(this.inspectLastObj);
//this.inspectLastObj.material.opacity = this.inspectLastOpacity;
//this.inspectLastObj.material.color = 0x0000ff;
}
// set the current object to new opacity
//o.material.opacity = 1.0;
//o.material.color = 0xff0000;
//this.sceneAdd(o);
// create glow
var glow = this.createGlow(o);
this.inspectPreviewGroup.add(glow);
// show dialog
var x = event.clientX;
var y = event.clientY;
x += 30; // slide right to clear mouse
y += -140;
this.inspectDlgEl.css('left', x + "px").css('top', y + "px");
this.inspectDlgEl.find('.inspect-line').text(ud.args.indx + 1);
this.inspectDlgEl.find('.inspect-gcode').text(ud.args.origtext);
this.inspectDlgEl.find('.inspect-end').text("X:" + ud.p2.x + ", Y:" + ud.p2.y + ", Z:" + ud.p2.z);
this.inspectDlgEl.find('.inspect-feedrate').text(ud.p2.feedrate);
this.inspectDlgEl.find('.inspect-distance').text(ud.p2.dist.toFixed(3));
this.inspectDlgEl.find('.inspect-time').text((ud.p2.timeMins * 60).toFixed(2) + "s");
var pretty = this.convertMinsToPrettyDuration(ud.p2.timeMinsSum);
this.inspectDlgEl.find('.inspect-timeSum').text(pretty);
this.inspectDlgEl.removeClass("hidden");
// set the last object to this one
this.inspectLastObj = o;
// remove any previous
/*
var that = this;
this.inspectLastDecorateGroup.traverse(function(o) {
that.inspectLastDecorateGroup.remove(o);
});
// draw a bounding box
var bbox = new THREE.BoundingBoxHelper( o, 0xff0000 );
bbox.update();
bbox.object.material.opacity = 0.1;
bbox.object.material.transparent = true;
bbox.material.opacity = 0.1;
bbox.material.transparent = true;
console.log("bbox:", bbox);
//this.sceneAdd( bbox );
this.inspectLastDecorateGroup.add(bbox);
*/
// clone it, make it pretty
/*
var newObj = obj.object.clone();
newObj.material.opacity = 1.0;
this.inspectLastDecorateGroup.add(newObj);
*/
}
//io[0].object.material.opacity = 1.0;
var pt = io[0].point;
// move arrow
this.inspectArrowGrp.position.set(pt.x, pt.y, 0);
this.inspectCurPos = pt.clone();
} else if (false) {
// nothing was hit, reset last obj
// reset last object
console.log("nothing hit. resetting inspectLastObj:", this.inspectLastObj);
if (this.inspectLastObj.uuid != "") {
// remove everything from this.inspectPreviewGroup
this.inspectPreviewGroup.children.forEach(function(threeObj) {
this.inspectPreviewGroup.remove(threeObj);
}, this);
//this.sceneRemove(this.inspectLastObj);
this.inspectLastObj.material.color = 0x0000ff;
this.inspectLastObj.material.opacity = this.inspectLastOpacity;
this.inspectLastObj = {uuid:""};
// hide dialog
this.inspectDlgEl.addClass("hidden");
}
}
},
createGlow: function(threeObj) {
console.log("createGlow. threeObj:", threeObj);
var obj = new THREE.Group();
if (threeObj instanceof THREE.Line) {
console.log("threeObj is Line");
// draw a cube at each end point
var v1 = threeObj.geometry.vertices[0];
var v2 = threeObj.geometry.vertices[threeObj.geometry.vertices.length - 1];
var uv1 = v1.clone();
var uv2 = v2.clone();
var length = v1.distanceTo(v2);
var dir = v2.clone().sub(v1).normalize();
var ray = new THREE.Ray(v1, dir);
var geometry = new THREE.CylinderGeometry( 1, 1, length );
var material = new THREE.MeshNormalMaterial( {
//color: 0x00ff00,
transparent: true,
opacity: 0.1
} );
var cylinder = new THREE.Mesh( geometry, material );
// figure out rotation
var arrow = new THREE.ArrowHelper( dir, v1, length, 0xff0000 );
obj.add(arrow);
//uv2.sub(uv1);
/*uv1.normalize();
uv2.normalize();
var quaternion = new THREE.Quaternion().setFromUnitVectors( uv1, uv2 );
var matrix = new THREE.Matrix4().makeRotationFromQuaternion( quaternion );
cylinder.applyMatrix( matrix );*/
var rot = arrow.rotation.clone()
cylinder.rotation.set(rot.x, rot.y, rot.z);
var cpos = ray.at(length/2);
cylinder.position.set(cpos.x, cpos.y, cpos.z);
console.log("adding cylinder:", cylinder);
obj.add(cylinder);
} else {
console.log("threeObj not Line");
//return
}
return obj;
},
createGlowCubeCaps: function(threeObj) {
console.log("createGlow. threeObj:", threeObj);
var obj = new THREE.Group();
if (threeObj instanceof THREE.Line) {
console.log("threeObj is Line");
// draw a cube at each end point
var v1 = threeObj.geometry.vertices[0];
var v2 = threeObj.geometry.vertices[threeObj.geometry.vertices.length - 1];
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshNormalMaterial( {
//color: 0x00ff00,
transparent: true,
opacity: 0.1
} );
var cube = new THREE.Mesh( geometry, material );
cube.position.set(v1.x, v1.y, v1.z);
var cube2 = cube.clone();
cube2.position.set(v2.x, v2.y, v2.z);
//this.sceneAdd( cube );
console.log("adding cube:", cube, "cube2:", cube2);
obj.add(cube);
obj.add(cube2);
//return cube;
} else {
console.log("threeObj not Line");
//return
}
return obj;
},
// JOG CODE REGION
isJogBtnAttached: false, // is the jog btn setup?
isJogSelect: false, // indicates we're in 3d jog mode
initJog: function() {
if (!this.isJogBtnAttached) {
// attach click event
console.log("doing one time run of initial jog setup. this should not run more than once!!!");
$('.com-chilipeppr-widget-3d-menu-jog').click(this.toggleJog.bind(this));
// attach shortcut key
//$(document).keydown(this.jogKeyDown.bind(this));
//$(document).keydown(this.jogKeyUp.bind(this));
var el = $('#com-chilipeppr-widget-3dviewer-renderArea');
el.focus();
$(document).keydown(this.jogKeyDown.bind(this));
$(document).keyup(this.jogKeyUp.bind(this));
this.isJogBtnAttached = true;
}
},
setupJog: function(evt) {
console.log("setupJog.");
if (this.isJogSelect) {
console.log("we are already in jogging mode. being asked to setup, but returning cuz u can't setup more than once.");
return;
}
// var el = $(this.renderer.domElement);
//var el = $('#com-chilipeppr-widget-3dviewer-renderArea');
//el.focus();
//console.log("setupJog. el:", el);
//el.keydown(this.jogKeyDown.bind(this));
//el.keyup(this.jogKeyUp.bind(this));
//this.renderer.domElement.addEventListener( 'keydown', this.jogKeyDown.bind(this), false );
// start watching mouse
var el = $(this.renderer.domElement);
el.mousemove(this.jogMouseMove.bind(this));
el.click(this.jogMouseClick.bind(this));
$('.com-chilipeppr-widget-3d-menu-jog').addClass("active");
$('.com-chilipeppr-widget-3d-menu-jog').addClass("btn-primary");
// make sure animation stays on
//this.gotoXyz({x:0,y:0,z:3});
this.isJogSelect = true;
},
unsetupJog: function() {
if (!this.isJogSelect) {
console.log("we are being asked to unsetup jog, but it is not running so why are we getting called?");
return;
}
var el = $(this.renderer.domElement);
el.unbind("mousemove"); //this.jogMouseMove.bind(this));
el.unbind("click");
$('.com-chilipeppr-widget-3d-menu-jog').removeClass("active");
$('.com-chilipeppr-widget-3d-menu-jog').removeClass("btn-primary");
this.unsetupJogRaycaster();
this.isJogSelect = false;
},
toggleJog: function(evt) {
if ($('.com-chilipeppr-widget-3d-menu-jog').hasClass("active")) {
// turn off
this.unsetupJog(evt);
} else {
this.setupJog(evt);
}
},
jogKeyDown: function(evt) {
//console.log("jogKeyDown. evt:", evt);
//if ((evt.cltrKey || evt.altKey) && !this.isJogSelect) {
//if ((evt.ctrlKey || evt.altKey) && !this.isJogSelect) {
if ((evt.ctrlKey) && !this.isJogSelect) {
//evt.preventDefault();
//this.isJogSelect = true;
this.wakeAnimate();
this.setupJog(evt);
} else {
//console.log("we are already jogging. ignoring keydown.");
}
},
jogKeyUp: function(evt) {
//console.log("jogKeyUp. evt:", evt);
//if ((evt.keyCode == 17 || evt.keyCode == 18) && this.isJogSelect) {
if ((evt.keyCode == 17) && this.isJogSelect) {
//this.isJogSelect = false;
this.unsetupJog(evt);
}
},
arrowHelper: null,
jogPlane: null,
isJogRaycaster: false,
jogArrow: null,
jogArrowCyl: null,
jogArrowLine: null,
jogArrowShadow: null,
unsetupJogRaycaster: function() {
this.sceneRemove(this.jogPlane);
this.sceneRemove(this.jogArrow);
this.isJogRaycaster = false;
},
setupJogRaycaster: function() {
console.log("doing setupJogRaycaster");
console.log("mimic grid size:", this.grid);
var helper = new THREE.BoundingBoxHelper(this.grid, 0xff0000);
helper.update();
// If you want a visible bounding box
//scene.add(helper);
// If you just want the numbers
console.log(helper.box.min);
console.log(helper.box.max);
console.log("boundingbox:", helper.box);
var w = helper.box.max.x - helper.box.min.x;
var h = helper.box.max.y - helper.box.min.y;
// create plane at z 0 to project onto
var geometry = new THREE.PlaneBufferGeometry( w, h );
var material = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} );
this.jogPlane = new THREE.Mesh( geometry, material );
//this.scene.add( this.jogPlane );
// setup arrow helper
/*
var length = 50;
var hex = 0xffff00;
var origin = new THREE.Vector3(0,0,50);
var dir = new THREE.Vector3(0,0,-1);
//if (this.arrowHelper != null) this.scene.remove(this.arrowHelper);
this.arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
//this.arrowHelper.material.visibility = false;
this.scene.add( this.arrowHelper );
*/
console.group("draw jogArrow");
// remove grid if drawn previously
if (this.jogArrow != null) {
console.log("there was a previous jogArrow. remove it. jogArrow:", this.jogArrow);
this.sceneRemove(this.jogArrow);
} else {
console.log("no previous jogArrow.");
}
// TOOLHEAD WITH SHADOW
var jogArrowGrp = new THREE.Object3D();
// jogArrow Cylinder
// API: THREE.CylinderGeometry(bottomRadius, topRadius, height, segmentsRadius, segmentsHeight)
var cylinder = new THREE.Mesh(new THREE.CylinderGeometry(0, 5, 40, 15, 1, false), new THREE.MeshNormalMaterial());
cylinder.overdraw = true;
cylinder.rotation.x = -90 * Math.PI / 180;
cylinder.position.z = 20;
//cylinder.position.z = 40;
cylinder.material.opacity = 0.3;
cylinder.material.transparent = true;
cylinder.castShadow = false;
console.log("jogArrow cone:", cylinder);
// move the cylinder up in the group to account for z pos of toolhead
// acct for scale
var posZ = (this.toolhead.position.z * 3);
cylinder.position.setZ(posZ + 20);
this.jogArrowCyl = cylinder;
jogArrowGrp.add(cylinder);
// scale the whole thing to correctly match mm vs inches
var scale = this.getUnitVal(1);
jogArrowGrp.scale.set(scale / 3, scale / 3, scale / 3);
// add fake shadow
var triangleShape = new THREE.Shape();
triangleShape.moveTo( 0, 0 );
triangleShape.lineTo( -8, 3 );
triangleShape.lineTo( -8.5, 2 );
triangleShape.lineTo( -8.7, 1 );
triangleShape.lineTo( -8.72, 0 );
triangleShape.lineTo( -8.7, -1 );
triangleShape.lineTo( -8.5, -2 );
triangleShape.lineTo( -8, -3 );
triangleShape.lineTo( 0, 0 ); // close path
var geometry = new THREE.ShapeGeometry( triangleShape );
//var mesh = THREE.SceneUtils.createMultiMaterialObject( geometry, [ new THREE.MeshLambertMaterial( { color: 0x000000, transparent: true, opacity:0.05 } ), new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true, transparent: true } ) ] );
var mesh = THREE.SceneUtils.createMultiMaterialObject( geometry, [ new THREE.MeshLambertMaterial( { color: 0x000000, transparent: true, opacity:0.05 } ) ] );
//mesh.position.set( x, y, z - 125 );
//mesh.rotation.set( rx, ry, rz );
//mesh.scale.set( s, s, s );
// figure out z position