-
Notifications
You must be signed in to change notification settings - Fork 502
/
Copy pathchat.js
1010 lines (821 loc) · 33.4 KB
/
chat.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
"use strict";
// Chat.js
// By Don Hopkins ([email protected])
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
(function() {
var webPageURL = Script.resolvePath("html/ChatPage.html"); // URL of tablet web page.
var randomizeWebPageURL = true; // Set to true for debugging.
var lastWebPageURL = ""; // Last random URL of tablet web page.
var onChatPage = false; // True when chat web page is opened.
var webHandlerConnected = false; // True when the web handler has been connected.
var channelName = "Chat"; // Unique name for channel that we listen to.
var tabletButtonName = "CHAT"; // Tablet button label.
var tabletButtonIcon = "icons/tablet-icons/menu-i.svg"; // Icon for chat button.
var tabletButtonActiveIcon = "icons/tablet-icons/menu-a.svg"; // Active icon for chat button.
var tabletButton = null; // The button we create in the tablet.
var tablet = Tablet.getTablet("com.highfidelity.interface.tablet.system"); // The awesome tablet.
var chatLog = []; // Array of chat messages in the form of [avatarID, displayName, message, data].
var avatarIdentifiers = {}; // Map of avatar ids to dict of identifierParams.
var speechBubbleShowing = false; // Is the speech bubble visible?
var speechBubbleMessage = null; // The message shown in the speech bubble.
var speechBubbleData = null; // The data of the speech bubble message.
var speechBubbleTextID = null; // The id of the speech bubble local text entity.
var speechBubbleTimer = null; // The timer to pop down the speech bubble.
var speechBubbleParams = null; // The params used to create or edit the speech bubble.
// Persistent variables saved in the Settings.
var chatName = ''; // The user's name shown in chat.
var chatLogMaxSize = 100; // The maximum number of chat messages we remember.
var sendTyping = true; // Send typing begin and end notification.
var identifyAvatarDuration = 10; // How long to leave the avatar identity line up, in seconds.
var identifyAvatarLineColor = { red: 0, green: 255, blue: 0 }; // The color of the avatar identity line.
var identifyAvatarMyJointName = 'Head'; // My bone from which to draw the avatar identity line.
var identifyAvatarYourJointName = 'Head'; // Your bone to which to draw the avatar identity line.
var speechBubbleDuration = 10; // How long to leave the speech bubble up, in seconds.
var speechBubbleTextColor = {red: 255, green: 255, blue: 255}; // The text color of the speech bubble.
var speechBubbleBackgroundColor = {red: 0, green: 0, blue: 0}; // The background color of the speech bubble.
var speechBubbleOffset = {x: 0, y: 0.3, z: 0.0}; // The offset from the joint to whic the speech bubble is attached.
var speechBubbleJointName = 'Head'; // The name of the joint to which the speech bubble is attached.
var speechBubbleLineHeight = 0.05; // The height of a line of text in the speech bubble.
var SPEECH_BUBBLE_MAX_WIDTH = 1; // meters
var textSizeOverlay = Overlays.addOverlay("text3d", {
position: MyAvatar.position,
lineHeight: speechBubbleLineHeight,
leftMargin: 0,
topMargin: 0,
rightMargin: 0,
bottomMargin: 0,
ignoreRayIntersection: true,
visible: false
});
// Load the persistent variables from the Settings, with defaults.
function loadSettings() {
chatName = Settings.getValue('Chat_chatName', MyAvatar.displayName);
if (!chatName) {
chatName = randomAvatarName();
}
chatLogMaxSize = Settings.getValue('Chat_chatLogMaxSize', 100);
sendTyping = Settings.getValue('Chat_sendTyping', true);
identifyAvatarDuration = Settings.getValue('Chat_identifyAvatarDuration', 10);
identifyAvatarLineColor = Settings.getValue('Chat_identifyAvatarLineColor', { red: 0, green: 255, blue: 0 });
identifyAvatarMyJointName = Settings.getValue('Chat_identifyAvatarMyJointName', 'Head');
identifyAvatarYourJointName = Settings.getValue('Chat_identifyAvatarYourJointName', 'Head');
speechBubbleDuration = Settings.getValue('Chat_speechBubbleDuration', 10);
speechBubbleTextColor = Settings.getValue('Chat_speechBubbleTextColor', {red: 255, green: 255, blue: 255});
speechBubbleBackgroundColor = Settings.getValue('Chat_speechBubbleBackgroundColor', {red: 0, green: 0, blue: 0});
speechBubbleOffset = Settings.getValue('Chat_speechBubbleOffset', {x: 0.0, y: 0.3, z:0.0});
speechBubbleJointName = Settings.getValue('Chat_speechBubbleJointName', 'Head');
speechBubbleLineHeight = Settings.getValue('Chat_speechBubbleLineHeight', 0.05);
Overlays.editOverlay(textSizeOverlay, {
lineHeight: speechBubbleLineHeight
});
saveSettings();
}
// Save the persistent variables to the Settings.
function saveSettings() {
Settings.setValue('Chat_chatName', chatName);
Settings.setValue('Chat_chatLogMaxSize', chatLogMaxSize);
Settings.setValue('Chat_sendTyping', sendTyping);
Settings.setValue('Chat_identifyAvatarDuration', identifyAvatarDuration);
Settings.setValue('Chat_identifyAvatarLineColor', identifyAvatarLineColor);
Settings.setValue('Chat_identifyAvatarMyJointName', identifyAvatarMyJointName);
Settings.setValue('Chat_identifyAvatarYourJointName', identifyAvatarYourJointName);
Settings.setValue('Chat_speechBubbleDuration', speechBubbleDuration);
Settings.setValue('Chat_speechBubbleTextColor', speechBubbleTextColor);
Settings.setValue('Chat_speechBubbleBackgroundColor', speechBubbleBackgroundColor);
Settings.setValue('Chat_speechBubbleOffset', speechBubbleOffset);
Settings.setValue('Chat_speechBubbleJointName', speechBubbleJointName);
Settings.setValue('Chat_speechBubbleLineHeight', speechBubbleLineHeight);
}
// Reset the Settings and persistent variables to the defaults.
function resetSettings() {
Settings.setValue('Chat_chatName', null);
Settings.setValue('Chat_chatLogMaxSize', null);
Settings.setValue('Chat_sendTyping', null);
Settings.setValue('Chat_identifyAvatarDuration', null);
Settings.setValue('Chat_identifyAvatarLineColor', null);
Settings.setValue('Chat_identifyAvatarMyJointName', null);
Settings.setValue('Chat_identifyAvatarYourJointName', null);
Settings.setValue('Chat_speechBubbleDuration', null);
Settings.setValue('Chat_speechBubbleTextColor', null);
Settings.setValue('Chat_speechBubbleBackgroundColor', null);
Settings.setValue('Chat_speechBubbleOffset', null);
Settings.setValue('Chat_speechBubbleJointName', null);
Settings.setValue('Chat_speechBubbleLineHeight', null);
loadSettings();
}
// Update anything that might depend on the settings.
function updateSettings() {
updateSpeechBubble();
trimChatLog();
updateChatPage();
}
// Trim the chat log so it is no longer than chatLogMaxSize lines.
function trimChatLog() {
if (chatLog.length > chatLogMaxSize) {
chatLog.splice(0, chatLogMaxSize - chatLog.length);
}
}
// Clear the local chat log.
function clearChatLog() {
//print("clearChatLog");
chatLog = [];
updateChatPage();
}
// We got a chat message from the channel.
// Trim the chat log, save the latest message in the chat log,
// and show the message on the tablet, if the chat page is showing.
function handleTransmitChatMessage(avatarID, displayName, message, data) {
//print("receiveChat", "avatarID", avatarID, "displayName", displayName, "message", message, "data", data);
trimChatLog();
chatLog.push([avatarID, displayName, message, data]);
if (onChatPage) {
tablet.emitScriptEvent(
JSON.stringify({
type: "ReceiveChatMessage",
avatarID: avatarID,
displayName: displayName,
message: message,
data: data
}));
}
}
// Trim the chat log, save the latest log message in the chat log,
// and show the message on the tablet, if the chat page is showing.
function logMessage(message, data) {
//print("logMessage", message, data);
trimChatLog();
chatLog.push([null, null, message, data]);
if (onChatPage) {
tablet.emitScriptEvent(
JSON.stringify({
type: "LogMessage",
message: message,
data: data
}));
}
}
// An empty chat message was entered.
// Hide our speech bubble.
function emptyChatMessage(data) {
popDownSpeechBubble();
}
// Notification that we typed a keystroke.
function type() {
//print("type");
}
// Notification that we began typing.
// Notify everyone that we started typing.
function beginTyping() {
//print("beginTyping");
if (!sendTyping) {
return;
}
Messages.sendMessage(
channelName,
JSON.stringify({
type: 'AvatarBeginTyping',
avatarID: MyAvatar.sessionUUID,
displayName: chatName
}));
}
// Notification that somebody started typing.
function handleAvatarBeginTyping(avatarID, displayName) {
//print("handleAvatarBeginTyping:", "avatarID", avatarID, displayName);
}
// Notification that we stopped typing.
// Notify everyone that we stopped typing.
function endTyping() {
//print("endTyping");
if (!sendTyping) {
return;
}
Messages.sendMessage(
channelName,
JSON.stringify({
type: 'AvatarEndTyping',
avatarID: MyAvatar.sessionUUID,
displayName: chatName
}));
}
// Notification that somebody stopped typing.
function handleAvatarEndTyping(avatarID, displayName) {
//print("handleAvatarEndTyping:", "avatarID", avatarID, displayName);
}
// Identify an avatar by drawing a line from our head to their head.
// If the avatar is our own, then just draw a line up into the sky.
function identifyAvatar(yourAvatarID) {
//print("identifyAvatar", yourAvatarID);
unidentifyAvatars();
var myAvatarID = MyAvatar.sessionUUID;
var myJointIndex = MyAvatar.getJointIndex(identifyAvatarMyJointName);
var myJointRotation =
Quat.multiply(
MyAvatar.orientation,
MyAvatar.getAbsoluteJointRotationInObjectFrame(myJointIndex));
var myJointPosition =
Vec3.sum(
MyAvatar.position,
Vec3.multiplyQbyV(
MyAvatar.orientation,
MyAvatar.getAbsoluteJointTranslationInObjectFrame(myJointIndex)));
var yourJointIndex = -1;
var yourJointPosition;
if (yourAvatarID == myAvatarID) {
// You pointed at your own name, so draw a line up from your head.
yourJointPosition = {
x: myJointPosition.x,
y: myJointPosition.y + 1000.0,
z: myJointPosition.z
};
} else {
// You pointed at somebody else's name, so draw a line from your head to their head.
var yourAvatar = AvatarList.getAvatar(yourAvatarID);
if (!yourAvatar) {
return;
}
yourJointIndex = yourAvatar.getJointIndex(identifyAvatarMyJointName)
var yourJointRotation =
Quat.multiply(
yourAvatar.orientation,
yourAvatar.getAbsoluteJointRotationInObjectFrame(yourJointIndex));
yourJointPosition =
Vec3.sum(
yourAvatar.position,
Vec3.multiplyQbyV(
yourAvatar.orientation,
yourAvatar.getAbsoluteJointTranslationInObjectFrame(yourJointIndex)));
}
var identifierParams = {
parentID: myAvatarID,
parentJointIndex: myJointIndex,
lifetime: identifyAvatarDuration,
start: myJointPosition,
endParentID: yourAvatarID,
endParentJointIndex: yourJointIndex,
end: yourJointPosition,
color: identifyAvatarLineColor,
alpha: 1
};
avatarIdentifiers[yourAvatarID] = identifierParams;
identifierParams.lineID = Overlays.addOverlay("line3d", identifierParams);
//print("ADDOVERLAY lineID", lineID, "myJointPosition", JSON.stringify(myJointPosition), "yourJointPosition", JSON.stringify(yourJointPosition), "lineData", JSON.stringify(lineData));
identifierParams.timer =
Script.setTimeout(function() {
//print("DELETEOVERLAY lineID");
unidentifyAvatar(yourAvatarID);
}, identifyAvatarDuration * 1000);
}
// Stop identifying an avatar.
function unidentifyAvatar(yourAvatarID) {
//print("unidentifyAvatar", yourAvatarID);
var identifierParams = avatarIdentifiers[yourAvatarID];
if (!identifierParams) {
return;
}
if (identifierParams.timer) {
Script.clearTimeout(identifierParams.timer);
}
if (identifierParams.lineID) {
Overlays.deleteOverlay(identifierParams.lineID);
}
delete avatarIdentifiers[yourAvatarID];
}
// Stop identifying all avatars.
function unidentifyAvatars() {
var ids = [];
for (var avatarID in avatarIdentifiers) {
ids.push(avatarID);
}
for (var i = 0, n = ids.length; i < n; i++) {
var avatarID = ids[i];
unidentifyAvatar(avatarID);
}
}
// Turn to face another avatar.
function faceAvatar(yourAvatarID, displayName) {
//print("faceAvatar:", yourAvatarID, displayName);
var myAvatarID = MyAvatar.sessionUUID;
if (yourAvatarID == myAvatarID) {
// You clicked on yourself.
return;
}
var yourAvatar = AvatarList.getAvatar(yourAvatarID);
if (!yourAvatar) {
logMessage(displayName + ' is not here!', null);
return;
}
// Project avatar positions to the floor and get the direction between those points,
// then face my avatar towards your avatar.
var yourPosition = yourAvatar.position;
yourPosition.y = 0;
var myPosition = MyAvatar.position;
myPosition.y = 0;
var myOrientation = Quat.lookAtSimple(myPosition, yourPosition);
MyAvatar.orientation = myOrientation;
}
// Make a hopefully unique random anonymous avatar name.
function randomAvatarName() {
return 'Anon_' + Math.floor(Math.random() * 1000000);
}
// Change the avatar size to bigger.
function biggerSize() {
//print("biggerSize");
logMessage("Increasing avatar size", null);
MyAvatar.increaseSize();
}
// Change the avatar size to smaller.
function smallerSize() {
//print("smallerSize");
logMessage("Decreasing avatar size", null);
MyAvatar.decreaseSize();
}
// Set the avatar size to normal.
function normalSize() {
//print("normalSize");
logMessage("Resetting avatar size to normal!", null);
MyAvatar.resetSize();
}
// Send out a "Who" message, including our avatarID as myAvatarID,
// which will be sent in the response, so we can tell the reply
// is to our request.
function transmitWho() {
//print("transmitWho");
logMessage("Who is here?", null);
Messages.sendMessage(
channelName,
JSON.stringify({
type: 'Who',
myAvatarID: MyAvatar.sessionUUID
}));
}
// Send a reply to a "Who" message, with a friendly message,
// our avatarID and our displayName. myAvatarID is the id
// of the avatar who send the Who message, to whom we're
// responding.
function handleWho(myAvatarID) {
var avatarID = MyAvatar.sessionUUID;
if (myAvatarID == avatarID) {
// Don't reply to myself.
return;
}
var message = "I'm here!";
var data = {};
Messages.sendMessage(
channelName,
JSON.stringify({
type: 'ReplyWho',
myAvatarID: myAvatarID,
avatarID: avatarID,
displayName: chatName,
message: message,
data: data
}));
}
// Receive the reply to a "Who" message. Ignore it unless we were the one
// who sent it out (if myAvatarIS is our avatar's id).
function handleReplyWho(myAvatarID, avatarID, displayName, message, data) {
if (myAvatarID != MyAvatar.sessionUUID) {
return;
}
handleTransmitChatMessage(avatarID, displayName, message, data);
}
// Handle input form the user, possibly multiple lines separated by newlines.
// Each line may be a chat command starting with "/", or a chat message.
function handleChatMessage(message, data) {
var messageLines = message.trim().split('\n');
for (var i = 0, n = messageLines.length; i < n; i++) {
var messageLine = messageLines[i];
if (messageLine.substr(0, 1) == '/') {
handleChatCommand(messageLine, data);
} else {
transmitChatMessage(messageLine, data);
}
}
}
// Handle a chat command prefixed by "/".
function handleChatCommand(message, data) {
var commandLine = message.substr(1);
var tokens = commandLine.trim().split(' ');
var command = tokens[0];
var rest = commandLine.substr(command.length + 1).trim();
//print("commandLine", commandLine, "command", command, "tokens", tokens, "rest", rest);
switch (command) {
case '?':
case 'help':
logMessage('Type "/?" or "/help" for help', null);
logMessage('Type "/name <name>" to set your chat name, or "/name" to use your display name. If your display name is not defined, a random name will be used.', null);
logMessage('Type "/close" to close your overhead chat message.', null);
logMessage('Type "/say <something>" to display a new message.', null);
logMessage('Type "/clear" to clear your chat log.', null);
logMessage('Type "/who" to ask who is in the chat session.', null);
logMessage('Type "/bigger", "/smaller" or "/normal" to change your avatar size.', null);
break;
case 'name':
if (rest == '') {
if (MyAvatar.displayName) {
chatName = MyAvatar.displayName;
saveSettings();
logMessage('Your chat name has been set to your display name "' + chatName + '".', null);
} else {
chatName = randomAvatarName();
saveSettings();
logMessage('Your avatar\'s display name is not defined, so your chat name has been set to "' + chatName + '".', null);
}
} else {
chatName = rest;
saveSettings();
logMessage('Your chat name has been set to "' + chatName + '".', null);
}
break;
case 'close':
popDownSpeechBubble();
logMessage('Overhead chat message closed.', null);
break;
case 'say':
if (rest == '') {
emptyChatMessage(data);
} else {
transmitChatMessage(rest, data);
}
break;
case 'who':
transmitWho();
break;
case 'clear':
clearChatLog();
break;
case 'bigger':
biggerSize();
break;
case 'smaller':
smallerSize();
break;
case 'normal':
normalSize();
break;
case 'resetsettings':
resetSettings();
updateSettings();
break;
case 'speechbubbleheight':
var y = parseInt(rest);
if (!isNaN(y)) {
speechBubbleOffset.y = y;
}
saveSettings();
updateSettings();
break;
case 'speechbubbleduration':
var duration = parseFloat(rest);
if (!isNaN(duration)) {
speechBubbleDuration = duration;
}
saveSettings();
updateSettings();
break;
default:
logMessage('Unknown chat command. Type "/help" or "/?" for help.', null);
break;
}
}
// Send out a chat message to everyone.
function transmitChatMessage(message, data) {
//print("transmitChatMessage", 'avatarID', avatarID, 'displayName', displayName, 'message', message, 'data', data);
popUpSpeechBubble(message, data);
Messages.sendMessage(
channelName,
JSON.stringify({
type: 'TransmitChatMessage',
avatarID: MyAvatar.sessionUUID,
displayName: chatName,
message: message,
data: data
}));
}
// Show the speech bubble.
function popUpSpeechBubble(message, data) {
//print("popUpSpeechBubble", message, data);
popDownSpeechBubble();
speechBubbleShowing = true;
speechBubbleMessage = message;
speechBubbleData = data;
updateSpeechBubble();
if (speechBubbleDuration > 0) {
speechBubbleTimer = Script.setTimeout(
function () {
popDownSpeechBubble();
},
speechBubbleDuration * 1000);
}
}
// Update the speech bubble.
// This is factored out so we can update an existing speech bubble if any settings change.
function updateSpeechBubble() {
if (!speechBubbleShowing) {
return;
}
var jointIndex = MyAvatar.getJointIndex(speechBubbleJointName);
var dimensions = {
x: 100.0,
y: 100.0,
z: 0.1
};
speechBubbleParams = {
type: "Text",
lifetime: speechBubbleDuration,
parentID: MyAvatar.sessionUUID,
jointIndex: jointIndex,
dimensions: dimensions,
lineHeight: speechBubbleLineHeight,
leftMargin: 0,
topMargin: 0,
rightMargin: 0,
bottomMargin: 0,
faceCamera: true,
drawInFront: true,
ignoreRayIntersection: true,
text: speechBubbleMessage,
textColor: speechBubbleTextColor,
color: speechBubbleTextColor,
backgroundColor: speechBubbleBackgroundColor
};
// Only overlay text3d has a way to measure the text, not entities.
// So we make a temporary one just for measuring text, then delete it.
var speechBubbleTextOverlayID = Overlays.addOverlay("text3d", speechBubbleParams);
var textSize = Overlays.textSize(textSizeOverlay, speechBubbleMessage);
try {
Overlays.deleteOverlay(speechBubbleTextOverlayID);
} catch (e) {}
//print("updateSpeechBubble:", "speechBubbleMessage", speechBubbleMessage, "textSize", textSize.width, textSize.height);
var fudge = 0.02;
var width = textSize.width + fudge;
var height = speechBubbleLineHeight + fudge;
if (textSize.width >= SPEECH_BUBBLE_MAX_WIDTH) {
var numLines = Math.ceil(width);
height = speechBubbleLineHeight * numLines + fudge;
width = SPEECH_BUBBLE_MAX_WIDTH;
}
dimensions = {
x: width,
y: height,
z: 0.1
};
speechBubbleParams.dimensions = dimensions;
var headRotation =
Quat.multiply(
MyAvatar.orientation,
MyAvatar.getAbsoluteJointRotationInObjectFrame(jointIndex));
var headPosition =
Vec3.sum(
MyAvatar.position,
Vec3.multiplyQbyV(
MyAvatar.orientation,
MyAvatar.getAbsoluteJointTranslationInObjectFrame(jointIndex)));
var rotatedOffset =
Vec3.multiplyQbyV(
headRotation,
speechBubbleOffset);
var position =
Vec3.sum(
headPosition,
rotatedOffset);
position.y += height / 2; // offset based on half of bubble height
speechBubbleParams.position = position;
if (!speechBubbleTextID) {
speechBubbleTextID =
Entities.addEntity(speechBubbleParams, true);
} else {
Entities.editEntity(speechBubbleTextID, speechBubbleParams);
}
//print("speechBubbleTextID:", speechBubbleTextID, "speechBubbleParams", JSON.stringify(speechBubbleParams));
}
// Hide the speech bubble.
function popDownSpeechBubble() {
cancelSpeechBubbleTimer();
speechBubbleShowing = false;
//print("popDownSpeechBubble speechBubbleTextID", speechBubbleTextID);
if (speechBubbleTextID) {
try {
Entities.deleteEntity(speechBubbleTextID);
} catch (e) {}
speechBubbleTextID = null;
}
}
// Cancel the speech bubble popup timer.
function cancelSpeechBubbleTimer() {
if (speechBubbleTimer) {
Script.clearTimeout(speechBubbleTimer);
speechBubbleTimer = null;
}
}
// Show the tablet web page and connect the web handler.
function showTabletWebPage() {
var url = Script.resolvePath(webPageURL);
if (randomizeWebPageURL) {
url += '?rand=' + Math.random();
}
lastWebPageURL = url;
onChatPage = true;
tablet.gotoWebScreen(lastWebPageURL);
// Connect immediately so we don't miss anything.
connectWebHandler();
}
// Update the tablet web page with the chat log.
function updateChatPage() {
if (!onChatPage) {
return;
}
tablet.emitScriptEvent(
JSON.stringify({
type: "Update",
chatLog: chatLog
}));
}
function onChatMessageReceived(channel, message, senderID) {
// Ignore messages to any other channel than mine.
if (channel != channelName) {
return;
}
// Parse the message and pull out the message parameters.
var messageData = JSON.parse(message);
var messageType = messageData.type;
//print("MESSAGE", message);
//print("MESSAGEDATA", messageData, JSON.stringify(messageData));
switch (messageType) {
case 'TransmitChatMessage':
handleTransmitChatMessage(messageData.avatarID, messageData.displayName, messageData.message, messageData.data);
break;
case 'AvatarBeginTyping':
handleAvatarBeginTyping(messageData.avatarID, messageData.displayName);
break;
case 'AvatarEndTyping':
handleAvatarEndTyping(messageData.avatarID, messageData.displayName);
break;
case 'Who':
handleWho(messageData.myAvatarID);
break;
case 'ReplyWho':
handleReplyWho(messageData.myAvatarID, messageData.avatarID, messageData.displayName, messageData.message, messageData.data);
break;
default:
print("onChatMessageReceived: unknown messageType", messageType, "message", message);
break;
}
}
// Handle events from the tablet web page.
function onWebEventReceived(event) {
if (!onChatPage) {
return;
}
//print("onWebEventReceived: event", event);
var eventData = JSON.parse(event);
var eventType = eventData.type;
switch (eventType) {
case 'Ready':
updateChatPage();
break;
case 'Update':
updateChatPage();
break;
case 'HandleChatMessage':
var message = eventData.message;
var data = eventData.data;
//print("onWebEventReceived: HandleChatMessage:", 'message', message, 'data', data);
handleChatMessage(message, data);
break;
case 'PopDownSpeechBubble':
popDownSpeechBubble();
break;
case 'EmptyChatMessage':
emptyChatMessage();
break;
case 'Type':
type();
break;
case 'BeginTyping':
beginTyping();
break;
case 'EndTyping':
endTyping();
break;
case 'IdentifyAvatar':
identifyAvatar(eventData.avatarID);
break;
case 'UnidentifyAvatar':
unidentifyAvatar(eventData.avatarID);
break;
case 'FaceAvatar':
faceAvatar(eventData.avatarID, eventData.displayName);
break;
case 'ClearChatLog':
clearChatLog();
break;
case 'Who':
transmitWho();
break;
case 'Bigger':
biggerSize();
break;
case 'Smaller':
smallerSize();
break;
case 'Normal':
normalSize();
break;
default:
print("onWebEventReceived: unexpected eventType", eventType);
break;
}
}
function onScreenChanged(type, url) {
//print("onScreenChanged", "type", type, "url", url, "lastWebPageURL", lastWebPageURL);
if ((type === "Web") &&
(url === lastWebPageURL)) {
if (!onChatPage) {
onChatPage = true;
connectWebHandler();
}
} else {
if (onChatPage) {
onChatPage = false;
disconnectWebHandler();
}
}
}
function connectWebHandler() {
if (webHandlerConnected) {
return;
}
try {
tablet.webEventReceived.connect(onWebEventReceived);
} catch (e) {
print("connectWebHandler: error connecting: " + e);
return;
}
webHandlerConnected = true;
//print("connectWebHandler connected");
updateChatPage();
}
function disconnectWebHandler() {
if (!webHandlerConnected) {
return;
}
try {
tablet.webEventReceived.disconnect(onWebEventReceived);
} catch (e) {
print("disconnectWebHandler: error disconnecting web handler: " + e);
return;
}
webHandlerConnected = false;
//print("disconnectWebHandler: disconnected");
}
// Show the tablet web page when the chat button on the tablet is clicked.
function onTabletButtonClicked() {
showTabletWebPage();
}
// Shut down the chat application when the tablet button is destroyed.
function onTabletButtonDestroyed() {
shutDown();
}
// Start up the chat application.
function startUp() {
//print("startUp");
loadSettings();
tabletButton = tablet.addButton({
icon: tabletButtonIcon,
activeIcon: tabletButtonActiveIcon,
text: tabletButtonName
});
Messages.subscribe(channelName);
tablet.screenChanged.connect(onScreenChanged);
Messages.messageReceived.connect(onChatMessageReceived);
tabletButton.clicked.connect(onTabletButtonClicked);
Script.scriptEnding.connect(onTabletButtonDestroyed);
logMessage('Type "/?" or "/help" for help with chat.', null);
//print("Added chat button to tablet.");
}
// Shut down the chat application.
function shutDown() {
//print("shutDown");
popDownSpeechBubble();
unidentifyAvatars();
disconnectWebHandler();
Overlays.deleteOverlay(textSizeOverlay);
if (onChatPage) {
tablet.gotoHomeScreen();
onChatPage = false;
}
tablet.screenChanged.disconnect(onScreenChanged);
Messages.messageReceived.disconnect(onChatMessageReceived);
// Clean up the tablet button we made.
tabletButton.clicked.disconnect(onTabletButtonClicked);