/
guider.cpp
executable file
·1541 lines (1318 loc) · 49.4 KB
/
guider.cpp
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
/*
* guider.cpp
* PHD Guiding
*
* Created by Bret McKee
* Copyright (c) 2012 Bret McKee
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS BE
* 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.
*
*/
#include "phd.h"
#include "nudge_lock.h"
#include "comet_tool.h"
#include "guiding_assistant.h"
// un-comment to log star deflections to a file
//#define CAPTURE_DEFLECTIONS
struct DeflectionLogger
{
#ifdef CAPTURE_DEFLECTIONS
wxFFile *m_file;
PHD_Point m_lastPos;
#endif
void Init();
void Uninit();
void Log(const PHD_Point& pos);
};
static DeflectionLogger s_deflectionLogger;
#ifdef CAPTURE_DEFLECTIONS
void DeflectionLogger::Init()
{
m_file = new wxFFile();
wxDateTime now = wxDateTime::UNow();
wxString pathname = Debug.GetLogDir() + PATHSEPSTR + now.Format(_T("star_displacement_%Y-%m-%d_%H%M%S.csv"));
m_file->Open(pathname, "w");
m_lastPos.Invalidate();
}
void DeflectionLogger::Uninit()
{
delete m_file;
m_file = 0;
}
void DeflectionLogger::Log(const PHD_Point& pos)
{
if (m_lastPos.IsValid())
{
PHD_Point mountpt;
pMount->TransformCameraCoordinatesToMountCoordinates(pos - m_lastPos, mountpt);
m_file->Write(wxString::Format("%0.2f,%0.2f\n", mountpt.X, mountpt.Y));
}
else
{
m_file->Write(wxString::Format("DeltaRA, DeltaDec, Scale=%0.2f\n", pFrame->GetCameraPixelScale()));
if (pMount->GetGuidingEnabled())
pFrame->Alert("GUIDING IS ACTIVE!!! Star displacements will be useless!");
}
m_lastPos = pos;
}
#else // CAPTURE_DEFLECTIONS
inline void DeflectionLogger::Init() { }
inline void DeflectionLogger::Uninit() { }
inline void DeflectionLogger::Log(const PHD_Point&) { }
#endif // CAPTURE_DEFLECTIONS
static const int DefaultOverlayMode = OVERLAY_NONE;
static const bool DefaultScaleImage = false;
BEGIN_EVENT_TABLE(Guider, wxWindow)
EVT_PAINT(Guider::OnPaint)
EVT_CLOSE(Guider::OnClose)
EVT_ERASE_BACKGROUND(Guider::OnErase)
END_EVENT_TABLE()
Guider::Guider(wxWindow *parent, int xSize, int ySize) :
wxWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE)
{
m_state = STATE_UNINITIALIZED;
m_scaleFactor = 1.0;
m_displayedImage = new wxImage(XWinSize,YWinSize,true);
m_paused = PAUSE_NONE;
m_starFoundTimestamp = 0;
m_avgDistanceNeedReset = false;
m_lockPosShift.shiftEnabled = false;
m_lockPosShift.shiftRate.SetXY(0., 0.);
m_lockPosShift.shiftUnits = UNIT_ARCSEC;
m_lockPosShift.shiftIsMountCoords = true;
m_lockPosIsSticky = false;
m_forceFullFrame = false;
m_pCurrentImage = new usImage(); // so we always have one
SetOverlayMode(DefaultOverlayMode);
wxPoint center;
center.x = pConfig->Profile.GetInt("/overlay/slit/center.x", 752 / 2);
center.y = pConfig->Profile.GetInt("/overlay/slit/center.y", 580 / 2);
wxSize size;
size.x = pConfig->Profile.GetInt("/overlay/slit/width", 8);
size.y = pConfig->Profile.GetInt("/overlay/slit/height", 100);
int angle = pConfig->Profile.GetInt("/overlay/slit/angle", 0);
SetOverlaySlitCoords(center, size, angle);
m_defectMapPreview = 0;
m_polarAlignCircleRadius = 0.0;
m_polarAlignCircleCorrection = 1.0;
SetBackgroundStyle(wxBG_STYLE_CUSTOM);
SetBackgroundColour(wxColour((unsigned char) 30, (unsigned char) 30,(unsigned char) 30));
s_deflectionLogger.Init();
}
Guider::~Guider(void)
{
delete m_displayedImage;
delete m_pCurrentImage;
s_deflectionLogger.Uninit();
}
void Guider::LoadProfileSettings(void)
{
bool enableFastRecenter = pConfig->Profile.GetBoolean("/guider/FastRecenter", true);
EnableFastRecenter(enableFastRecenter);
bool scaleImage = pConfig->Profile.GetBoolean("/guider/ScaleImage", DefaultScaleImage);
SetScaleImage(scaleImage);
}
PauseType Guider::SetPaused(PauseType pause)
{
Debug.AddLine("Guider::SetPaused(%d)", pause);
PauseType prev = m_paused;
m_paused = pause;
if (prev == PAUSE_FULL && pause != prev)
{
Debug.AddLine("Guider::SetPaused: resetting avg dist filter");
m_avgDistanceNeedReset = true;
}
return prev;
}
void Guider::ForceFullFrame(void)
{
if (!m_forceFullFrame)
{
Debug.AddLine("setting force full frames = true");
m_forceFullFrame = true;
}
}
OVERLAY_MODE Guider::GetOverlayMode(void)
{
return m_overlayMode;
}
bool Guider::SetOverlayMode(int overlayMode)
{
bool bError = false;
try
{
switch (overlayMode)
{
case OVERLAY_NONE:
case OVERLAY_BULLSEYE:
case OVERLAY_GRID_FINE:
case OVERLAY_GRID_COARSE:
case OVERLAY_RADEC:
case OVERLAY_SLIT:
break;
default:
throw ERROR_INFO("invalid overlayMode");
}
m_overlayMode = (OVERLAY_MODE) overlayMode;
}
catch (wxString Msg)
{
POSSIBLY_UNUSED(Msg);
m_overlayMode = OVERLAY_NONE;
bError = true;
}
Refresh();
Update();
return bError;
}
void Guider::GetOverlaySlitCoords(wxPoint *center, wxSize *size, int *angle)
{
*center = m_overlaySlitCoords.center;
*size = m_overlaySlitCoords.size;
*angle = m_overlaySlitCoords.angle;
}
void Guider::SetOverlaySlitCoords(const wxPoint& center, const wxSize& size, int angle)
{
m_overlaySlitCoords.center = center;
m_overlaySlitCoords.size = size;
m_overlaySlitCoords.angle = angle;
pConfig->Profile.SetInt("/overlay/slit/center.x", center.x);
pConfig->Profile.SetInt("/overlay/slit/center.y", center.y);
pConfig->Profile.SetInt("/overlay/slit/width", size.x);
pConfig->Profile.SetInt("/overlay/slit/height", size.y);
pConfig->Profile.SetInt("/overlay/slit/angle", angle);
if (size.GetWidth() > 0 && size.GetHeight() > 0)
{
if (angle != 0)
{
double a = -radians((double)angle);
double s = sin(a);
double c = cos(a);
double cx = (double)center.x;
double cy = (double)center.y;
double x, y;
x = +(double)size.GetWidth() / 2.0;
y = +(double)size.GetHeight() / 2.0;
m_overlaySlitCoords.corners[0].x = cx + (int)floor(x * c - y * s);
m_overlaySlitCoords.corners[0].y = cy + (int)floor(x * s + y * c);
x = -(double)size.GetWidth() / 2.0;
y = +(double)size.GetHeight() / 2.0;
m_overlaySlitCoords.corners[1].x = cx + (int)floor(x * c - y * s);
m_overlaySlitCoords.corners[1].y = cy + (int)floor(x * s + y * c);
x = -(double)size.GetWidth() / 2.0;
y = -(double)size.GetHeight() / 2.0;
m_overlaySlitCoords.corners[2].x = cx + (int)floor(x * c - y * s);
m_overlaySlitCoords.corners[2].y = cy + (int)floor(x * s + y * c);
x = +(double)size.GetWidth() / 2.0;
y = -(double)size.GetHeight() / 2.0;
m_overlaySlitCoords.corners[3].x = cx + (int)floor(x * c - y * s);
m_overlaySlitCoords.corners[3].y = cy + (int)floor(x * s + y * c);
}
else
{
m_overlaySlitCoords.corners[0] = wxPoint(center.x + size.GetWidth() / 2, center.y + size.GetHeight() / 2);
m_overlaySlitCoords.corners[1] = wxPoint(center.x - size.GetWidth() / 2, center.y + size.GetHeight() / 2);
m_overlaySlitCoords.corners[2] = wxPoint(center.x - size.GetWidth() / 2, center.y - size.GetHeight() / 2);
m_overlaySlitCoords.corners[3] = wxPoint(center.x + size.GetWidth() / 2, center.y - size.GetHeight() / 2);
}
m_overlaySlitCoords.corners[4] = m_overlaySlitCoords.corners[0];
}
Refresh();
Update();
}
bool Guider::IsFastRecenterEnabled(void)
{
return m_fastRecenterEnabled;
}
void Guider::EnableFastRecenter(bool enable)
{
m_fastRecenterEnabled = enable;
pConfig->Profile.SetInt("/guider/FastRecenter", m_fastRecenterEnabled);
}
void Guider::SetPolarAlignCircle(const PHD_Point& pt, double radius)
{
m_polarAlignCircleRadius = radius;
m_polarAlignCircleCenter = pt;
}
double Guider::GetPolarAlignCircleCorrection(void)
{
return m_polarAlignCircleCorrection;
}
void Guider::SetPolarAlignCircleCorrection(double val)
{
m_polarAlignCircleCorrection = val;
}
bool Guider::SetScaleImage(bool newScaleValue)
{
bool bError = false;
try
{
m_scaleImage = newScaleValue;
}
catch (wxString Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
}
pConfig->Profile.SetBoolean("/guider/ScaleImage", m_scaleImage);
return bError;
}
bool Guider::GetScaleImage(void)
{
return m_scaleImage;
}
const PHD_Point& Guider::LockPosition()
{
return m_lockPosition;
}
GUIDER_STATE Guider::GetState(void)
{
return m_state;
}
bool Guider::IsCalibratingOrGuiding(void)
{
return m_state >= STATE_CALIBRATING_PRIMARY && m_state <= STATE_GUIDING;
}
void Guider::OnErase(wxEraseEvent& evt)
{
evt.Skip();
}
void Guider::OnClose(wxCloseEvent& evt)
{
Destroy();
}
bool Guider::PaintHelper(wxClientDC& dc, wxMemoryDC& memDC)
{
bool bError = false;
try
{
GUIDER_STATE state = GetState();
GetSize(&XWinSize, &YWinSize);
if (m_pCurrentImage->ImageData)
{
int blevel = m_pCurrentImage->FiltMin;
int wlevel = m_pCurrentImage->FiltMax;
m_pCurrentImage->CopyToImage(&m_displayedImage, blevel, wlevel, pFrame->Stretch_gamma);
}
int imageWidth = m_displayedImage->GetWidth();
int imageHeight = m_displayedImage->GetHeight();
// scale the image if necessary
if (imageWidth != XWinSize || imageHeight != YWinSize)
{
// The image is not the exact right size -- figure out what to do.
double xScaleFactor = imageWidth / (double)XWinSize;
double yScaleFactor = imageHeight / (double)YWinSize;
int newWidth = imageWidth;
int newHeight = imageHeight;
double newScaleFactor = (xScaleFactor > yScaleFactor) ?
xScaleFactor :
yScaleFactor;
// Debug.AddLine("xScaleFactor=%.2f, yScaleFactor=%.2f, newScaleFactor=%.2f", xScaleFactor,
// yScaleFactor, newScaleFactor);
// we rescale the image if:
// - The image is either too big
// - The image is so small that at least one dimension is less
// than half the width of the window or
// - The user has requsted rescaling
if (xScaleFactor > 1.0 || yScaleFactor > 1.0 ||
xScaleFactor < 0.45 || yScaleFactor < 0.45 || m_scaleImage)
{
newWidth /= newScaleFactor;
newHeight /= newScaleFactor;
newScaleFactor = 1.0 / newScaleFactor;
m_scaleFactor = newScaleFactor;
Debug.AddLine("Resizing image to %d,%d", newWidth, newHeight);
if (newWidth > 0 && newHeight > 0)
{
m_displayedImage->Rescale(newWidth, newHeight, wxIMAGE_QUALITY_HIGH);
}
}
else
{
m_scaleFactor = 1.0;
}
}
// important to provide explicit color for r,g,b, optional args to Size().
// If default args are provided wxWidgets performs some expensive histogram
// operations.
wxBitmap DisplayedBitmap(m_displayedImage->Size(wxSize(XWinSize, YWinSize), wxPoint(0, 0), 0, 0, 0));
memDC.SelectObject(DisplayedBitmap);
dc.Blit(0, 0, DisplayedBitmap.GetWidth(), DisplayedBitmap.GetHeight(), &memDC, 0, 0, wxCOPY, false);
int XImgSize = m_displayedImage->GetWidth();
int YImgSize = m_displayedImage->GetHeight();
if (m_overlayMode)
{
dc.SetPen(wxPen(wxColor(200,50,50)));
dc.SetBrush(*wxTRANSPARENT_BRUSH);
switch (m_overlayMode)
{
case OVERLAY_BULLSEYE:
{
int cx = XImgSize / 2;
int cy = YImgSize / 2;
dc.DrawCircle(cx,cy,25);
dc.DrawCircle(cx,cy,50);
dc.DrawCircle(cx,cy,100);
dc.DrawLine(0, cy, XImgSize, cy);
dc.DrawLine(cx, 0, cx, YImgSize);
break;
}
case OVERLAY_GRID_FINE:
case OVERLAY_GRID_COARSE:
{
int i;
int size = (m_overlayMode - 1) * 20;
for (i=size; i<XImgSize; i+=size)
dc.DrawLine(i,0,i,YImgSize);
for (i=size; i<YImgSize; i+=size)
dc.DrawLine(0,i,XImgSize,i);
break;
}
case OVERLAY_RADEC:
{
if (!pMount)
Debug.AddLine("No mount specified for View/RA_Dec overlay"); // Soft error
else
{
double r=30.0;
double xAngle = pMount->IsCalibrated() ? pMount->xAngle() : 0.0;
double cos_angle = cos(xAngle);
double sin_angle = sin(xAngle);
double StarX = CurrentPosition().X;
double StarY = CurrentPosition().Y;
dc.SetPen(wxPen(pFrame->pGraphLog->GetRaOrDxColor(),2,wxPENSTYLE_DOT));
r=15.0;
dc.DrawLine(ROUND(StarX*m_scaleFactor+r*cos_angle),ROUND(StarY*m_scaleFactor+r*sin_angle),
ROUND(StarX*m_scaleFactor-r*cos_angle),ROUND(StarY*m_scaleFactor-r*sin_angle));
dc.SetPen(wxPen(pFrame->pGraphLog->GetDecOrDyColor(),2,wxPENSTYLE_DOT));
double yAngle = pMount->IsCalibrated() ? pMount->yAngle() : M_PI / 2.0;
cos_angle = cos(yAngle);
sin_angle = sin(yAngle);
dc.DrawLine(ROUND(StarX*m_scaleFactor+r*cos_angle),ROUND(StarY*m_scaleFactor+r*sin_angle),
ROUND(StarX*m_scaleFactor-r*cos_angle),ROUND(StarY*m_scaleFactor-r*sin_angle));
wxGraphicsContext *gc = wxGraphicsContext::Create(dc);
gc->SetPen(wxPen(pFrame->pGraphLog->GetRaOrDxColor(),1,wxPENSTYLE_DOT ));
wxGraphicsPath path = gc->CreatePath();
int i;
double step = (double) YImgSize / 10.0;
double MidX = (double) XImgSize / 2.0;
double MidY = (double) YImgSize / 2.0;
gc->Rotate(xAngle);
gc->GetTransform().TransformPoint(&MidX, &MidY);
gc->Rotate(-xAngle);
gc->Translate((double) XImgSize / 2.0 - MidX, (double) YImgSize / 2.0 - MidY);
gc->Rotate(xAngle);
for (i=-2; i<12; i++) {
gc->StrokeLine(0.0,step * (double) i,
(double) XImgSize, step * (double) i);
}
MidX = (double) XImgSize / 2.0;
MidY = (double) YImgSize / 2.0;
gc->Rotate(-xAngle);
gc->Rotate(yAngle);
gc->GetTransform().TransformPoint(&MidX, &MidY);
gc->Rotate(-yAngle);
gc->Translate((double) XImgSize / 2.0 - MidX, (double) YImgSize / 2.0 - MidY);
gc->Rotate(yAngle);
gc->SetPen(wxPen(pFrame->pGraphLog->GetDecOrDyColor(),1,wxPENSTYLE_DOT ));
for (i=-2; i<12; i++) {
gc->StrokeLine(0.0,step * (double) i,
(double) XImgSize, step * (double) i);
}
delete gc;
}
break;
}
case OVERLAY_SLIT:
if (m_overlaySlitCoords.size.GetWidth() > 0 && m_overlaySlitCoords.size.GetHeight() > 0)
{
if (m_scaleFactor == 1.0)
{
dc.DrawLines(5, m_overlaySlitCoords.corners);
}
else
{
wxPoint pt[5];
for (int i = 0; i < 5; i++)
{
pt[i].x = (int) floor(m_overlaySlitCoords.corners[i].x * m_scaleFactor);
pt[i].y = (int) floor(m_overlaySlitCoords.corners[i].y * m_scaleFactor);
}
dc.DrawLines(5, pt);
}
}
break;
case OVERLAY_NONE:
break;
}
}
if (m_defectMapPreview)
{
dc.SetPen(wxPen(wxColor(255, 0, 0), 1, wxSOLID));
for (DefectMap::const_iterator it = m_defectMapPreview->begin(); it != m_defectMapPreview->end(); ++it)
{
const wxPoint& pt = *it;
dc.DrawPoint((int)(pt.x * m_scaleFactor), (int)(pt.y * m_scaleFactor));
}
}
// draw the lockpoint of there is one
if (state > STATE_SELECTED)
{
double LockX = LockPosition().X;
double LockY = LockPosition().Y;
switch (state)
{
case STATE_UNINITIALIZED:
case STATE_SELECTING:
case STATE_SELECTED:
case STATE_STOP:
break;
case STATE_CALIBRATING_PRIMARY:
case STATE_CALIBRATING_SECONDARY:
dc.SetPen(wxPen(wxColor(255,255,0),1, wxDOT));
break;
case STATE_CALIBRATED:
case STATE_GUIDING:
dc.SetPen(wxPen(wxColor(0,255,0)));
break;
}
dc.DrawLine(0, int(LockY * m_scaleFactor), XImgSize, int(LockY * m_scaleFactor));
dc.DrawLine(int(LockX * m_scaleFactor), 0, int(LockX * m_scaleFactor), YImgSize);
}
// draw a polar alignment circle
if (m_polarAlignCircleRadius)
{
dc.SetBrush(*wxTRANSPARENT_BRUSH);
wxPenStyle penStyle = m_polarAlignCircleCorrection == 1.0 ? wxPENSTYLE_DOT : wxPENSTYLE_SOLID;
dc.SetPen(wxPen(wxColor(255,0,255), 1, penStyle));
int radius = ROUND(m_polarAlignCircleRadius * m_polarAlignCircleCorrection * m_scaleFactor);
dc.DrawCircle(m_polarAlignCircleCenter.X * m_scaleFactor,
m_polarAlignCircleCenter.Y * m_scaleFactor, radius);
}
}
catch (wxString Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
}
return bError;
}
void Guider::UpdateImageDisplay(usImage *pImage)
{
if (!pImage)
{
pImage = m_pCurrentImage;
}
Debug.AddLine("UpdateImageDisplay: Size=(%d,%d) min=%d, max=%d, FiltMin=%d, FiltMax=%d",
pImage->Size.x, pImage->Size.y, pImage->Min, pImage->Max, pImage->FiltMin, pImage->FiltMax);
Refresh();
Update();
}
void Guider::SetDefectMapPreview(const DefectMap *defectMap)
{
m_defectMapPreview = defectMap;
Refresh();
Update();
}
bool Guider::SaveCurrentImage(const wxString& fileName)
{
return m_pCurrentImage->Save(fileName);
}
void Guider::InvalidateLockPosition(void)
{
m_lockPosition.Invalidate();
EvtServer.NotifyLockPositionLost();
NudgeLockTool::UpdateNudgeLockControls();
}
bool Guider::SetLockPosition(const PHD_Point& position)
{
bool bError = false;
try
{
if (!position.IsValid())
{
throw ERROR_INFO("Point is not valid");
}
double x = position.X;
double y = position.Y;
Debug.AddLine(wxString::Format("setting lock position to (%.2f, %.2f)", x, y));
if ((x < 0.0) || (x >= m_pCurrentImage->Size.x))
{
throw ERROR_INFO("invalid x value");
}
if ((y < 0.0) || (y >= m_pCurrentImage->Size.y))
{
throw ERROR_INFO("invalid y value");
}
if (!m_lockPosition.IsValid() || position.X != m_lockPosition.X || position.Y != m_lockPosition.Y)
{
EvtServer.NotifySetLockPosition(position);
if (m_state == STATE_GUIDING)
GuideLog.NotifySetLockPosition(this);
NudgeLockTool::UpdateNudgeLockControls();
}
m_lockPosition.SetXY(x, y);
}
catch (wxString Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
}
return bError;
}
bool Guider::SetLockPosToStarAtPosition(const PHD_Point& starPosHint)
{
bool error = SetCurrentPosition(m_pCurrentImage, starPosHint);
if (!error && CurrentPosition().IsValid())
{
SetLockPosition(CurrentPosition());
}
return error;
}
MOVE_LOCK_RESULT Guider::MoveLockPosition(const PHD_Point& mountDelta)
{
MOVE_LOCK_RESULT result = MOVE_LOCK_OK;
try
{
if (!mountDelta.IsValid())
{
throw ERROR_INFO("Point is not valid");
}
if (!pMount || !pMount->IsCalibrated())
{
throw ERROR_INFO("No mount");
}
PHD_Point cameraDelta;
if (pMount->TransformMountCoordinatesToCameraCoordinates(mountDelta, cameraDelta))
{
throw ERROR_INFO("Transform failed");
}
PHD_Point newLockPosition = m_lockPosition + cameraDelta;
if (!IsValidLockPosition(newLockPosition))
{
return MOVE_LOCK_REJECTED;
}
if (SetLockPosition(newLockPosition))
{
throw ERROR_INFO("SetLockPosition failed");
}
// update average distance right away so GetCurrentDistance reflects the increased distance from the dither
m_avgDistance += cameraDelta.Distance();
if (IsFastRecenterEnabled())
{
m_ditherRecenterRemaining.SetXY(fabs(mountDelta.X), fabs(mountDelta.Y));
m_ditherRecenterDir.x = mountDelta.X < 0.0 ? 1 : -1;
m_ditherRecenterDir.y = mountDelta.Y < 0.0 ? 1 : -1;
double f = (double) GetMaxMovePixels() / m_ditherRecenterRemaining.Distance();
m_ditherRecenterStep.SetXY(f * m_ditherRecenterRemaining.X, f * m_ditherRecenterRemaining.Y);
}
}
catch (wxString Msg)
{
POSSIBLY_UNUSED(Msg);
result = MOVE_LOCK_ERROR;
}
return result;
}
void Guider::SetState(GUIDER_STATE newState)
{
try
{
Debug.Write(wxString::Format("Changing from state %d to %d\n", m_state, newState));
if (newState == STATE_STOP)
{
// we are going to stop looping exposures. We should put
// ourselves into a good state to restart looping later
switch (m_state)
{
case STATE_UNINITIALIZED:
case STATE_SELECTING:
case STATE_SELECTED:
newState = m_state;
break;
case STATE_CALIBRATING_PRIMARY:
case STATE_CALIBRATING_SECONDARY:
// because we have done some moving here, we need to just
// start over...
newState = STATE_UNINITIALIZED;
break;
case STATE_CALIBRATED:
case STATE_GUIDING:
newState = STATE_SELECTED;
break;
case STATE_STOP:
break;
}
if (pMount && pMount->GuidingCeases())
{
throw ERROR_INFO("GuidingCeases() failed");
}
}
assert(newState != STATE_STOP);
if (newState > m_state + 1)
{
Debug.AddLine("Cannot transition from %d to newState=%d", m_state, newState);
throw ERROR_INFO("Illegal state transition");
}
GUIDER_STATE requestedState = newState;
switch (requestedState)
{
case STATE_UNINITIALIZED:
InvalidateLockPosition();
InvalidateCurrentPosition();
newState = STATE_SELECTING;
break;
case STATE_SELECTED:
if (pMount)
{
Debug.AddLine("Guider::SetState: clearing mount guide algorithm history");
pMount->ClearHistory();
}
break;
case STATE_CALIBRATING_PRIMARY:
if (!pMount->IsCalibrated())
{
if (pMount->BeginCalibration(CurrentPosition()))
{
newState = STATE_UNINITIALIZED;
Debug.Write(ERROR_INFO("pMount->BeginCalibration failed"));
}
else
{
GuideLog.StartCalibration(pMount);
EvtServer.NotifyStartCalibration(pMount);
}
break;
}
// fall through
case STATE_CALIBRATING_SECONDARY:
if (!pSecondaryMount || !pSecondaryMount->IsConnected())
{
newState = STATE_CALIBRATED;
}
else if (!pSecondaryMount->IsCalibrated())
{
if (pSecondaryMount->BeginCalibration(CurrentPosition()))
{
newState = STATE_UNINITIALIZED;
Debug.Write(ERROR_INFO("pSecondaryMount->BeginCalibration failed"));
}
else
{
GuideLog.StartCalibration(pSecondaryMount);
EvtServer.NotifyStartCalibration(pSecondaryMount);
}
}
break;
case STATE_GUIDING:
assert(pMount);
m_ditherRecenterRemaining.Invalidate(); // reset dither fast recenter state
pMount->AdjustCalibrationForScopePointing();
if (pSecondaryMount)
{
pSecondaryMount->AdjustCalibrationForScopePointing();
}
if (m_lockPosition.IsValid() && m_lockPosIsSticky)
{
Debug.AddLine("keeping sticky lock position");
}
else
{
SetLockPosition(CurrentPosition());
}
break;
case STATE_SELECTING:
case STATE_CALIBRATED:
case STATE_STOP:
break;
}
if (newState >= requestedState)
{
m_state = newState;
}
else
{
SetState(newState);
}
}
catch (wxString Msg)
{
POSSIBLY_UNUSED(Msg);
}
}
void Guider::UpdateCurrentDistance(double distance)
{
m_starFoundTimestamp = wxDateTime::GetTimeNow();
if (IsGuiding())
{
// update moving average distance
static double const alpha = .3; // moderately high weighting for latest sample
m_avgDistance += alpha * (distance - m_avgDistance);
}
else
{
// not yet guiding, reinitialize average distance
m_avgDistance = distance;
}
if (m_avgDistanceNeedReset)
{
// avg distance history invalidated
m_avgDistance = distance;
m_avgDistanceNeedReset = false;
}
}
double Guider::CurrentError(void)
{
enum { THRESHOLD_SECONDS = 20 };
static double const LARGE_DISTANCE = 100.0;
if (!m_starFoundTimestamp)
{
return LARGE_DISTANCE;
}
if (wxDateTime::GetTimeNow() - m_starFoundTimestamp > THRESHOLD_SECONDS)
{
return LARGE_DISTANCE;
}
return m_avgDistance;
}
usImage *Guider::CurrentImage(void)
{
return m_pCurrentImage;
}
wxImage *Guider::DisplayedImage(void)
{
return m_displayedImage;
}
double Guider::ScaleFactor(void)
{
return m_scaleFactor;
}
void Guider::StartGuiding(void)
{
// we set the state to calibrating. The state machine will
// automatically move from calibrating->calibrated->guiding
// when it can
SetState(STATE_CALIBRATING_PRIMARY);
}
void Guider::StopGuiding(void)
{
// first, send a notification that we stopped
switch (m_state)
{
case STATE_UNINITIALIZED:
case STATE_SELECTING:
case STATE_SELECTED:
EvtServer.NotifyLoopingStopped();
break;
case STATE_CALIBRATING_PRIMARY:
case STATE_CALIBRATING_SECONDARY:
case STATE_CALIBRATED:
EvtServer.NotifyCalibrationFailed(m_state == STATE_CALIBRATING_SECONDARY ? pSecondaryMount : pMount,
_("Calibration manually stopped"));
break;
case STATE_GUIDING:
EvtServer.NotifyGuidingStopped();
GuideLog.StopGuiding();
break;
case STATE_STOP:
break;
}
SetState(STATE_STOP);
}
void Guider::Reset(bool fullReset)
{
SetState(STATE_UNINITIALIZED);
if (fullReset)
{
InvalidateCurrentPosition(true);
}
}
/************* A new image is ready ************************/