-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
647 lines (591 loc) · 16.1 KB
/
main.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
var colors = "8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"
var typeColor = {};
var selectedDate = 0;
var MaxDuration;
var playInterval;
var maxTurnDuration = 30;
var hideOnTimeline =["PlantMotions","PlayerMotions","Visibility"]
function Play(pace){
window.clearInterval(playInterval)
if(!pace){
d3.select("#play_at0").node().checked = true;
return;
}
var delta = pace >0?1:-1
var time = 1000/pace*delta;
d3.selectAll(".timeline")
.each(d=>{
d.selectedTime = Math.max(Math.min(d.selectedTime ,MaxDuration),0);
})
playInterval = window.setInterval(function(){
let canContinue = false;
let tl = d3.selectAll(".timeline")
.each(d=>{
d.selectedTime += delta;
if(d.selectedTime >0 && d.selectedTime < MaxDuration)
canContinue = true;
})
tl.select(".timelineUsefull") // propagate data
tl.selectAll(".timeslider")
.property("value",d=>d.selectedTime/MaxDuration)
refreshDetailsOfSeries()
if(!canContinue)
Play(0)
},time)
}
function colorOf(typeName){
if(!typeColor[typeName])
typeColor[typeName] = "#"+colorHash(typeName);
return typeColor[typeName]
}
function Get(target) {
var req = new XMLHttpRequest();
req.open('GET', target, true);
var p = new Promise(res => {
req.onload = res
}).then(evt => {
return req.response
})
.catch(e=>
console.error(e)
)
req.responseType = 'json';
req.send(null);
return p;
}
function mm_ssFormat(timestamp){
let minitCount = Math.floor(timestamp/60);
let mm = minitCount.toString();
let ss = (timestamp-minitCount*60).toString();
if(mm.length < 2)
mm = "0"+mm;
if(ss.length < 2)
ss = "0"+ss;
return mm+":"+ss;
}
var findEndtryPosition = d3.bisector(function(d) { return d.tiemstamp; }).left
// Offter to the user to donwload some data
function sendFile(data,name){
var link = document.createElement("a");
link.setAttribute("href", "data:txt/utf-8,"+data);
link.setAttribute("download", name);
document.body.appendChild(link); // Required for FF
setTimeout(function(){
link.click() // click seem to interupt curent execution, it's isolated in a timeout.
link.remove()
},0)
}
function setupBars(exps){
let expId = 0;
let markerTypes = {Agent:true};
for(var exp of exps) {
let start = parseFloat(exp.Log[1][0])
let end = parseFloat(exp.Log[exp.Log.length-2][0])
let duration = end - start
exp.timeline = Object.keys(exp)
.flatMap(key=> {
let v = exp[key];
if(Array.isArray(v) && v.length > 1){
markerTypes[key] = true;
let goodLine = v.filter(line => line.length > 1 && !isNaN(line[0]))
return goodLine.map(l => {
let floatTime = parseFloat(l[0])
let data = l.slice(1)
let entry = {
type : key,
tiemstamp : floatTime - start,
data : data,
relativeTime : (floatTime - start)/duration,
experiment : exp
}
entry.isAgentAction = isAgentAction.bind(entry);
return entry
})
}
return []
})
.sort((a,b)=>
a.tiemstamp-b.tiemstamp
);
exp.start = start
exp.end = end
exp.duration = duration;
exp.expId = expId++;
let dateSplit = exp.name.split(/[_T]/)
dateSplit.shift();
dateSplit[1]= dateSplit[1].replace(/-/g,":")
exp.date = new Date(dateSplit.join("T"));
exp.selectedTime = 0;
usedNames = {};
exp.players = {};
exp.Players
.forEach(joined => {
if(joined[3] == "join") {
let name = atob(joined[2]);
if(name != "Moi" && name !="Agent"){
exp.players[joined[1]] = name;
usedNames[name] = true;
}else
exp.players[joined[1]] = "Agent";
}
})
exp.playersNames = Object.keys(usedNames)
}
exps.sort((a,b)=> a.duration-b.duration);
MaxDuration = exps[exps.length-1].duration;
let views = d3.select(".view")
.selectAll("div")
.data(exps)
.enter()
.append("div")
.classed("expsView",1)
.on("click",displayDetailsOf)
var label = views.append("div")
.classed("expLabel",1)
.call(makeLabels)
let tl = views.append("div")
.classed("timeline",1)
tl.append("div")
.classed("timelineUsefull",1)
.style("width",d => ((d.duration/MaxDuration)*100)+"%")
.call(drawEvents)
tl.append("input")
.attr("type","range")
.attr("min","0")
.attr("max","1")
.attr("step",1/4000)
.property("value",0)
.classed("timeslider",1)
.on("input",onTimeChanged)
d3.select(".expsView:first-child").each(displayDetailsOf)
displayFilters(Object.keys(markerTypes))
timeControl()
refreshDetailsOfSeries()
}
function displayFilters(markerTypes){
let fs = d3.select(".filters")
.selectAll("div")
.data(markerTypes)
.enter()
.append("span")
.classed("filterSpan",1)
.style("background-color",d=>colorOf(d))
function applyFilter(type){
let checked = this.checked;
d3.selectAll('bar[eventtype="'+type+'"]')
.attr("hidden",!checked)
.each(d=>d.hidden = !checked )
}
fs.append("input")
.attr("type","checkbox")
.attr("id",d => "toogle"+d)
.attr("name",d => "toogle"+d)
.property('checked', t=>!hideOnTimeline.includes(t))
.on("change",applyFilter)
.each(applyFilter)
fs.append("label")
.attr("for",d => "toogle"+d)
.text(d=> d)
}
function makeLabels(labels){
let dates = labels.append("div")
.classed(".labelDate",1)
.text(d=>d.date);
let info = labels.append("div")
.classed(".labelInfo",1)
.text(d=>d.playersNames.join(", "))
}
function selectTime(t){
var time
var slide
if(t<1 && t>=0){
time = MaxDuration *t;
slide = t;
}
else{
time = t;
slide = t/MaxDuration
}
d3.selectAll(".timelineUsefull")
.each(d=>{
d.selectedTime = time;
})
d3.selectAll(".timeslider")
.property("value",slide)
}
function onTimeChanged(){
let value = this.value
d3.selectAll(".timeslider")
.property("value",value)
d3.selectAll(".timelineUsefull")
.each(d=>{
d.selectedTime = MaxDuration * value;
})
d3.select(this.parentNode.parentNode).each(displayDetailsOf)
}
function isAgentAction(){
if(this.type == "UI" && this.data[4] == "ChatInputField"){
let name = this.experiment.players[this.data[0]];
return name == "Agent"
}
return false;
}
function refreshCanva(domCanva, domTime){
let rootElem = domCanva.parentNode
let rect = rootElem.getBoundingClientRect()
domCanva.height = rect.height;
domCanva.width = rect.width;
var context = domCanva.getContext('2d')
context.clearRect(0,0,domCanva.height,domCanva.width);
console.log("redraw");
for (var child = domTime.firstChild; child; child = child.nextSibling)
child.redraw(context);
}
function Obeserver(domCanva, domTime) {
let callback = function(mutationsList){
for(var mutation of mutationsList) {
if(!domTime.willRedraw){
domTime.willRedraw = true;
requestAnimationFrame(()=>{
try{
refreshCanva(domCanva, domTime)
}finally{
domTime.willRedraw = false;
}
})
}
}
}
return new MutationObserver(callback)
};
function drawEvents(usefullTimeline){
usefullTimeline.each(function(d){
let canvas = d3.select(this).append("canvas")
.on('click',function(){
let rect = this.getBoundingClientRect()
let time = (d3.event.pageX - rect.left) / rect.width * d.duration
selectTime(time);
refreshDetailsOfSeries()
})
.node()
let time = d3.select(this).append("time")
let domTime = time.node()
time.selectAll("bar")
.data(d => d.timeline)
.enter()
.append("bar")
.attr("xrel",d=> d.relativeTime)
.attr("eventType",d=>d.isAgentAction()?"Agent":d.type)
.attr("fill",d=>d.isAgentAction()?colorOf("Agent"):colorOf(d.type)+"af")
.each(function(){
this.redraw = (context)=>{
if(this.getAttribute("hidden") == "true")
return;
context.strokeStyle = this.getAttribute("stroke");
context.fillStyle = this.getAttribute("fill");
let canva = context.canvas
let pos = parseFloat(this.getAttribute("xrel")) * canvas.width;
context.fillRect(pos,0,window.innerWidth *0.001,canvas.height)
}
var observerOptions = {
childList: true,
attributes: true,
subtree: true //Omit or set to false to observe only changes to the parent node.
}
var observer = Obeserver(canvas,domTime);
observer.observe(this, observerOptions);
})
})
window.onresize = function(){
usefullTimeline.each(function(d){
let canvas = d3.select(this).select("canvas").node()
let time = d3.select(this).select("time").node()
refreshCanva(canvas, time)
})
}
window.onresize()
}
function displayDetailsOf(serie){
d3.select(".participants")
.text(serie.playersNames)
d3.select(".duration")
.text(mm_ssFormat(serie.duration));
var visibleEvent = serie.timeline.filter(d=>!d.hidden)
var selectedEvent = Math.max(0,findEndtryPosition(visibleEvent,serie.selectedTime) - 1 )
if(!isNaN(selectedEvent)){
displayDataOf(visibleEvent[Math.min(selectedEvent,visibleEvent.length-1)])
updateChat(serie)
updateMinimap(serie)
}
d3.selectAll(".expsView")
.classed("selected",false);
d3.select(this).classed("selected",true)
}
function refreshDetailsOfSeries(){
d3.select(".expsView.selected").each(displayDetailsOf)
}
function countTurn(chatToDisplay,serie){
let turnCount = 0
let prevMessageDate = 0
let spokenThisTurn = {}
let exchangeStarter;
function isNewTurn(name, date, content){
if(name == "Agent")
return false;
spokenThisTurn[name] = true;
if(!prevMessageDate)
return true;
if(!content)
return false;
var dt = date - prevMessageDate
if(dt > maxTurnDuration)
return true;
return Object.keys(spokenThisTurn).length >= 2 && name == exchangeStarter
}
chatToDisplay.forEach(message => {
let name = serie.playersNames[message[1]]
let date = message[0]
let content = message[6]
if(isNewTurn(name, date, content)){
turnCount ++;
spokenThisTurn = {};
exchangeStarter = name;
spokenThisTurn[name] = true;
}
prevMessageDate = message[0]
})
if(turnCount > 0){
// We count a turn when the next start, so we alway miss the last one.
turnCount ++;
}
return turnCount;
}
function updateChat(serie) {
let chatVP = d3.select(".chatViewPort").node();
let isScrollMax = chatVP.scrollTop + chatVP.clientHeight *1.01 >= chatVP.scrollHeight
var chatUpTo = d3.bisector(function(d) { return parseFloat(d[0])-serie.start; }).right
var chat = serie.UI.filter(x => x[5] == "ChatInputField")
let chatLimit = chatUpTo(chat,serie.selectedTime)
var chatToDisplay = chat.slice(0,chatLimit);
var chatLines = d3.select(".chat")
.selectAll("div")
.data(chatToDisplay,function(d){
return this.id || d && "of_"+serie.expId+"at_"+d[0];
})
var messageCount = d3.nest()
.key(d=>serie.players[d[1]])
.entries(chatToDisplay)
messageCount.forEach(d=>d.values = d.values.length)
var countEntry = d3.select(".CountM tbody")
.selectAll("tr")
.data(messageCount,function(d){
return this.id || d && "countOf_"+d.key;
})
var newCountEntry =countEntry.enter()
.append("tr")
newCountEntry.append("td")
.text(d=>d.key)
newCountEntry.append("td")
.classed("countValue",1)
newCountEntry.merge(countEntry)
.select(".countValue")
.text(d=>d.values)
countEntry.exit().remove()
chatLines.exit().remove()
chatLines.enter()
.append("div")
.classed("chatLines",1)
.call(printChatLine,serie)
d3.select(".CountT")
.text(countTurn(chatToDisplay,serie))
if(isScrollMax)
chatVP.scrollTop = chatVP.scrollHeight;
}
function printChatLine(line,serie){
line.classed("agentLine",d=>{
let playerName = serie.players[d[1]];
return playerName == "Agent"
});
line.on("click", d=> {
selectTime(d[0]-serie.start)
refreshDetailsOfSeries()
})
line.append("span").text(d =>
mm_ssFormat(d[0]-serie.start)+" "+serie.players[d[1]] + " : "
)
line.append("span").text(d => {
var message = atob(d[6]);
return message || "<clicked on message field>"
})
}
function updateMinimap(serie){
function nameOf(d){
return serie.players[d[1]];
}
var moveUpTo = d3.bisector(function(d) { return parseFloat(d[0])-serie.start; }).right
var playersMotions = d3.nest()
.key(nameOf)
.entries(serie.PlayerMotions.filter(x=>x.length > 2))
let playersLayers = d3.select(".minimap")
.selectAll("g.layer_player")
.data(Object.values(playersMotions),function(d){
return this && this.id || d && "layer_player_"+d.key;
})
let playersMarkers = playersLayers.enter()
.append("g")
.classed("layer_player",1)
.attr("id",d=> "layer_player_"+d.key)
.style("--color",d=>
colorOf(d.key)
)
.merge(playersLayers)
.selectAll("g")
.data(
d=>{
let moveLimit = moveUpTo(d.values,serie.selectedTime)
return d.values.slice(0,moveLimit)
},
function(d){
return this && this.id || d && "marker_"+d[0]+"_"+nameOf(d);
}
)
var rad = 1
var newMarkers = playersMarkers.enter()
.append("g")
.attr("id", d=> "marker_"+d[0]+"_"+nameOf(d))
.attr("transform",d=>"translate("+d[2]+","+(-d[4])+")")
.classed("playerMarker",1)
newMarkers.append("circle")
.attr("r",rad)
.attr("cx",0)
.attr("cy",0)
.merge(playersMarkers)
newMarkers.append("line")
.attr("x1",0)
.attr("y1",0)
.attr("x2",function(d,i,arr){
return i>0? arr[i-1].__data__[2] - d[2]:0
})
.attr("y2",function(d,i,arr){
return i>0? -(arr[i-1].__data__[4] - d[4]):0
})
newMarkers.append("polygon")
.attr("points",d =>{
let lookx = d[5] * rad
let looky = -d[7] * rad
let sqrt3 = Math.sqrt(3)
return [
[-looky, lookx],
[sqrt3 * lookx, sqrt3 * looky],
[looky, -lookx]
].map(x=>x.join(",")).join(" ")
})
newMarkers.append("title")
.text(nameOf)
newMarkers.merge(playersMarkers)
.attr("opacity",d=>(0.3*(parseFloat(d[0])-serie.start)/serie.selectedTime))
.filter(":last-child")
.attr("opacity",1)
playersMarkers.exit().remove();
playersLayers.exit().remove();
var plants = d3.nest()
.key(d=>d[1])
.entries(serie.PlantMotions.filter(x=>x.length > 2))
.map(e => {
let age = (parseFloat(e.values[0][0])-serie.start)
let negativeAge = age > serie.selectedTime
if(negativeAge)
return null;
let lastIndex = moveUpTo(e.values,serie.selectedTime)
return e.values[Math.max(0,lastIndex-1)];
})
.filter(x=>x)
var markerPlants = d3.select(".plantLayer")
.selectAll("g")
.data(plants,function(d){
return this && this.id || d && "marker_"+d[0]+"_"+d[1];
})
var newPlantsMarkers = markerPlants.enter()
.append("g")
.attr("id",d=> "marker_"+d[0]+"_"+d[1])
newPlantsMarkers.append("text")
.attr("x",0)
.attr("y",0)
.text("🌳")
.append("title")
newPlantsMarkers.merge(markerPlants)
.attr("transform",d=>"rotate("+d[6]+") translate("+d[3]+","+(-d[5])+")")
.select("title")
.text(d=> "Last modified by "+serie.players[d[2]])
markerPlants.exit().remove()
let playersLastPos = d3.select(".minimap")
.selectAll("use")
.data(
d3.select(".minimap").selectAll("g.layer_player").nodes(),
function(d){
return this && this.id || d && "last_of"+d.id;
}
)
playersLastPos.enter()
.append("use")
.style("--color",d=>{
return d.style.getPropertyValue("--color")
}
)
.attr("id",d=> "last_of"+d.id)
.merge(playersLastPos)
.raise()
.attr("href",d => {
var ns = d3.select(d).selectAll(".playerMarker").nodes()
if(!ns || !ns.length)
return "";
return "#"+ns[ns.length-1].id;
})
playersLastPos.exit().remove();
}
function displayDataOf(event){
d3.select(".eventDate")
.text(mm_ssFormat(event.tiemstamp))
d3.select(".eventType")
.text(event.type)
displaySpeData(event.type, event.data)
}
function timeControl(){
let flows = [-10,-2,-1,0,1,2,10]
let flowControl = d3.select(".timeControl")
.selectAll("span")
.data(flows)
.enter()
.append("span")
.classed("timeButton",1)
flowControl.append("label")
.attr("for",d=>"play_at"+d)
.text(d=>d)
flowControl.append("input")
.attr("name",d=>"play_rate")
.attr("id",d=>"play_at"+d)
.attr("type","radio")
.on("change",function(d){
if(this.checked)
Play(d);
})
.each(function(d){
this.checked = !d;
})
}
function displaySpeData(type, data){
d3.select(".eventOwnData")
.text(data.toString())
}
function colorHash(stringy){
var hash = 0, i, chr;
var str = stringy.toString()
if (str.length === 0) return hash;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
let start = hash % (colors.length - 6)
return colors.slice(start,start+6);
}