Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132938 views
License: OTHER
1
/**
2
* This class represents a digital camera with an autofocus feature.
3
*
4
* @author Markus Iser, Martin Thoma
5
*
6
*/
7
public class Camera {
8
/** This epsilon is used for internal float comparisons. */
9
private static final double EPSILON = 1E-6;
10
11
/** The objective that is currently used by the camera. */
12
private final Objective objective;
13
14
/**
15
* The constructor for objective.
16
*
17
* @param objective
18
* an objective
19
*/
20
public Camera(final Objective objective) {
21
this.objective = objective;
22
}
23
24
/**
25
* Check two doubles for equality.
26
*
27
* @param fp1 first floating point number
28
* @param fp2 second floating point number
29
* @return {@code true} if both floats are equal, otherwise {@code false}
30
*/
31
private boolean fpEquals(final double fp1, final double fp2) {
32
return Math.abs(fp1 - fp2) < EPSILON;
33
}
34
35
/**
36
* Determine if the contrast on the left is higher than on the current
37
* position.
38
*
39
* @param objective the objective you are manipulating
40
* @return {@code true} the contrast on the left of the current position is
41
* higher, otherwise {@code false}
42
*/
43
private boolean isLeftContrastHigher(Objective objective) {
44
double contrast = objective.getContrast();
45
objective.stepLeft();
46
double contrastNew = objective.getContrast();
47
objective.stepRight();
48
49
// check if the contrast - according to our EPSILON - is the same
50
if (fpEquals(contrast, contrastNew)) {
51
return false;
52
}
53
54
return contrastNew > contrast;
55
}
56
57
/**
58
* Adjust objective to get the optimum focus. The optimum focus is
59
* determined by the highest contrast.
60
*/
61
public void autofocus() {
62
boolean stepLeft;
63
double contrast = objective.getContrast();
64
65
// determine direction
66
stepLeft = isLeftContrastHigher(objective);
67
68
// loop until optimum passed
69
while (objective.getContrast() > contrast
70
&& !fpEquals(contrast, objective.getContrast())) {
71
contrast = objective.getContrast();
72
if (stepLeft) {
73
objective.stepLeft();
74
} else {
75
objective.stepRight();
76
}
77
}
78
79
// optional correction-move back
80
if (!fpEquals(contrast, objective.getContrast())) {
81
if (stepLeft) {
82
objective.stepRight();
83
} else {
84
objective.stepLeft();
85
}
86
}
87
}
88
}
89
90
91