forked from ngscopeclient/scopehal-apps
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaveformArea.cpp
More file actions
4436 lines (3804 loc) · 130 KB
/
WaveformArea.cpp
File metadata and controls
4436 lines (3804 loc) · 130 KB
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
/***********************************************************************************************************************
* *
* ngscopeclient *
* *
* Copyright (c) 2012-2026 Andrew D. Zonenberg and contributors *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *
* following conditions are met: *
* *
* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *
* following disclaimer. *
* *
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *
* following disclaimer in the documentation and/or other materials provided with the distribution. *
* *
* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
***********************************************************************************************************************/
/**
@file
@author Andrew D. Zonenberg
@brief Implementation of WaveformArea
*/
#include "ngscopeclient.h"
#include "WaveformArea.h"
#include "MainWindow.h"
#include "../../scopehal/TwoLevelTrigger.h"
#include "../../scopeprotocols/ConstellationFilter.h"
#include "../../scopeprotocols/EyePattern.h"
#include "../../scopeprotocols/SpectrogramFilter.h"
#include "../../scopeprotocols/Waterfall.h"
#include "../../scopehal/DensityFunctionWaveform.h"
#include "imgui_internal.h" //for SetItemUsingMouseWheel
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DisplayedChannel
DisplayedChannel::DisplayedChannel(StreamDescriptor stream, Session& session)
: m_colorRamp("eye-gradient-viridis")
, m_stream(stream)
, m_session(session)
, m_rasterizedWaveform("DisplayedChannel.m_rasterizedWaveform")
, m_indexBuffer("DisplayedChannel.m_indexBuffer")
, m_rasterizedX(0)
, m_rasterizedY(0)
, m_cachedX(0)
, m_cachedY(0)
, m_persistenceEnabled(false)
, m_yButtonPos(0)
{
auto schan = dynamic_cast<OscilloscopeChannel*>(stream.m_channel);
if(schan)
schan->AddRef();
vk::CommandPoolCreateInfo cmdPoolInfo(
vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
session.GetMainWindow()->GetRenderQueue()->m_family );
m_utilCmdPool = std::make_unique<vk::raii::CommandPool>(*g_vkComputeDevice, cmdPoolInfo);
vk::CommandBufferAllocateInfo bufinfo(**m_utilCmdPool, vk::CommandBufferLevel::ePrimary, 1);
m_utilCmdBuffer = make_unique<vk::raii::CommandBuffer>(
std::move(vk::raii::CommandBuffers(*g_vkComputeDevice, bufinfo).front()));
//Use GPU-side memory for rasterized waveform
//TODO: instead of using CPU-side mirror, use a shader to memset it when clearing?
m_rasterizedWaveform.SetCpuAccessHint(AcceleratorBuffer<float>::HINT_LIKELY);
m_rasterizedWaveform.SetGpuAccessHint(AcceleratorBuffer<float>::HINT_LIKELY);
//Create tone map pipeline depending on waveform type
switch(m_stream.GetType())
{
case Stream::STREAM_TYPE_EYE:
m_toneMapPipe = make_shared<ComputePipeline>(
"shaders/EyeToneMap.spv", 1, sizeof(EyeToneMapArgs), 1, 1);
break;
case Stream::STREAM_TYPE_CONSTELLATION:
m_toneMapPipe = make_shared<ComputePipeline>(
"shaders/ConstellationToneMap.spv", 1, sizeof(ConstellationToneMapArgs), 1, 1);
break;
case Stream::STREAM_TYPE_WATERFALL:
m_toneMapPipe = make_shared<ComputePipeline>(
"shaders/WaterfallToneMap.spv", 1, sizeof(WaterfallToneMapArgs), 1, 1);
break;
case Stream::STREAM_TYPE_SPECTROGRAM:
m_toneMapPipe = make_shared<ComputePipeline>(
"shaders/SpectrogramToneMap.spv", 1, sizeof(SpectrogramToneMapArgs), 1, 1);
break;
default:
m_toneMapPipe = make_shared<ComputePipeline>(
"shaders/WaveformToneMap.spv", 1, sizeof(WaveformToneMapArgs), 1);
}
//If we have native int64 support we can do the index search for sparse waveforms on the GPU
if(g_hasShaderInt64)
{
m_indexSearchComputePipeline = make_shared<ComputePipeline>(
"shaders/IndexSearch.spv", 2, sizeof(IndexSearchConstants));
//Use GPU local memory for index buffer
m_indexBuffer.SetCpuAccessHint(AcceleratorBuffer<uint32_t>::HINT_LIKELY);
m_indexBuffer.SetGpuAccessHint(AcceleratorBuffer<uint32_t>::HINT_LIKELY);
}
else
{
//Use pinned memory for index buffer since it should only be read once
m_indexBuffer.SetCpuAccessHint(AcceleratorBuffer<uint32_t>::HINT_LIKELY);
m_indexBuffer.SetGpuAccessHint(AcceleratorBuffer<uint32_t>::HINT_UNLIKELY);
}
}
DisplayedChannel::~DisplayedChannel()
{
auto schan = dynamic_cast<OscilloscopeChannel*>(m_stream.m_channel);
if(schan)
{
//Remove pausable filters from trigger group when they're deleted
//TODO: potential race condition here?
auto pf = dynamic_cast<PausableFilter*>(schan);
if(pf && (pf->GetRefCount() == 1))
{
LogTrace("Deleting last copy of pausable filter, removing from trigger group\n");
m_session.GetTriggerGroupForFilter(pf)->RemoveFilter(pf);
}
auto scope = schan->GetScope();
schan->Release();
//If the channel is part of an instrument and we turned it off, we may have changed the set of sample rates
//Refresh the sidebar!
//TODO: make this more narrow and only refresh this scope etc?
if( (scope != nullptr) && !schan->IsEnabled())
m_session.GetMainWindow()->RefreshStreamBrowserDialog();
}
}
/**
@brief Handles a change in size of the displayed waveform
@param newSize New size of WaveformArea
@return true if size has changed, false otherwise
*/
bool DisplayedChannel::UpdateSize(ImVec2 newSize, MainWindow* top)
{
size_t x = newSize.x;
size_t y = newSize.y;
//Special processing needed for eyes coming from BERTs or sampling scopes
//These can change size on their own even if the window isn't resized
auto eye = dynamic_cast<EyePattern*>(m_stream.m_channel);
auto constellation = dynamic_cast<ConstellationFilter*>(m_stream.m_channel);
auto waterfall = dynamic_cast<Waterfall*>(m_stream.m_channel);
auto data = m_stream.GetData();
auto eyedata = dynamic_cast<EyeWaveform*>(data);
if( (m_stream.GetType() == Stream::STREAM_TYPE_EYE) && eyedata && !eye)
{
x = eyedata->GetWidth();
y = eyedata->GetHeight();
if( (m_cachedX != x) || (m_cachedY != y) )
LogTrace("Hardware eye resolution changed, processing resize\n");
}
if( (m_cachedX != x) || (m_cachedY != y) )
{
m_cachedX = x;
m_cachedY = y;
//Don't actually create an image object if the image is degenerate (zero pixels)
if( (x == 0) || (y == 0) )
return true;
//If this is an eye pattern filter, need to reallocate the texture
//To avoid constantly destroying the integrated eye if we slightly resize stuff, round up to next power of 2
size_t roundedX = pow(2, ceil(log2(x)));
size_t roundedY = pow(2, ceil(log2(y)));
if(eye)
{
if( (eye->GetWidth() != roundedX) || (eye->GetHeight() != roundedY) )
{
eye->SetWidth(roundedX);
eye->SetHeight(roundedY);
eye->Refresh(*m_utilCmdBuffer, m_session.GetMainWindow()->GetRenderQueue());
}
x = roundedX;
y = roundedY;
}
//Eyes coming from BERTs, sampling scopes, etc cannot be reallocated
//TODO: what about if someone else makes their own filter that outputs eyes?
else if(m_stream.GetType() == Stream::STREAM_TYPE_EYE)
{
if(eyedata)
{
x = eyedata->GetWidth();
y = eyedata->GetHeight();
}
}
//Waterfalls only care about height
else if(waterfall)
{
if(waterfall->GetHeight() != roundedY)
{
waterfall->SetHeight(roundedY);
FilterGraphExecutor ex;
set<FlowGraphNode*> nodesToUpdate;
nodesToUpdate.emplace(waterfall);
ex.RunBlocking(nodesToUpdate);
}
//Rendered image should be the actual plot size
}
else if(constellation)
{
if( (constellation->GetWidth() != roundedX) || (constellation->GetHeight() != roundedY) )
{
constellation->SetWidth(roundedX);
constellation->SetHeight(roundedY);
FilterGraphExecutor ex;
set<FlowGraphNode*> nodesToUpdate;
nodesToUpdate.emplace(constellation);
ex.RunBlocking(nodesToUpdate);
}
x = roundedX;
y = roundedY;
}
LogTrace("Displayed channel resized (to %zu x %zu), reallocating texture\n", x, y);
//NOTE: Assumes the render queue is also capable of transfers (see QueueManager)
vk::ImageCreateInfo imageInfo(
{},
vk::ImageType::e2D,
vk::Format::eR32G32B32A32Sfloat,
vk::Extent3D(x, y, 1),
1,
1,
VULKAN_HPP_NAMESPACE::SampleCountFlagBits::e1,
VULKAN_HPP_NAMESPACE::ImageTiling::eOptimal,
vk::ImageUsageFlagBits::eStorage | vk::ImageUsageFlagBits::eSampled,
vk::SharingMode::eExclusive,
{},
vk::ImageLayout::eUndefined
);
//Keep a reference to the old texture around for one more frame
//in case the previous frame hasn't fully completed rendering yet
top->AddTextureUsedThisFrame(m_texture);
//Make the new texture and mark that as in use too
m_texture = make_shared<Texture>(
*g_vkComputeDevice, imageInfo, top->GetTextureManager(), "DisplayedChannel.m_texture");
top->AddTextureUsedThisFrame(m_texture);
//Add a barrier to convert the image format to "general"
lock_guard<mutex> lock(g_vkTransferMutex);
vk::ImageSubresourceRange range(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1);
vk::ImageMemoryBarrier barrier(
vk::AccessFlagBits::eNone,
vk::AccessFlagBits::eShaderWrite,
vk::ImageLayout::eUndefined,
vk::ImageLayout::eGeneral,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
m_texture->GetImage(),
range);
g_vkTransferCommandBuffer->begin({});
g_vkTransferCommandBuffer->pipelineBarrier(
vk::PipelineStageFlagBits::eTopOfPipe,
vk::PipelineStageFlagBits::eComputeShader,
{},
{},
{},
barrier);
g_vkTransferCommandBuffer->end();
g_vkTransferQueue->SubmitAndBlock(*g_vkTransferCommandBuffer);
return true;
}
return false;
}
/**
@brief Prepares to rasterize the waveform at the specified resolution
*/
void DisplayedChannel::PrepareToRasterize(size_t x, size_t y)
{
bool sizeChanged = (m_rasterizedX != x) || (m_rasterizedY != y);
m_rasterizedX = x;
m_rasterizedY = y;
if(sizeChanged)
{
size_t npixels = x*y;
m_rasterizedWaveform.resize(npixels);
//fill with black
m_rasterizedWaveform.PrepareForCpuAccess();
memset(m_rasterizedWaveform.GetCpuPointer(), 0, npixels * sizeof(float));
m_rasterizedWaveform.MarkModifiedFromCpu();
}
//Allocate index buffer for sparse waveforms
if(!IsDensePacked())
m_indexBuffer.resize(x);
}
/**
@brief Serializes the configuration for this channel
*/
YAML::Node DisplayedChannel::Serialize(IDTable& table) const
{
YAML::Node node;
node["persistence"] = m_persistenceEnabled;
node["channel"] = table[m_stream.m_channel];
node["stream"] = m_stream.m_stream;
node["colorRamp"] = m_colorRamp;
return node;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
WaveformArea::WaveformArea(StreamDescriptor stream, shared_ptr<WaveformGroup> group, MainWindow* parent)
: m_width(1)
, m_height(1)
, m_yAxisOffset(0)
, m_ymid(0)
, m_pixelsPerYAxisUnit(1)
, m_yAxisUnit(stream.GetYAxisUnits())
, m_dragState(DRAG_STATE_NONE)
, m_group(group)
, m_parent(parent)
, m_tLastMouseMove(GetTime())
, m_mouseOverTriggerArrow(false)
, m_mouseOverBERTarget(false)
, m_triggerLevelDuringDrag(0)
, m_xAxisPosDuringDrag(0)
, m_triggerDuringDrag(nullptr)
, m_bertChannelDuringDrag(nullptr)
, m_lastRightClickOffset(0)
, m_channelButtonHeight(0)
, m_dragPeakLabel(nullptr)
, m_mouseOverButton(false)
, m_yAxisCursorMode(Y_CURSOR_NONE)
{
m_yAxisCursorPositions[0] = 0;
m_yAxisCursorPositions[1] = 0;
m_displayedChannels.push_back(make_shared<DisplayedChannel>(stream, m_parent->GetSession()));
}
WaveformArea::~WaveformArea()
{
m_displayedChannels.clear();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Serialization
void WaveformArea::SerializeConfiguration(YAML::Node& node)
{
YAML::Node ycursors;
switch(m_yAxisCursorMode)
{
case Y_CURSOR_SINGLE:
ycursors["mode"] = "single";
break;
case Y_CURSOR_DUAL:
ycursors["mode"] = "dual";
break;
case Y_CURSOR_NONE:
default:
ycursors["mode"] = "none";
break;
}
ycursors["pos0"] = m_yAxisCursorPositions[0];
ycursors["pos1"] = m_yAxisCursorPositions[1];
node["ycursors"] = ycursors;
}
void WaveformArea::LoadConfiguration(YAML::Node& node)
{
auto cursornode = node["ycursors"];
if(cursornode)
{
m_yAxisCursorPositions[0] = cursornode["pos0"].as<float>();
m_yAxisCursorPositions[1] = cursornode["pos1"].as<float>();
auto mode = cursornode["mode"].as<string>();
if(mode == "single")
m_yAxisCursorMode = Y_CURSOR_SINGLE;
else if(mode == "dual")
m_yAxisCursorMode = Y_CURSOR_DUAL;
else
m_yAxisCursorMode = Y_CURSOR_NONE;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Stream management
/**
@brief Adds a new stream to this plot
*/
void WaveformArea::AddStream(StreamDescriptor desc, bool persistence, const string& ramp)
{
auto chan = make_shared<DisplayedChannel>(desc, m_parent->GetSession());
chan->SetPersistenceEnabled(persistence);
chan->m_colorRamp = ramp;
m_displayedChannels.push_back(chan);
}
/**
@brief Removes the stream at a specified index
*/
void WaveformArea::RemoveStream(size_t i)
{
//See if we're dragging the stream being removed (i.e. we just dropped it somewhere).
//If so, immediately stop all drag activity.
//This normally happens in Render() but if we're in an off-screen tab, it might be indefinitely delayed
//until we re-activate that tab and we want the drag/drop overlays to disappear immediately
//(https://github.com/ngscopeclient/scopehal-apps/issues/651)
auto stream = m_displayedChannels[i]->GetStream();
if( (m_dragState == DRAG_STATE_CHANNEL) && (stream == m_dragStream) )
m_dragState = DRAG_STATE_NONE;
m_channelsToRemove.push_back(m_displayedChannels[i]);
m_displayedChannels.erase(m_displayedChannels.begin() + i);
}
/**
@brief Returns the first analog stream displayed in this area.
If no analog waveforms are visible, returns a null stream.
*/
StreamDescriptor WaveformArea::GetFirstAnalogStream()
{
for(auto chan : m_displayedChannels)
{
auto stream = chan->GetStream();
if(stream.GetType() == Stream::STREAM_TYPE_ANALOG)
return stream;
}
return StreamDescriptor(nullptr, 0);
}
/**
@brief Returns the first analog, spectrogram or eye pattern stream displayed in this area.
(this really means "has a useful Y axis")
If no suitable waveforms returns a null stream.
*/
StreamDescriptor WaveformArea::GetFirstAnalogOrDensityStream()
{
for(auto chan : m_displayedChannels)
{
auto stream = chan->GetStream();
if(stream.GetType() == Stream::STREAM_TYPE_ANALOG)
return stream;
if(stream.GetType() == Stream::STREAM_TYPE_SPECTROGRAM)
return stream;
if(stream.GetType() == Stream::STREAM_TYPE_EYE)
return stream;
if(stream.GetType() == Stream::STREAM_TYPE_CONSTELLATION)
return stream;
}
return StreamDescriptor(nullptr, 0);
}
/**
@brief Returns the first eye pattern displayed in this area.
If no eye patterns are visible, returns a null stream.
*/
StreamDescriptor WaveformArea::GetFirstEyeStream()
{
for(auto chan : m_displayedChannels)
{
auto stream = chan->GetStream();
if(stream.GetType() == Stream::STREAM_TYPE_EYE)
return stream;
}
return StreamDescriptor(nullptr, 0);
}
/**
@brief Returns the first constellation diagram displayed in this area.
If no constellation diagrams are visible, returns a null stream.
*/
StreamDescriptor WaveformArea::GetFirstConstellationStream()
{
for(auto chan : m_displayedChannels)
{
auto stream = chan->GetStream();
if(stream.GetType() == Stream::STREAM_TYPE_CONSTELLATION)
return stream;
}
return StreamDescriptor(nullptr, 0);
}
/**
@brief Returns the first density plot displayed in this area.
If none are visible, returns a null stream.
*/
StreamDescriptor WaveformArea::GetFirstDensityFunctionStream()
{
for(auto chan : m_displayedChannels)
{
auto stream = chan->GetStream();
if(stream.GetType() == Stream::STREAM_TYPE_EYE)
return stream;
if(stream.GetType() == Stream::STREAM_TYPE_CONSTELLATION)
return stream;
if(stream.GetType() == Stream::STREAM_TYPE_SPECTROGRAM)
return stream;
if(stream.GetType() == Stream::STREAM_TYPE_WATERFALL)
return stream;
}
return StreamDescriptor(nullptr, 0);
}
/**
@brief Marks all of our waveform textures as being used this frame
*/
void WaveformArea::ReferenceWaveformTextures()
{
for(auto chan : m_displayedChannels)
m_parent->AddTextureUsedThisFrame(chan->GetTexture());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Y axis helpers
float WaveformArea::PixelsToYAxisUnits(float pix)
{
return pix / m_pixelsPerYAxisUnit;
}
float WaveformArea::YAxisUnitsToPixels(float volt)
{
return volt * m_pixelsPerYAxisUnit;
}
float WaveformArea::YAxisUnitsToYPosition(float volt)
{
return m_ymid - YAxisUnitsToPixels(volt + m_yAxisOffset);
}
float WaveformArea::YPositionToYAxisUnits(float y)
{
return PixelsToYAxisUnits(-1 * (y - m_ymid) ) - m_yAxisOffset;
}
float WaveformArea::PickStepSize(float volts_per_half_span, int min_steps, int max_steps)
{
static const float steps[3] = {1, 2, 5};
for(int exp = -4; exp < 12; exp ++)
{
for(int i=0; i<3; i++)
{
float step = pow(10, exp) * steps[i];
float steps_per_half_span = volts_per_half_span / step;
if(steps_per_half_span > max_steps)
continue;
if(steps_per_half_span < min_steps)
continue;
return step;
}
}
//if no hits
return FLT_MAX;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// GUI widget rendering
/**
@brief Returns true if a channel is currently being dragged
*/
bool WaveformArea::IsChannelBeingDragged()
{
return (m_dragState == DRAG_STATE_CHANNEL) || (m_dragState == DRAG_STATE_CHANNEL_LAST);
}
/**
@brief Returns the channel being dragged, if one exists
*/
StreamDescriptor WaveformArea::GetChannelBeingDragged()
{
if(IsChannelBeingDragged())
return m_dragStream;
else
return StreamDescriptor(nullptr, 0);
}
/**
@brief Renders a waveform area
Returns false if the area should be closed (no more waveforms visible in it)
*/
bool WaveformArea::Render(int iArea, int numAreas, ImVec2 clientArea)
{
if(m_dragState != DRAG_STATE_NONE)
OnDragUpdate();
//Clear channels from last frame
if(!m_channelsToRemove.empty())
{
g_vkComputeDevice->waitIdle();
m_channelsToRemove.clear();
}
//Save timestamps if we right clicked
if(ImGui::IsMouseClicked(ImGuiMouseButton_Right))
m_lastRightClickOffset = m_group->XPositionToXAxisUnits(ImGui::GetMousePos().x);
//Detect mouse movement
double tnow = GetTime();
auto mouseDelta = ImGui::GetIO().MouseDelta;
if( (mouseDelta.x != 0) || (mouseDelta.y != 0) )
m_tLastMouseMove = tnow;
ImGui::PushID(to_string(iArea).c_str());
float totalHeightAvailable = floor(clientArea.y - 2*ImGui::GetFrameHeightWithSpacing());
float spacing = m_group->GetSpacing();
float heightPerArea = totalHeightAvailable / numAreas;
float totalSpacing = (numAreas-1)*spacing;
float unspacedHeightPerArea = floor( (totalHeightAvailable - totalSpacing) / numAreas);
unspacedHeightPerArea -= ImGui::GetStyle().FramePadding.y;
if(numAreas == 1)
unspacedHeightPerArea = heightPerArea;
//Update cached scale
m_height = unspacedHeightPerArea;
auto first = GetFirstAnalogOrDensityStream();
if(first)
{
//Don't touch scale if we're dragging, since the dragged value is newer than the hardware value
if(m_dragState != DRAG_STATE_Y_AXIS)
m_yAxisOffset = first.GetOffset();
m_pixelsPerYAxisUnit = unspacedHeightPerArea / first.GetVoltageRange();
m_yAxisUnit = first.GetYAxisUnits();
}
//Size of the Y axis view at the right of the plot
float yAxisWidth = m_group->GetYAxisWidth();
float yAxisWidthSpaced = yAxisWidth + spacing;
//Settings calculated by RenderGrid() then reused in RenderYAxis()
map<float, float> gridmap;
float vbot = 0.0f;
float vtop = 0.0f;
auto cpos = ImGui::GetCursorPos();
if(ImGui::BeginChild(ImGui::GetID(this), ImVec2(clientArea.x - yAxisWidthSpaced, unspacedHeightPerArea)))
{
auto csize = ImGui::GetContentRegionAvail();
auto pos = ImGui::GetWindowPos();
m_width = csize.x;
//Calculate midpoint of our plot
m_ymid = pos.y + unspacedHeightPerArea / 2;
//Draw the background
RenderBackgroundGradient(pos, csize);
RenderGrid(pos, csize, gridmap, vbot, vtop);
//Blank out space for the actual waveform
ImGui::Dummy(ImVec2(csize.x, csize.y));
ImGui::SetNextItemAllowOverlap();
//Check for context menu if we didn't do one yet
PlotContextMenu();
//Draw actual waveforms (and protocol decode overlays)
RenderWaveforms(pos, csize);
ImGui::SetItemKeyOwner(ImGuiKey_MouseWheelY);
ImGui::SetItemKeyOwner(ImGuiKey_MouseWheelX);
if(ImGui::IsItemHovered())
{
auto wheel = ImGui::GetIO().MouseWheel;
auto wheel_h = ImGui::GetIO().MouseWheelH;
if((wheel != 0) || (wheel_h != 0))
OnMouseWheelPlotArea(wheel, wheel_h);
}
//Make targets for drag-and-drop
if(ImGui::GetDragDropPayload() != nullptr)
DragDropOverlays(pos, csize, iArea, numAreas);
//Cursors have to be drawn over the waveform
RenderCursors(pos, csize);
RenderBERSamplingPoint(pos, csize);
//Make sure all channels have same vertical scale and warn if not
CheckForScaleMismatch(pos, csize);
//Tooltip for eye pattern
RenderEyePatternTooltip(pos, csize);
//Draw control widgets
m_mouseOverButton = false;
ImGui::SetCursorPos(ImGui::GetWindowContentRegionMin());
ImGui::BeginGroup();
for(size_t i=0; i<m_displayedChannels.size(); i++)
ChannelButton(m_displayedChannels[i], i);
ImGui::EndGroup();
ImGui::SetNextItemAllowOverlap();
}
else
m_mouseOverButton = false;
ImGui::EndChild();
//Handle help messages
if(ImGui::IsItemHovered() && !m_mouseOverButton)
m_parent->AddStatusHelp("mouse_wheel", "Zoom horizontal axis");
//Draw the vertical scale on the right side of the plot
RenderYAxis(ImVec2(yAxisWidth, unspacedHeightPerArea), gridmap, vbot, vtop);
//Render the Y axis cursors (if we have any) over the top of everything else
{
auto csize = ImGui::GetContentRegionAvail();
auto pos = ImGui::GetWindowPos();
ImGui::SetCursorPos(cpos);
RenderYAxisCursors(pos, csize, yAxisWidth);
}
//Cursor should now be at end of window
ImGui::SetCursorPos(ImVec2(cpos.x, cpos.y + unspacedHeightPerArea));
//Add spacing
if(iArea != numAreas-1)
ImGui::Dummy(ImVec2(0, spacing));
ImGui::PopID();
//Update scale again in case we had a mouse wheel event
//(we need scale to be accurate for the re-render in the background thread)
if(first)
m_pixelsPerYAxisUnit = unspacedHeightPerArea / first.GetVoltageRange();
if(m_displayedChannels.empty())
return false;
return true;
}
/**
@brief Render horizontal cursors over the plot
*/
void WaveformArea::RenderYAxisCursors(ImVec2 pos, ImVec2 size, float yAxisWidth)
{
//No cursors? Nothing to do
if(m_yAxisCursorMode == Y_CURSOR_NONE)
{
//Exit cursor drag state if we no longer have a cursor to drag
if( (m_dragState == DRAG_STATE_Y_CURSOR0) || (m_dragState == DRAG_STATE_Y_CURSOR1) )
m_dragState = DRAG_STATE_NONE;
return;
}
//Create a child window for all of our drawing
//(this is needed so we're above the WaveformArea content in z order, but behind popup windows)
if(ImGui::BeginChild("ycursors", size, ImGuiChildFlags_None, ImGuiWindowFlags_NoInputs))
{
auto list = ImGui::GetWindowDrawList();
auto& prefs = m_parent->GetSession().GetPreferences();
auto cursor0_color = prefs.GetColor("Appearance.Cursors.cursor_1_color");
auto cursor1_color = prefs.GetColor("Appearance.Cursors.cursor_2_color");
auto fill_color = prefs.GetColor("Appearance.Cursors.cursor_fill_color");
auto font = m_parent->GetFontPref("Appearance.Cursors.label_font");
ImGui::PushFont(font.first, font.second);
float ypos0 = round(YAxisUnitsToYPosition(m_yAxisCursorPositions[0]));
float ypos1 = round(YAxisUnitsToYPosition(m_yAxisCursorPositions[1]));
//Fill between if dual cursor
if(m_yAxisCursorMode == Y_CURSOR_DUAL)
list->AddRectFilled(ImVec2(pos.x, ypos0), ImVec2(pos.x + size.x, ypos1), fill_color);
//First cursor
list->AddLine(ImVec2(pos.x, ypos0), ImVec2(pos.x + size.x, ypos0), cursor0_color, 1);
//Text
//Anchor bottom left at the cursor
auto str = string("Y1: ") + m_yAxisUnit.PrettyPrint(m_yAxisCursorPositions[0]);
auto tsize = ImGui::CalcTextSize(str.c_str());
float padding = 2;
float wrounding = 2;
float textTop = ypos0 - (3*padding + tsize.y);
float plotRight = pos.x + size.x - yAxisWidth;
float textLeft = plotRight - (2*padding + tsize.x);
list->AddRectFilled(
ImVec2(textLeft, textTop - padding ),
ImVec2(plotRight, ypos0 - padding),
ImGui::GetColorU32(ImGuiCol_PopupBg),
wrounding);
list->AddText(
ImVec2(textLeft + padding, textTop + padding),
cursor0_color,
str.c_str());
//Second cursor
if(m_yAxisCursorMode == Y_CURSOR_DUAL)
{
list->AddLine(ImVec2(pos.x, ypos1), ImVec2(pos.x + size.x, ypos1), cursor1_color, 1);
float delta = m_yAxisCursorPositions[0] - m_yAxisCursorPositions[1];
str = string("Y2: ") + m_yAxisUnit.PrettyPrint(m_yAxisCursorPositions[1]) + "\n" +
"ΔY = " + m_yAxisUnit.PrettyPrint(delta);
//Text
tsize = ImGui::CalcTextSize(str.c_str());
textTop = ypos1 - (3*padding + tsize.y);
textLeft = plotRight - (2*padding + tsize.x);
list->AddRectFilled(
ImVec2(textLeft, textTop - padding ),
ImVec2(plotRight, ypos1 - padding),
ImGui::GetColorU32(ImGuiCol_PopupBg),
wrounding);
list->AddText(
ImVec2(textLeft + padding, textTop + padding),
cursor1_color,
str.c_str());
}
//not dragging if we no longer have a second cursor
else if(m_dragState == DRAG_STATE_Y_CURSOR1)
m_dragState = DRAG_STATE_NONE;
//TODO: text for value readouts, in-band power, etc?
ImGui::PopFont();
}
ImGui::EndChild();
//Default help text related to cursors (may change if we're over a cursor)
if(ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows) &&
!m_mouseOverButton && (m_dragState == DRAG_STATE_NONE) )
{
if(m_yAxisCursorMode != Y_CURSOR_NONE)
m_parent->AddStatusHelp("mouse_lmb", "Place first cursor");
if(m_yAxisCursorMode == Y_CURSOR_DUAL)
m_parent->AddStatusHelp("mouse_lmb_drag", "Place second cursor");
}
if( (m_dragState == DRAG_STATE_Y_CURSOR0) || (m_dragState == DRAG_STATE_Y_CURSOR1) )
m_parent->AddStatusHelp("mouse_lmb_drag", "Move cursor");
//Child window doesn't get mouse events (this flag is needed so we can pass mouse events to the WaveformArea's)
//So we have to do all of our interaction processing inside the top level window
DoCursor(0, DRAG_STATE_Y_CURSOR0);
if(m_yAxisCursorMode == Y_CURSOR_DUAL)
DoCursor(1, DRAG_STATE_Y_CURSOR1);
//If not currently dragging, a click places cursor 0 and starts dragging cursor 1 (if enabled)
//Don't process this if a popup is open
if( ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows) &&
(m_dragState == DRAG_STATE_NONE) &&
ImGui::IsMouseClicked(ImGuiMouseButton_Left) &&
!m_mouseOverButton &&
!ImGui::IsPopupOpen("", ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel))
{
auto ypos = ImGui::GetMousePos().y;
m_yAxisCursorPositions[0] = YPositionToYAxisUnits(ypos);
if(m_yAxisCursorMode == Y_CURSOR_DUAL)
{
m_dragState = DRAG_STATE_Y_CURSOR1;
m_yAxisCursorPositions[1] = m_yAxisCursorPositions[0];
}
else
m_dragState = DRAG_STATE_Y_CURSOR0;
}
//Cursor 0 should always be above cursor 1 (if both are enabled).
//If they get swapped, exchange them.
if( (m_yAxisCursorPositions[0] < m_yAxisCursorPositions[1]) && (m_yAxisCursorMode == Y_CURSOR_DUAL) )
{
//Swap the cursors themselves
float tmp = m_yAxisCursorPositions[0];
m_yAxisCursorPositions[0] = m_yAxisCursorPositions[1];
m_yAxisCursorPositions[1] = tmp;
//If dragging one cursor, switch to dragging the other
if(m_dragState == DRAG_STATE_Y_CURSOR0)
m_dragState = DRAG_STATE_Y_CURSOR1;
else if(m_dragState == DRAG_STATE_Y_CURSOR1)
m_dragState = DRAG_STATE_Y_CURSOR0;
}
}
/**
@brief Run interaction processing for dragging a Y axis cursor
*/
void WaveformArea::DoCursor(int iCursor, DragState state)
{
float ypos = round(YAxisUnitsToYPosition(m_yAxisCursorPositions[iCursor]));
float searchRadius = 0.5 * ImGui::GetFontSize();
//Check if the mouse hit us
auto mouse = ImGui::GetMousePos();
if(ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows) && !m_mouseOverButton)
{
if( fabs(mouse.y - ypos) < searchRadius)
{
ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS);
m_parent->AddStatusHelp("mouse_lmb", "");
m_parent->AddStatusHelp("mouse_lmb_drag", "Move cursor");
//Start dragging if clicked
if(ImGui::IsMouseClicked(ImGuiMouseButton_Left))
m_dragState = state;
}
}
//If dragging, move the cursor to track
if(m_dragState == state)
{
if(ImGui::IsMouseReleased(ImGuiMouseButton_Left))
m_dragState = DRAG_STATE_NONE;
m_yAxisCursorPositions[iCursor] = YPositionToYAxisUnits(mouse.y);
}
}
/**
@brief Run the context menu for the main plot area
*/
void WaveformArea::PlotContextMenu()
{
if(ImGui::BeginPopupContextWindow())
{
//Look for markers that might be near our right click location
float lastRightClickPos = m_group->XAxisUnitsToXPosition(m_lastRightClickOffset);
auto& markers = m_parent->GetSession().GetMarkers(GetWaveformTimestamp());
bool hitMarker = false;
size_t selectedMarker = 0;
for(size_t i=0; i<markers.size(); i++)
{
auto& m = markers[i];
float xpos = round(m_group->XAxisUnitsToXPosition(m.m_offset));
float searchRadius = 0.25 * ImGui::GetFontSize();
if(fabs(xpos - lastRightClickPos) < searchRadius)
{
hitMarker = true;
selectedMarker = i;
break;
}
}